/
objc-runtime-new.mm
9489 lines (7960 loc) · 311 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.
**********************************************************************/
#include <cstdint>
#include "DenseMapExtras.h"
#include "llvm-MathExtras.h"
#include "objc-private.h"
#include "objc-malloc-instance.h"
#include "objc-runtime-new.h"
#include "objc-file.h"
#include "objc-probes.h"
#include "objc-zalloc.h"
#include <Block.h>
#include <objc/message.h>
#if !TARGET_OS_EXCLAVEKIT
#include <mach/shared_region.h>
extern "C" {
#include <os/bsd.h>
#include <os/reason_private.h>
#include <os/variant_private.h>
}
#endif // !TARGET_OS_EXCLAVEKIT
#define newprotocol(p) ((protocol_t *)p)
static void disableTaggedPointers();
static void detach_class(Class cls, bool isMeta);
static void free_class(Class cls);
static IMP addMethod(Class cls, SEL name, IMP imp, const char *types, bool replace);
static void adjustCustomFlagsForMethodChange(Class cls, method_t *meth);
static method_t *search_method_list(const method_list_t *mlist, SEL sel);
template<typename T> static bool method_lists_contains_any(T *mlists, T *end,
SEL sels[], size_t selcount);
static void flushCaches(Class cls, const char *func, bool (^predicate)(Class c));
static void initializeTaggedPointerObfuscator(void);
#if SUPPORT_FIXUP
static void fixupMessageRef(message_ref_t *msg);
#endif
static Class realizeClassMaybeSwiftAndUnlock(Class cls, mutex_t& lock);
static Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized);
template<class EnumerateFunc>
static void enumerateSelectorsInMethodList(const method_list_t *list,
const EnumerateFunc &fn);
struct locstamped_category_t {
category_t *cat;
struct header_info *hi;
};
enum {
ATTACH_CLASS = 1 << 0,
ATTACH_METACLASS = 1 << 1,
ATTACH_CLASS_AND_METACLASS = 1 << 2,
ATTACH_EXISTING = 1 << 3,
};
static void attachCategories(Class cls, const struct locstamped_category_t *cats_list, uint32_t cats_count, int flags);
/***********************************************************************
* Lock management
**********************************************************************/
mutex_t runtimeLock;
mutex_t selLock;
#if CONFIG_USE_CACHE_LOCK
mutex_t cacheUpdateLock;
#endif
recursive_mutex_t loadMethodLock;
/***********************************************************************
* Class structure decoding
**********************************************************************/
const uintptr_t objc_debug_class_rw_data_mask = DEBUG_DATA_MASK;
/***********************************************************************
* Non-pointer isa decoding
**********************************************************************/
#if SUPPORT_INDEXED_ISA
// Indexed non-pointer isa.
// These are used to mask the ISA and see if its got an index or not.
const uintptr_t objc_debug_indexed_isa_magic_mask = ISA_INDEX_MAGIC_MASK;
const uintptr_t objc_debug_indexed_isa_magic_value = ISA_INDEX_MAGIC_VALUE;
// die if masks overlap
STATIC_ASSERT((ISA_INDEX_MASK & ISA_INDEX_MAGIC_MASK) == 0);
// die if magic is wrong
STATIC_ASSERT((~ISA_INDEX_MAGIC_MASK & ISA_INDEX_MAGIC_VALUE) == 0);
// Then these are used to extract the index from the ISA.
const uintptr_t objc_debug_indexed_isa_index_mask = ISA_INDEX_MASK;
const uintptr_t objc_debug_indexed_isa_index_shift = ISA_INDEX_SHIFT;
asm("\n .globl _objc_absolute_indexed_isa_magic_mask" \
"\n _objc_absolute_indexed_isa_magic_mask = " STRINGIFY2(ISA_INDEX_MAGIC_MASK));
asm("\n .globl _objc_absolute_indexed_isa_magic_value" \
"\n _objc_absolute_indexed_isa_magic_value = " STRINGIFY2(ISA_INDEX_MAGIC_VALUE));
asm("\n .globl _objc_absolute_indexed_isa_index_mask" \
"\n _objc_absolute_indexed_isa_index_mask = " STRINGIFY2(ISA_INDEX_MASK));
asm("\n .globl _objc_absolute_indexed_isa_index_shift" \
"\n _objc_absolute_indexed_isa_index_shift = " STRINGIFY2(ISA_INDEX_SHIFT));
// And then we can use that index to get the class from this array. Note
// the size is provided so that clients can ensure the index they get is in
// bounds and not read off the end of the array.
// Defined in the objc-msg-*.s files
// const Class objc_indexed_classes[]
// When we don't have enough bits to store a class*, we can instead store an
// index in to this array. Classes are added here when they are realized.
// Note, an index of 0 is illegal.
uintptr_t objc_indexed_classes_count = 0;
// SUPPORT_INDEXED_ISA
#else
// not SUPPORT_INDEXED_ISA
// These variables exist but are all set to 0 so that they are ignored.
const uintptr_t objc_debug_indexed_isa_magic_mask = 0;
const uintptr_t objc_debug_indexed_isa_magic_value = 0;
const uintptr_t objc_debug_indexed_isa_index_mask = 0;
const uintptr_t objc_debug_indexed_isa_index_shift = 0;
Class objc_indexed_classes[1] = { nil };
uintptr_t objc_indexed_classes_count = 0;
// not SUPPORT_INDEXED_ISA
#endif
#if SUPPORT_PACKED_ISA
// Packed non-pointer isa.
asm("\n .globl _objc_absolute_packed_isa_class_mask" \
"\n _objc_absolute_packed_isa_class_mask = " STRINGIFY2(ISA_MASK));
// a better definition is
// (uintptr_t)ptrauth_strip((void *)ISA_MASK, ISA_SIGNING_KEY)
// however we know that PAC uses bits outside of MACH_VM_MAX_ADDRESS
// so approximate the definition here to be constant
template <typename T>
static constexpr T coveringMask(T n) {
for (T mask = 0; mask != ~T{0}; mask = (mask << 1) | 1) {
if ((n & mask) == n) return mask;
}
return ~T{0};
}
const uintptr_t objc_debug_isa_class_mask = ISA_MASK & coveringMask(OBJC_VM_MAX_ADDRESS - 1);
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 & OBJC_VM_MAX_ADDRESS) == 0 ||
ISA_MASK + sizeof(void*) == OBJC_VM_MAX_ADDRESS);
// SUPPORT_PACKED_ISA
#else
// not SUPPORT_PACKED_ISA
// 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;
// not SUPPORT_PACKED_ISA
#endif
// We use a *signed* "pointer" to control enforcement. It's signed so that
// an attacker can't just overwrite it with some random thing to turn off
// pointer authentication of the class_ro_t pointers.
//
// Note that this is *disable* rather than *enable* because NULL pointers
// are not signed, and we want to protect against it being turned off;
// enabling it increases security so an attacker is unlikely to want to
// do that.
namespace objc {
uintptr_t ptrauth_class_rx_enforce disableEnforceClassRXPtrAuth;
}
/***********************************************************************
* Swift marker bits
**********************************************************************/
const uintptr_t objc_debug_swift_stable_abi_bit = FAST_IS_SWIFT_STABLE;
/***********************************************************************
* allocatedClasses
* A table of all classes (and metaclasses) which have been allocated
* with objc_allocateClassPair.
**********************************************************************/
namespace objc {
static ExplicitInitDenseSet<Class> allocatedClasses;
}
/***********************************************************************
* _firstRealizedClass
* The root of all realized classes
**********************************************************************/
static Class _firstRealizedClass = nil;
/***********************************************************************
* didInitialAttachCategories
* Whether the initial attachment of categories present at startup has
* been done.
**********************************************************************/
static bool didInitialAttachCategories = false;
/***********************************************************************
* didCallDyldNotifyRegister
* Whether the call to _dyld_objc_notify_register has completed.
**********************************************************************/
bool didCallDyldNotifyRegister = false;
/***********************************************************************
* smallMethodIMPMap
* The map from small method pointers to replacement IMPs.
*
* Locking: runtimeLock must be held when accessing this map.
**********************************************************************/
namespace objc {
// The value type of smallMethodIMPMap is really IMP, but signed with a
// custom discriminator and blended with the method_t* that it's associated
// with. This securely ties the IMP in the table to the method that it
// belongs to, without requiring the table itself to be aware of address
// discrimination or hashing signed pointers.
static objc::LazyInitDenseMap<const method_t *, void *> smallMethodIMPMap;
#define smallMethodIMPMapKey ptrauth_key_process_dependent_code
#define smallMethodIMPMapDiscriminator(methodPtr) \
ptrauth_blend_discriminator(methodPtr, ptrauth_string_discriminator("smallMethodIMPMap"))
static objc::LazyInitDenseMap<const method_t *, objc_method_description *> methodDescriptionMap;
}
static IMP method_t_remappedImp_nolock(const method_t *m) {
lockdebug::assert_locked(&runtimeLock);
auto *map = objc::smallMethodIMPMap.get(false);
if (!map)
return nullptr;
auto iter = map->find(m);
if (iter == map->end())
return nullptr;
return bitcast_auth_and_resign(IMP, iter->second,
smallMethodIMPMapKey,
smallMethodIMPMapDiscriminator(m),
ptrauth_key_function_pointer,
ptrauth_function_pointer_type_discriminator(IMP));
}
IMP method_t::remappedImp(bool needsLock) const {
ASSERT(getKind() == Kind::small);
if (needsLock) {
mutex_locker_t guard(runtimeLock);
return method_t_remappedImp_nolock(this);
} else {
lockdebug::assert_locked(&runtimeLock);
return method_t_remappedImp_nolock(this);
}
}
void method_t::remapImp(IMP imp) {
ASSERT(getKind() == Kind::small);
lockdebug::assert_locked(&runtimeLock);
auto *map = objc::smallMethodIMPMap.get(true);
(*map)[this] = bitcast_auth_and_resign(void *, imp,
ptrauth_key_function_pointer,
ptrauth_function_pointer_type_discriminator(IMP),
smallMethodIMPMapKey,
smallMethodIMPMapDiscriminator(this));
}
objc_method_description *method_t::getCachedDescription() const {
mutex_locker_t guard(runtimeLock);
auto &ptr = (*objc::methodDescriptionMap.get(true))[this];
if (!ptr) {
ptr = (objc_method_description *)malloc(sizeof *ptr);
ptr->name = name();
ptr->types = (char *)types();
}
return ptr;
}
void method_t::tryFreeContents_nolock() {
assert_locked(&runtimeLock);
try_free(types());
if (auto *map = objc::methodDescriptionMap.get(false))
map->erase(this);
}
/*
Low two bits of mlist->entsize is used as the fixed-up marker.
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.
High two bits of protocol->flags is used as the fixed-up marker.
PREOPTIMIZED VERSION:
Protocols from shared cache are 1<<30.
Runtime fixed-up protocols get 1<<30.
UN-PREOPTIMIZED VERSION:
Protocols from shared cache are 1<<30.
Shared cache's fixups are not trusted.
Runtime fixed-up protocols get 3<<30.
*/
static const uint32_t fixed_up_method_list = 3;
static const uint32_t uniqued_method_list = 1;
static uint32_t fixed_up_protocol = PROTOCOL_FIXED_UP_1;
static uint32_t canonical_protocol = PROTOCOL_IS_CANONICAL;
void
disableSharedCacheProtocolOptimizations(void)
{
fixed_up_protocol = PROTOCOL_FIXED_UP_1 | PROTOCOL_FIXED_UP_2;
// Its safe to just set canonical protocol to 0 as we'll never call
// clearIsCanonical() unless isCanonical() returned true, which can't happen
// with a 0 mask
canonical_protocol = 0;
}
bool method_list_t::isUniqued() const {
// Small lists always use selrefs which are already uniqued before we use them.
if ( listKind() == method_t::Kind::small )
return true;
return (flags() & uniqued_method_list) != 0;
}
bool method_list_t::isFixedUp() const {
// Ignore any flags in the top bits, just look at the bottom two.
return (flags() & 0x3) == fixed_up_method_list;
}
void method_list_t::setFixedUp() {
lockdebug::assert_locked(&runtimeLock);
ASSERT(!isFixedUp());
entsizeAndFlags = entsizeAndFlags| fixed_up_method_list;
}
bool protocol_t::isFixedUp() const {
return (flags & PROTOCOL_FIXED_UP_MASK) == fixed_up_protocol;
}
void protocol_t::setFixedUp() {
lockdebug::assert_locked(&runtimeLock);
ASSERT(!isFixedUp());
flags = (flags & ~PROTOCOL_FIXED_UP_MASK) | fixed_up_protocol;
}
bool protocol_t::isCanonical() const {
return (flags & canonical_protocol) != 0;
}
void protocol_t::clearIsCanonical() {
lockdebug::assert_locked(&runtimeLock);
ASSERT(isCanonical());
flags = flags & ~canonical_protocol;
}
method_array_t::ListIterator method_array_t::endCategoryMethodLists(Class cls) const
{
auto mlists = beginLists();
auto mlistsEnd = endLists();
if (mlists == mlistsEnd || !cls->data()->ro()->baseMethods)
{
// No methods, or no base methods.
// Everything here is a category method.
return mlistsEnd;
}
// Have base methods. Category methods are
// everything except the last method list.
return --mlistsEnd;
}
static const char *sel_cname(SEL sel)
{
return (const char *)(void *)sel;
}
static size_t protocol_list_size(const protocol_list_t *plist)
{
return sizeof(protocol_list_t) + plist->count * sizeof(protocol_t *);
}
using ClassCopyFixupHandler = void (*)(Class _Nonnull oldClass,
Class _Nonnull newClass);
// Normally there's only one handler registered.
static GlobalSmallVector<ClassCopyFixupHandler, 1> classCopyFixupHandlers;
void _objc_setClassCopyFixupHandler(void (* _Nonnull newFixupHandler)
(Class _Nonnull oldClass, Class _Nonnull newClass)) {
mutex_locker_t lock(runtimeLock);
classCopyFixupHandlers.append(newFixupHandler);
}
static Class
alloc_class_for_subclass(Class supercls, size_t extraBytes)
{
if (!supercls || !supercls->isAnySwift()) {
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(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);
memset(swcls, 0, sizeof(objc_class));
swcls->description = nil;
for (auto handler : classCopyFixupHandlers) {
handler(supercls, (Class)swcls);
}
return (Class)swcls;
}
/***********************************************************************
* object_getIndexedIvars.
**********************************************************************/
void *object_getIndexedIvars(id obj)
{
uint8_t *base = (uint8_t *)obj;
if (_objc_isTaggedPointerOrNil(obj)) return nil;
if (!obj->isClass()) return base + obj->ISA()->alignedInstanceSize();
Class cls = (Class)obj;
if (!cls->isAnySwift()) 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)
{
lockdebug::assert_locked(&runtimeLock);
if (rw->flags & RW_COPIED_RO) {
// already writeable, do nothing
} else {
rw->set_ro(rw->ro()->duplicate());
rw->flags |= RW_COPIED_RO;
}
return const_cast<class_ro_t *>(rw->ro());
}
/***********************************************************************
* dataSegmentsContain
* Returns true if the given address lies within a data segment in any
* loaded image.
**********************************************************************/
NEVER_INLINE
static bool
dataSegmentsContain(Class cls)
{
uint32_t index;
if (objc::dataSegmentsRanges.find((uintptr_t)cls, index)) {
// if the class is realized (hence has a class_rw_t),
// memorize where we found the range
if (cls->isRealized()) {
cls->data()->witness = (uint16_t)index;
}
return true;
}
return false;
}
/***********************************************************************
* isKnownClass
* Return true if the class is known to the runtime (located within the
* shared cache, within the data segment of a loaded image, or has been
* allocated with obj_allocateClassPair).
*
* The result of this operation is cached on the class in a "witness"
* value that is cheaply checked in the fastpath.
**********************************************************************/
ALWAYS_INLINE
static bool
isKnownClass(Class cls)
{
if (fastpath(cls->isRealized() && objc::dataSegmentsRanges.contains(cls->data()->witness, (uintptr_t)cls))) {
return true;
}
auto &set = objc::allocatedClasses.get();
return set.find(cls) != set.end() || dataSegmentsContain(cls);
}
/***********************************************************************
* addClassTableEntry
* Add a class to the table of all classes. If addMeta is true,
* automatically adds the metaclass of the class as well.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static void
addClassTableEntry(Class cls, bool addMeta = true)
{
lockdebug::assert_locked(&runtimeLock);
// This class is allowed to be a known class via the shared cache or via
// data segments, but it is not allowed to be in the dynamic table already.
auto &set = objc::allocatedClasses.get();
ASSERT(set.find(cls) == set.end());
if (!isKnownClass(cls))
set.insert(cls);
if (addMeta)
addClassTableEntry(cls->ISA(), false);
}
/***********************************************************************
* checkIsKnownClass
* Checks the given class against the list of all known classes. Dies
* with a fatal error if the class is not known.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
ALWAYS_INLINE
static void
checkIsKnownClass(Class cls)
{
if (slowpath(!isKnownClass(cls))) {
_objc_fatal("Attempt to use unknown class %p.", cls);
}
}
/***********************************************************************
* classNSObject
* Returns class NSObject.
* Locking: none
**********************************************************************/
static Class classNSObject(void)
{
extern objc_class OBJC_CLASS_$_NSObject;
return (Class)&OBJC_CLASS_$_NSObject;
}
static Class metaclassNSObject(void)
{
extern objc_class OBJC_METACLASS_$_NSObject;
return (Class)&OBJC_METACLASS_$_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.
**********************************************************************/
__attribute__((cold, noinline))
static void
printReplacements(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count)
{
uint32_t c;
bool isMeta = cls->isMetaClass();
// 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;
method_list_t *mlist = cat->methodsForMeta(isMeta);
if (!mlist) continue;
for (const auto& meth : *mlist) {
SEL s = sel_registerName(sel_cname(meth.name()));
// Search for replaced methods in method lookup order.
// Complain about the first duplicate only.
// Look for method in earlier categories
for (uint32_t c2 = 0; c2 < c; c2++) {
category_t *cat2 = cats_list[c2].cat;
const method_list_t *mlist2 = cat2->methodsForMeta(isMeta);
if (!mlist2) continue;
for (const auto& meth2 : *mlist2) {
SEL s2 = sel_registerName(sel_cname(meth2.name()));
if (s == s2) {
logReplacedMethod(cls->nameForLogging(), s,
cls->isMetaClass(), cat->name,
meth2.impRaw(), meth.impRaw());
goto complained;
}
}
}
// Look for method in cls
for (const auto& meth2 : cls->data()->methods()) {
SEL s2 = sel_registerName(sel_cname(meth2.name()));
if (s == s2) {
logReplacedMethod(cls->nameForLogging(), s,
cls->isMetaClass(), cat->name,
meth2.impRaw(), meth.impRaw());
goto complained;
}
}
complained:
;
}
}
}
/***********************************************************************
* unreasonableClassCount
* Provides an upper bound for any iteration of classes,
* to prevent spins when runtime metadata is corrupted.
**********************************************************************/
static unsigned unreasonableClassCount()
{
lockdebug::assert_locked(&runtimeLock);
int base = NXCountMapTable(gdb_objc_realized_classes) +
getPreoptimizedClassUnreasonableCount();
// Provide lots of slack here. Some iterations touch metaclasses too.
// Some iterations backtrack (like realized class iteration).
// We don't need an efficient bound, merely one that prevents spins.
return (base + 1) * 16;
}
/***********************************************************************
* Class enumerators
* The passed in block returns `false` if subclasses can be skipped
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static inline void
foreach_realized_class_and_subclass_2(Class top, unsigned &count,
bool skip_metaclass,
bool (^code)(Class) __attribute((noescape)))
{
Class cls = top;
lockdebug::assert_locked(&runtimeLock);
ASSERT(top);
while (1) {
if (--count == 0) {
_objc_fatal("Memory corruption in class list.");
}
bool skip_subclasses;
if (skip_metaclass && cls->isMetaClass()) {
skip_subclasses = true;
} else {
skip_subclasses = !code(cls);
}
if (!skip_subclasses && cls->data()->firstSubclass) {
cls = cls->data()->firstSubclass;
} else {
while (!cls->data()->nextSiblingClass && cls != top) {
cls = cls->getSuperclass();
if (--count == 0) {
_objc_fatal("Memory corruption in class list.");
}
}
if (cls == top) break;
cls = cls->data()->nextSiblingClass;
}
}
}
// Enumerates a class and all of its realized subclasses.
static void
foreach_realized_class_and_subclass(Class top, bool (^code)(Class) __attribute((noescape)))
{
unsigned int count = unreasonableClassCount();
foreach_realized_class_and_subclass_2(top, count, false, code);
}
// Enumerates all realized classes and metaclasses.
static void
foreach_realized_class_and_metaclass(bool (^code)(Class) __attribute((noescape)))
{
unsigned int count = unreasonableClassCount();
for (Class top = _firstRealizedClass;
top != nil;
top = top->data()->nextSiblingClass)
{
foreach_realized_class_and_subclass_2(top, count, false, code);
}
}
// Enumerates all realized classes (ignoring metaclasses).
static void
foreach_realized_class(bool (^code)(Class) __attribute((noescape)))
{
unsigned int count = unreasonableClassCount();
for (Class top = _firstRealizedClass;
top != nil;
top = top->data()->nextSiblingClass)
{
foreach_realized_class_and_subclass_2(top, count, true, code);
}
}
/***********************************************************************
* enumerateSelectorsInMethodList
**********************************************************************/
template<class EnumerateFunc>
static void enumerateSelectorsInMethodList(const method_list_t *list,
const EnumerateFunc &fn) {
switch (list->listKind()) {
case method_t::Kind::small:
if (CONFIG_SHARED_CACHE_RELATIVE_DIRECT_SELECTORS && objc::inSharedCache((uintptr_t)list)) {
for (auto& meth: *list) if (!fn(meth.getSmallNameAsSEL())) break;
} else {
for (auto& meth: *list) if (!fn(meth.getSmallNameAsSELRef())) break;
}
break;
case method_t::Kind::big:
for (auto& meth: *list) if (!fn(meth.big().name)) break;
break;
case method_t::Kind::bigSigned:
for (auto& meth: *list) if (!fn(meth.bigSigned().name)) break;
break;
#if TARGET_OS_EXCLAVEKIT
case method_t::Kind::bigStripped:
for (auto& meth: *list) if (!fn(meth.bigStripped().name)) break;
break;
#endif
}
}
/***********************************************************************
* Method Scanners / Optimization tracking
* Implementation of scanning for various implementations of methods.
**********************************************************************/
namespace objc {
// The current state of NSObject swizzling for every scanner
//
// It allows for cheap checks of global swizzles, and also lets
// things like IMP Swizzling before NSObject has been initialized
// to be remembered, as setInitialized() would miss these.
//
// The bits have values from flag_t below, *but* if we're asking
// about the metaclass then shifted left one.
static uintptr_t NSObjectSwizzledMask;
static uintptr_t InterestingSelectorOnes;
static uintptr_t InterestingSelectorZeroes;
static const char * const interestingSelectors[] = {
"_isDeallocating",
"_tryRetain",
"alloc",
"allocWithZone:",
"allowsWeakReference",
"autorelease",
"class",
"isKindOfClass:",
"new",
"release",
"respondsToSelector:",
"retain",
"retainCount",
"retainWeakReference",
"self"
};
class Scanner {
// There must be a spare bit between each of these
typedef enum {
AWZ = 0x0001,
RR = 0x0004,
Core = 0x0010,
} flag_t;
typedef enum {
NotInherited,
Inherited
} inherited_t;
typedef enum {
NotMetaclass,
Metaclass
} metaclass_t;
public:
static void
init()
{
static const unsigned count = (sizeof(interestingSelectors)
/sizeof(interestingSelectors[0]));
uintptr_t ones = ~(uintptr_t)0;
uintptr_t zeroes = ~(uintptr_t)0;
for (unsigned n = 0; n < count; ++n) {
// Look up the selector only if it's provided by the shared cache. We
// haven't yet initialized the named selector table, so we can't create a
// new selector if it isn't already in the shared cache table.
SEL sel = _sel_searchBuiltins(interestingSelectors[n]);
// If we couldn't look up the selector, give up and set masks that
// match every selector.
if (!sel) {
ones = 0;
zeroes = 0;
break;
}
ones &= (uintptr_t)sel;
zeroes &= ~(uintptr_t)sel;
}
InterestingSelectorOnes = ones;
InterestingSelectorZeroes = zeroes;
}
private:
static void
printCustom(const char *prefix, Class cls, inherited_t inherited)
{
_objc_inform("%s: %s%s%s",
prefix,
cls->nameForLogging(),
cls->isMetaClass() ? " (meta)" : "",
inherited == Inherited ? " (inherited)" : "");
}
static void
propagateCustomFlags(Class cls,
unsigned flags,
inherited_t inherited = NotInherited)
{
bool customAWZ = !!(flags & AWZ);
bool customRR = !!(flags & RR);
bool customCore = !!(flags & Core);
foreach_realized_class_and_subclass(cls, [=](Class c){
bool isSubclass = c != cls;
if (isSubclass && !c->isInitialized()) {
// Subclass not yet initialized. Wait for setInitialized() to do it
return false;
}
bool keepGoing = false;
inherited_t isInherited = isSubclass ? Inherited : inherited;
if (customAWZ && !c->hasCustomAWZ()) {
c->setHasCustomAWZ();
if (PrintCustomAWZ)
printCustom("CUSTOM AWZ", c, isInherited);
keepGoing = true;
}
if (customRR && !c->hasCustomRR()) {
c->setHasCustomRR();
if (PrintCustomRR)
printCustom("CUSTOM RR", c, isInherited);
keepGoing = true;
}
if (customCore && !c->hasCustomCore()) {
c->setHasCustomCore();
if (PrintCustomCore)
printCustom("CUSTOM Core", c, isInherited);
keepGoing = true;
}
return keepGoing;
});
}
static ALWAYS_INLINE bool isInterestingSelector(SEL sel) {
uintptr_t uisel = (uintptr_t)sel;
return (uisel & InterestingSelectorZeroes) == 0
&& (uisel & InterestingSelectorOnes) == InterestingSelectorOnes;
}
static ALWAYS_INLINE bool isAWZSelector(SEL sel) {
return sel == @selector(alloc) || sel == @selector(allocWithZone:);
}
static ALWAYS_INLINE
bool isRRSelector(SEL sel) {
return sel == @selector(retain) ||
sel == @selector(release) ||
sel == @selector(autorelease) ||
sel == @selector(_tryRetain) ||
sel == @selector(_isDeallocating) ||
sel == @selector(retainCount) ||
sel == @selector(allowsWeakReference) ||
sel == @selector(retainWeakReference);
}
static ALWAYS_INLINE
bool isCoreSelector(SEL sel) {
return sel == @selector(new) ||
sel == @selector(self) ||
sel == @selector(class) ||
sel == @selector(isKindOfClass:) ||
sel == @selector(respondsToSelector:);
}
static
bool isClassOnly(unsigned flags) {
return flags == AWZ;
}
static
bool isSwiftObject(Class cls) {
if (cls->isRootClass() || cls->isRootMetaclass())
if (strcmp(cls->mangledName(), "_TtCs12_SwiftObject") == 0)
return true;
return false;
}
static
bool isNSObjectSwizzled(unsigned flags, metaclass_t mc) {
return NSObjectSwizzledMask & (flags << mc);
}
static
void setNSObjectSwizzled(Class cls, unsigned flags, metaclass_t mc) {
NSObjectSwizzledMask |= (flags << mc);
if (cls->isInitialized())
propagateCustomFlags(cls, flags);
}