-
Notifications
You must be signed in to change notification settings - Fork 268
/
objc-runtime-new.mm
7127 lines (5880 loc) · 221 KB
/
objc-runtime-new.mm
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-2009 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-file.h"
#include "objc-cache.h"
#include <Block.h>
#include <objc/message.h>
#include <mach/shared_region.h>
#define newprotocol(p) ((protocol_t *)p)
static void disableTaggedPointers();
static void detach_class(Class cls, BOOL isMeta);
static void free_class(Class cls);
static Class setSuperclass(Class cls, Class newSuper);
static Class realizeClass(Class cls);
static method_t *getMethodNoSuper_nolock(Class cls, SEL sel);
static method_t *getMethod_nolock(Class cls, SEL sel);
static IMP _method_getImplementation(method_t *m);
static IMP addMethod(Class cls, SEL name, IMP imp, const char *types, BOOL replace);
static NXHashTable *realizedClasses(void);
static bool isRRSelector(SEL sel);
static bool isAWZSelector(SEL sel);
static bool methodListImplementsRR(const method_list_t *mlist);
static bool methodListImplementsAWZ(const method_list_t *mlist);
static void updateCustomRR_AWZ(Class cls, method_t *meth);
static method_t *search_method_list(const method_list_t *mlist, SEL sel);
#if SUPPORT_FIXUP
static void fixupMessageRef(message_ref_t *msg);
#endif
static bool MetaclassNSObjectAWZSwizzled;
static bool ClassNSObjectRRSwizzled;
id objc_noop_imp(id self, SEL _cmd __unused) {
return self;
}
/***********************************************************************
* Lock management
**********************************************************************/
rwlock_t runtimeLock;
rwlock_t selLock;
mutex_t cacheUpdateLock = MUTEX_INITIALIZER;
recursive_mutex_t loadMethodLock = RECURSIVE_MUTEX_INITIALIZER;
#if SUPPORT_QOS_HACK
pthread_priority_t BackgroundPriority = 0;
pthread_priority_t MainPriority = 0;
# if !NDEBUG
static __unused void destroyQOSKey(void *arg) {
_objc_fatal("QoS override level at thread exit is %zu instead of zero",
(size_t)(uintptr_t)arg);
}
# endif
#endif
void lock_init(void)
{
rwlock_init(&selLock);
rwlock_init(&runtimeLock);
recursive_mutex_init(&loadMethodLock);
#if SUPPORT_QOS_HACK
BackgroundPriority = _pthread_qos_class_encode(QOS_CLASS_BACKGROUND, 0, 0);
MainPriority = _pthread_qos_class_encode(qos_class_main(), 0, 0);
# if !NDEBUG
pthread_key_init_np(QOS_KEY, &destroyQOSKey);
# endif
#endif
}
/***********************************************************************
* Non-pointer isa decoding
**********************************************************************/
#if SUPPORT_NONPOINTER_ISA
const uintptr_t objc_debug_isa_class_mask = ISA_MASK;
const uintptr_t objc_debug_isa_magic_mask = ISA_MAGIC_MASK;
const uintptr_t objc_debug_isa_magic_value = ISA_MAGIC_VALUE;
// die if masks overlap
STATIC_ASSERT((ISA_MASK & ISA_MAGIC_MASK) == 0);
// die if magic is wrong
STATIC_ASSERT((~ISA_MAGIC_MASK & ISA_MAGIC_VALUE) == 0);
// die if virtual address space bound goes up
STATIC_ASSERT((~ISA_MASK & MACH_VM_MAX_ADDRESS) == 0);
#else
// These variables exist but enforce pointer alignment only.
const uintptr_t objc_debug_isa_class_mask = (~WORD_MASK);
const uintptr_t objc_debug_isa_magic_mask = WORD_MASK;
const uintptr_t objc_debug_isa_magic_value = 0;
#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 { \
class_rw_t *_data = _cls->data(); \
const method_list_t *_mlist; \
if (_data->method_lists) { \
if (_data->flags & RW_METHOD_ARRAY) { \
method_list_t **_mlistp; \
for (_mlistp=_data->method_lists; _mlistp[0]; _mlistp++){ \
_mlist = _mlistp[0]; \
code \
} \
} else { \
_mlist = _data->method_list; \
code \
} \
} \
} while (0)
// As above, but skips the class's base method list.
#define FOREACH_CATEGORY_METHOD_LIST(_mlist, _cls, code) \
do { \
class_rw_t *_data = _cls->data(); \
const method_list_t *_mlist; \
if (_data->method_lists) { \
if (_data->flags & RW_METHOD_ARRAY) { \
if (_data->ro->baseMethods) { \
/* has base methods: use all mlists except the last */ \
method_list_t **_mlistp; \
for (_mlistp=_data->method_lists; _mlistp[0] && _mlistp[1]; _mlistp++){ \
_mlist = _mlistp[0]; \
code \
} \
} else { \
/* no base methods: use all mlists including the last */ \
method_list_t **_mlistp; \
for (_mlistp=_data->method_lists; _mlistp[0]; _mlistp++){ \
_mlist = _mlistp[0]; \
code \
} \
} \
} else if (!_data->ro->baseMethods) { \
/* no base methods: use all mlists including the last */ \
_mlist = _data->method_list; \
code \
} \
} \
} while (0)
/*
Low two bits of mlist->entsize is used as the fixed-up marker.
PREOPTIMIZED VERSION:
Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted).
(Protocol method lists are not sorted because of their extra parallel data)
Runtime fixed-up method lists get 3.
UN-PREOPTIMIZED VERSION:
Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted)
Shared cache's sorting and uniquing are not trusted, but do affect the
location of the selector name string.
Runtime fixed-up method lists get 2.
*/
static uint32_t fixed_up_method_list = 3;
void
disableSharedCacheOptimizations(void)
{
fixed_up_method_list = 2;
}
static bool
isMethodListFixedUp(const method_list_t *mlist)
{
return (mlist->entsize_NEVER_USE & 3) == fixed_up_method_list;
}
static const char *sel_cname(SEL sel)
{
return (const char *)(void *)sel;
}
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(property_t);
}
*/
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 & ~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 &mlist->get(i);
}
static uint32_t method_list_count(const method_list_t *mlist)
{
return mlist ? mlist->count : 0;
}
static void method_list_swap(method_list_t *mlist, uint32_t i, uint32_t j)
{
size_t entsize = method_list_entsize(mlist);
char temp[entsize];
memcpy(temp, method_list_nth(mlist, i), entsize);
memcpy(method_list_nth(mlist, i), method_list_nth(mlist, j), entsize);
memcpy(method_list_nth(mlist, j), temp, entsize);
}
static uint32_t method_list_index(const method_list_t *mlist,const method_t *m)
{
uint32_t i = (uint32_t)(((uintptr_t)m - (uintptr_t)mlist) / method_list_entsize(mlist));
assert(i < mlist->count);
return i;
}
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 nil;
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 nil;
return method_list_nth(cmlist, i);
}
static property_t *
property_list_nth(const property_list_t *plist, uint32_t i)
{
return (property_t *)(i*plist->entsize + (char *)&plist->first);
}
// fixme don't chain property lists
typedef struct chained_property_list {
struct chained_property_list *next;
uint32_t count;
property_t list[0]; // variable-size
} chained_property_list;
static void try_free(const void *p)
{
if (p && malloc_size(p)) free((void *)p);
}
static Class
alloc_class_for_subclass(Class supercls, size_t extraBytes)
{
if (!supercls || !supercls->isSwift()) {
return _calloc_class(sizeof(objc_class) + extraBytes);
}
// Superclass is a Swift class. New subclass must duplicate its extra bits.
// Allocate the new class, with space for super's prefix and suffix
// and self's extraBytes.
swift_class_t *swiftSupercls = (swift_class_t *)supercls;
size_t superSize = swiftSupercls->classSize;
void *superBits = swiftSupercls->baseAddress();
void *bits = _malloc_internal(superSize + extraBytes);
// Copy all of the superclass's data to the new class.
memcpy(bits, superBits, superSize);
// Erase the objc data and the Swift description in the new class.
swift_class_t *swcls = (swift_class_t *)
((uint8_t *)bits + swiftSupercls->classAddressOffset);
bzero(swcls, sizeof(objc_class));
swcls->description = nil;
// Mark this class as Swift-enhanced.
swcls->bits.setIsSwift();
return (Class)swcls;
}
/***********************************************************************
* object_getIndexedIvars.
**********************************************************************/
void *object_getIndexedIvars(id obj)
{
uint8_t *base = (uint8_t *)obj;
if (!obj) return nil;
if (obj->isTaggedPointer()) return nil;
if (!obj->isClass()) return base + obj->ISA()->alignedInstanceSize();
Class cls = (Class)obj;
if (!cls->isSwift()) return base + sizeof(objc_class);
swift_class_t *swcls = (swift_class_t *)cls;
return base - swcls->classAddressOffset + word_align(swcls->classSize);
}
/***********************************************************************
* 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 = (class_ro_t *)
_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 = nil;
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 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 instead
NXMapTable *cats = unattachedCategories();
category_list *list;
list = (category_list *)NXMapGet(cats, cls);
if (!list) {
list = (category_list *)
_calloc_internal(sizeof(*list) + sizeof(list->list[0]), 1);
} else {
list = (category_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 cls)
{
rwlock_assert_writing(&runtimeLock);
// DO NOT use cat->cls! cls may be cat->cls->isa instead
NXMapTable *cats = unattachedCategories();
category_list *list;
list = (category_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;
}
}
}
/***********************************************************************
* unattachedCategoriesForClass
* Returns the list of unattached categories for a class, and
* deletes them from the list.
* The result must be freed by the caller.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static category_list *unattachedCategoriesForClass(Class cls)
{
rwlock_assert_writing(&runtimeLock);
return (category_list *)NXMapRemove(unattachedCategories(), cls);
}
/***********************************************************************
* classNSObject
* Returns class NSObject.
* Locking: none
**********************************************************************/
static Class classNSObject(void)
{
extern objc_class OBJC_CLASS_$_NSObject;
return (Class)&OBJC_CLASS_$_NSObject;
}
/***********************************************************************
* printReplacements
* Implementation of PrintReplacedMethods / OBJC_PRINT_REPLACED_METHODS.
* Warn about methods from cats that override other methods in cats or cls.
* Assumes no methods from cats have been added to cls yet.
**********************************************************************/
static void printReplacements(Class cls, category_list *cats)
{
uint32_t c;
BOOL isMeta = cls->isMetaClass();
if (!cats) return;
// Newest categories are LAST in cats
// Later categories override earlier ones.
for (c = 0; c < cats->count; c++) {
category_t *cat = cats->list[c].cat;
uint32_t cmCount = cat_method_count(cat, isMeta);
uint32_t m;
for (m = 0; m < cmCount; m++) {
uint32_t c2, m2;
method_t *meth2 = nil;
method_t *meth = cat_method_nth(cat, isMeta, m);
SEL s = sel_registerName(sel_cname(meth->name));
// Don't warn about GC-ignored selectors
if (ignoreSelector(s)) continue;
// Look for method in earlier categories
for (c2 = 0; c2 < c; c2++) {
category_t *cat2 = cats->list[c2].cat;
uint32_t cm2Count = cat_method_count(cat2, isMeta);
for (m2 = 0; m2 < cm2Count; m2++) {
meth2 = cat_method_nth(cat2, isMeta, m2);
SEL s2 = sel_registerName(sel_cname(meth2->name));
if (s == s2) goto whine;
}
}
// Look for method in cls
FOREACH_METHOD_LIST(mlist, cls, {
for (m2 = 0; m2 < mlist->count; m2++) {
meth2 = method_list_nth(mlist, m2);
SEL s2 = sel_registerName(sel_cname(meth2->name));
if (s == s2) goto whine;
}
});
// Didn't find any override.
continue;
whine:
// Found an override.
logReplacedMethod(cls->nameForLogging(), s,
cls->isMetaClass(), cat->name,
_method_getImplementation(meth2),
_method_getImplementation(meth));
}
}
}
static BOOL isBundleClass(Class cls)
{
return (cls->data()->ro->flags & RO_FROM_BUNDLE) ? YES : NO;
}
static method_list_t *
fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort)
{
rwlock_assert_writing(&runtimeLock);
assert(!isMethodListFixedUp(mlist));
mlist = (method_list_t *)
_memdup_internal(mlist, method_list_size(mlist));
// fixme lock less in attachMethodLists ?
sel_lock();
// Unique selectors in list.
uint32_t m;
for (m = 0; m < mlist->count; m++) {
method_t *meth = method_list_nth(mlist, m);
const char *name = sel_cname(meth->name);
SEL sel = sel_registerNameNoLock(name, bundleCopy);
meth->name = sel;
if (ignoreSelector(sel)) {
meth->imp = (IMP)&_objc_ignored_method;
}
}
sel_unlock();
// Sort by selector address.
if (sort) {
method_t::SortBySELAddress sorter;
std::stable_sort(mlist->begin(), mlist->end(), sorter);
}
// Mark method list as uniqued and sorted
setMethodListFixedUp(mlist);
return mlist;
}
static void
attachMethodLists(Class cls, method_list_t **addedLists, int addedCount,
bool baseMethods, bool methodsFromBundle,
bool flushCaches)
{
rwlock_assert_writing(&runtimeLock);
// Don't scan redundantly
bool scanForCustomRR = !UseGC && !cls->hasCustomRR();
bool scanForCustomAWZ = !UseGC && !cls->hasCustomAWZ();
// There exist RR/AWZ special cases for some class's base methods.
// But this code should never need to scan base methods for RR/AWZ:
// default RR/AWZ cannot be set before setInitialized().
// Therefore we need not handle any special cases here.
if (baseMethods) {
assert(!scanForCustomRR && !scanForCustomAWZ);
}
// Method list array is nil-terminated.
// Some elements of lists are nil; we must filter them out.
method_list_t *oldBuf[2];
method_list_t **oldLists;
int oldCount = 0;
if (cls->data()->flags & RW_METHOD_ARRAY) {
oldLists = cls->data()->method_lists;
} else {
oldBuf[0] = cls->data()->method_list;
oldBuf[1] = nil;
oldLists = oldBuf;
}
if (oldLists) {
while (oldLists[oldCount]) oldCount++;
}
int newCount = oldCount;
for (int i = 0; i < addedCount; i++) {
if (addedLists[i]) newCount++; // only non-nil entries get added
}
method_list_t *newBuf[2];
method_list_t **newLists;
if (newCount > 1) {
newLists = (method_list_t **)
_malloc_internal((1 + newCount) * sizeof(*newLists));
} else {
newLists = newBuf;
}
// Add method lists to array.
// Reallocate un-fixed method lists.
// The new methods are PREPENDED to the method list array.
newCount = 0;
int i;
for (i = 0; i < addedCount; i++) {
method_list_t *mlist = addedLists[i];
if (!mlist) continue;
// Fixup selectors if necessary
if (!isMethodListFixedUp(mlist)) {
mlist = fixupMethodList(mlist, methodsFromBundle, true/*sort*/);
}
// Scan for method implementations tracked by the class's flags
if (scanForCustomRR && methodListImplementsRR(mlist)) {
cls->setHasCustomRR();
scanForCustomRR = false;
}
if (scanForCustomAWZ && methodListImplementsAWZ(mlist)) {
cls->setHasCustomAWZ();
scanForCustomAWZ = false;
}
// Update method caches
if (flushCaches) {
cache_eraseMethods(cls, mlist);
}
// Fill method list array
newLists[newCount++] = mlist;
}
// Copy old methods to the method list array
for (i = 0; i < oldCount; i++) {
newLists[newCount++] = oldLists[i];
}
if (oldLists && oldLists != oldBuf) free(oldLists);
// nil-terminate
newLists[newCount] = nil;
if (newCount > 1) {
assert(newLists != newBuf);
cls->data()->method_lists = newLists;
cls->setInfo(RW_METHOD_ARRAY);
} else {
assert(newLists == newBuf);
cls->data()->method_list = newLists[0];
assert(!(cls->data()->flags & RW_METHOD_ARRAY));
}
}
static void
attachCategoryMethods(Class cls, category_list *cats, bool flushCaches)
{
if (!cats) return;
if (PrintReplacedMethods) printReplacements(cls, cats);
bool isMeta = cls->isMetaClass();
method_list_t **mlists = (method_list_t **)
_malloc_internal(cats->count * sizeof(*mlists));
// Count backwards through cats to get newest categories first
int mcount = 0;
int i = cats->count;
BOOL fromBundle = NO;
while (i--) {
method_list_t *mlist = cat_method_list(cats->list[i].cat, isMeta);
if (mlist) {
mlists[mcount++] = mlist;
fromBundle |= cats->list[i].fromBundle;
}
}
attachMethodLists(cls, mlists, mcount, NO, fromBundle, flushCaches);
_free_internal(mlists);
}
static chained_property_list *
buildPropertyList(const property_list_t *plist, category_list *cats, BOOL isMeta)
{
chained_property_list *newlist;
uint32_t count = 0;
uint32_t p, c;
// Count properties in all lists.
if (plist) count = plist->count;
if (cats) {
for (c = 0; c < cats->count; c++) {
category_t *cat = cats->list[c].cat;
/*
if (isMeta && cat->classProperties) {
count += cat->classProperties->count;
}
else*/
if (!isMeta && cat->instanceProperties) {
count += cat->instanceProperties->count;
}
}
}
if (count == 0) return nil;
// Allocate new list.
newlist = (chained_property_list *)
_malloc_internal(sizeof(*newlist) + count * sizeof(property_t));
newlist->count = 0;
newlist->next = nil;
// Copy properties; newest categories first, then ordinary properties
if (cats) {
c = cats->count;
while (c--) {
property_list_t *cplist;
category_t *cat = cats->list[c].cat;
/*
if (isMeta) {
cplist = cat->classProperties;
} else */
{
cplist = cat->instanceProperties;
}
if (cplist) {
for (p = 0; p < cplist->count; p++) {
newlist->list[newlist->count++] =
*property_list_nth(cplist, p);
}
}
}
}
if (plist) {
for (p = 0; p < plist->count; p++) {
newlist->list[newlist->count++] = *property_list_nth(plist, p);
}
}
assert(newlist->count == count);
return newlist;
}
static const protocol_list_t **
buildProtocolList(category_list *cats, const protocol_list_t *base,
const protocol_list_t **protos)
{
const protocol_list_t **p, **newp;
const protocol_list_t **newprotos;
unsigned int count = 0;
unsigned int i;
// count protocol list in base
if (base) count++;
// count protocol lists in cats
if (cats) for (i = 0; i < cats->count; i++) {
category_t *cat = cats->list[i].cat;
if (cat->protocols) count++;
}
// no base or category protocols? return existing protocols unchanged
if (count == 0) return protos;
// count protocol lists in protos
for (p = protos; p && *p; p++) {
count++;
}
if (count == 0) return nil;
newprotos = (const protocol_list_t **)
_malloc_internal((count+1) * sizeof(protocol_list_t *));
newp = newprotos;
if (base) {
*newp++ = base;
}
for (p = protos; p && *p; p++) {
*newp++ = *p;
}
if (cats) for (i = 0; i < cats->count; i++) {
category_t *cat = cats->list[i].cat;
if (cat->protocols) {
*newp++ = cat->protocols;
}
}
*newp = nil;
return newprotos;
}
/***********************************************************************
* methodizeClass
* Fixes up cls's method list, protocol list, and property list.
* Attaches any outstanding categories.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static void methodizeClass(Class cls)
{
category_list *cats;
BOOL isMeta;
rwlock_assert_writing(&runtimeLock);
isMeta = cls->isMetaClass();
// Methodizing for the first time
if (PrintConnecting) {
_objc_inform("CLASS: methodizing class '%s' %s",
cls->nameForLogging(), isMeta ? "(meta)" : "");
}
// Build method and protocol and property lists.
// Include methods and protocols and properties from categories, if any
attachMethodLists(cls, (method_list_t **)&cls->data()->ro->baseMethods, 1,
YES, isBundleClass(cls), NO);
// Root classes get bonus method implementations if they don't have
// them already. These apply before category replacements.
if (cls->isRootMetaclass()) {
// root metaclass
addMethod(cls, SEL_initialize, (IMP)&objc_noop_imp, "", NO);
}
cats = unattachedCategoriesForClass(cls);
attachCategoryMethods(cls, cats, NO);
if (cats || cls->data()->ro->baseProperties) {
cls->data()->properties =
buildPropertyList(cls->data()->ro->baseProperties, cats, isMeta);
}
if (cats || cls->data()->ro->baseProtocols) {
cls->data()->protocols =
buildProtocolList(cats, cls->data()->ro->baseProtocols, nil);
}
if (PrintConnecting) {
uint32_t i;
if (cats) {
for (i = 0; i < cats->count; i++) {
_objc_inform("CLASS: attached category %c%s(%s)",
isMeta ? '+' : '-',
cls->nameForLogging(), cats->list[i].cat->name);
}
}
}
if (cats) _free_internal(cats);
#ifndef NDEBUG
// Debug: sanity-check all SELs; log method list contents
FOREACH_METHOD_LIST(mlist, cls, {
method_list_t::method_iterator iter = mlist->begin();
method_list_t::method_iterator end = mlist->end();
for ( ; iter != end; ++iter) {
if (PrintConnecting) {
_objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-',
cls->nameForLogging(), sel_getName(iter->name));
}
assert(ignoreSelector(iter->name) || sel_registerName(sel_getName(iter->name))==iter->name);
}
});
#endif
}
/***********************************************************************
* remethodizeClass
* Attach outstanding categories to an existing class.
* Fixes up cls's method list, protocol list, and property list.
* Updates method caches for cls and its subclasses.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static void remethodizeClass(Class cls)
{
category_list *cats;
BOOL isMeta;
rwlock_assert_writing(&runtimeLock);
isMeta = cls->isMetaClass();
// Re-methodizing: check for more categories
if ((cats = unattachedCategoriesForClass(cls))) {
chained_property_list *newproperties;
const protocol_list_t **newprotos;
if (PrintConnecting) {
_objc_inform("CLASS: attaching categories to class '%s' %s",
cls->nameForLogging(), isMeta ? "(meta)" : "");
}
// Update methods, properties, protocols
attachCategoryMethods(cls, cats, YES);
newproperties = buildPropertyList(nil, cats, isMeta);
if (newproperties) {
newproperties->next = cls->data()->properties;
cls->data()->properties = newproperties;
}
newprotos = buildProtocolList(cats, nil, cls->data()->protocols);
if (cls->data()->protocols && cls->data()->protocols != newprotos) {
_free_internal(cls->data()->protocols);
}
cls->data()->protocols = newprotos;
_free_internal(cats);
}