-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathProtocolConformance.cpp
2325 lines (2019 loc) · 87.4 KB
/
ProtocolConformance.cpp
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
//===--- ProtocolConformance.cpp - Swift protocol conformance checking ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Checking and caching of Swift protocol conformances.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringExtras.h"
#include "swift/ABI/TypeIdentity.h"
#include "swift/Basic/Lazy.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Runtime/Bincompat.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/Concurrent.h"
#include "swift/Runtime/EnvironmentVariables.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Basic/Unreachable.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerUnion.h"
#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "ImageInspection.h"
#include "Private.h"
#include "Tracing.h"
#include <new>
#include <vector>
#if __has_include(<mach-o/dyld_priv.h>)
#include <mach-o/dyld_priv.h>
#define DYLD_EXPECTED_SWIFT_OPTIMIZATIONS_VERSION 1u
// Redeclare these functions as weak so we can build against a macOS 12 SDK and
// still test on macOS 11.
LLVM_ATTRIBUTE_WEAK
struct _dyld_protocol_conformance_result
_dyld_find_protocol_conformance(const void *protocolDescriptor,
const void *metadataType,
const void *typeDescriptor);
LLVM_ATTRIBUTE_WEAK
struct _dyld_protocol_conformance_result
_dyld_find_foreign_type_protocol_conformance(const void *protocol,
const char *foreignTypeIdentityStart,
size_t foreignTypeIdentityLength);
LLVM_ATTRIBUTE_WEAK
uint32_t _dyld_swift_optimizations_version(void);
#if DYLD_FIND_PROTOCOL_ON_DISK_CONFORMANCE_DEFINED
// Redeclare these functions as weak as well.
LLVM_ATTRIBUTE_WEAK bool _dyld_has_preoptimized_swift_protocol_conformances(
const struct mach_header *mh);
LLVM_ATTRIBUTE_WEAK struct _dyld_protocol_conformance_result
_dyld_find_protocol_conformance_on_disk(const void *protocolDescriptor,
const void *metadataType,
const void *typeDescriptor,
uint32_t flags);
LLVM_ATTRIBUTE_WEAK struct _dyld_protocol_conformance_result
_dyld_find_foreign_type_protocol_conformance_on_disk(
const void *protocol, const char *foreignTypeIdentityStart,
size_t foreignTypeIdentityLength, uint32_t flags);
#endif // DYLD_FIND_PROTOCOL_ON_DISK_CONFORMANCE_DEFINED
#endif // __has_include(<mach-o/dyld_priv.h>)
// Set this to 1 to enable logging of calls to the dyld shared cache conformance
// table
#if 0
#define DYLD_CONFORMANCES_LOG(fmt, ...) \
fprintf(stderr, "PROTOCOL CONFORMANCE: " fmt "\n", __VA_ARGS__)
#define SHARED_CACHE_LOG_ENABLED 1
#else
#define DYLD_CONFORMANCES_LOG(fmt, ...) (void)0
#endif
// Enable dyld shared cache acceleration only when it's available and we have
// ObjC interop.
#if DYLD_FIND_PROTOCOL_CONFORMANCE_DEFINED && SWIFT_OBJC_INTEROP
#define USE_DYLD_SHARED_CACHE_CONFORMANCE_TABLES 1
#endif
using namespace swift;
#ifndef NDEBUG
template <> SWIFT_USED void ProtocolDescriptor::dump() const {
printf("TargetProtocolDescriptor.\n"
"Name: \"%s\".\n",
Name.get());
}
void ProtocolDescriptorFlags::dump() const {
printf("ProtocolDescriptorFlags.\n");
printf("Is Swift: %s.\n", (isSwift() ? "true" : "false"));
printf("Needs Witness Table: %s.\n",
(needsWitnessTable() ? "true" : "false"));
printf("Is Resilient: %s.\n", (isResilient() ? "true" : "false"));
printf("Special Protocol: %s.\n",
(bool(getSpecialProtocol()) ? "Error" : "None"));
printf("Class Constraint: %s.\n",
(bool(getClassConstraint()) ? "Class" : "Any"));
printf("Dispatch Strategy: %s.\n",
(bool(getDispatchStrategy()) ? "Swift" : "ObjC"));
}
#endif
#if !defined(NDEBUG) && SWIFT_OBJC_INTEROP
#include <objc/runtime.h>
static const char *class_getName(const ClassMetadata* type) {
return class_getName(
reinterpret_cast<Class>(const_cast<ClassMetadata*>(type)));
}
template<> void ProtocolConformanceDescriptor::dump() const {
std::optional<SymbolInfo> info;
auto symbolName = [&](const void *addr) -> const char * {
info = SymbolInfo::lookup(addr);
if (info.has_value() && info->getSymbolName()) {
return info->getSymbolName();
}
return "<unknown addr>";
};
switch (getTypeKind()) {
case TypeReferenceKind::DirectObjCClassName:
printf("direct Objective-C class name %s", getDirectObjCClassName());
break;
case TypeReferenceKind::IndirectObjCClass:
printf("indirect Objective-C class %s",
class_getName(*getIndirectObjCClass()));
break;
case TypeReferenceKind::DirectTypeDescriptor:
case TypeReferenceKind::IndirectTypeDescriptor:
printf("unique nominal type descriptor %s", symbolName(getTypeDescriptor()));
break;
}
printf(" => ");
printf("witness table pattern (%p) %s\n", getWitnessTablePattern(), symbolName(getWitnessTablePattern()));
}
#endif
#ifndef NDEBUG
template <> SWIFT_USED void ProtocolConformanceDescriptor::verify() const {
auto typeKind = unsigned(getTypeKind());
assert(((unsigned(TypeReferenceKind::First_Kind) <= typeKind) &&
(unsigned(TypeReferenceKind::Last_Kind) >= typeKind)) &&
"Corrupted type metadata record kind");
}
#endif
#if SWIFT_OBJC_INTEROP
template <>
const ClassMetadata *TypeReference::getObjCClass(TypeReferenceKind kind) const {
switch (kind) {
case TypeReferenceKind::IndirectObjCClass:
return *getIndirectObjCClass(kind);
case TypeReferenceKind::DirectObjCClassName:
return reinterpret_cast<const ClassMetadata *>(
objc_lookUpClass(getDirectObjCClassName(kind)));
case TypeReferenceKind::DirectTypeDescriptor:
case TypeReferenceKind::IndirectTypeDescriptor:
return nullptr;
}
swift_unreachable("Unhandled TypeReferenceKind in switch.");
}
#endif
static MetadataState
tryGetCompleteMetadataNonblocking(const Metadata *metadata) {
return swift_checkMetadataState(
MetadataRequest(MetadataState::Complete, /*isNonBlocking*/ true),
metadata)
.State;
}
/// Get the superclass of metadata, which may be incomplete. When the metadata
/// is not sufficiently complete, then we fall back to demangling the superclass
/// in the nominal type descriptor, which is slow but works. Return {NULL,
/// MetadataState::Complete} if the metadata is not a class, or has no
/// superclass.
///
/// If the metadata's current state is known, it may be passed in as
/// knownMetadataState. This saves the cost of retrieving that info separately.
///
/// When instantiateSuperclassMetadata is true, this function will instantiate
/// superclass metadata when necessary. When false, this will return {NULL,
/// MetadataState::Abstract} to indicate that there's an uninstantiated
/// superclass that was not returned.
static MetadataResponse getSuperclassForMaybeIncompleteMetadata(
const Metadata *metadata, std::optional<MetadataState> knownMetadataState,
bool instantiateSuperclassMetadata) {
const ClassMetadata *classMetadata = dyn_cast<ClassMetadata>(metadata);
if (!classMetadata)
return {_swift_class_getSuperclass(metadata), MetadataState::Complete};
#if SWIFT_OBJC_INTEROP
// Artificial subclasses are not valid type metadata and
// tryGetCompleteMetadataNonblocking will crash on them. However, they're
// always fully set up, so we can just skip it and fetch the Subclass field.
if (classMetadata->isTypeMetadata() && classMetadata->isArtificialSubclass())
return {classMetadata->Superclass, MetadataState::Complete};
// Pure ObjC classes are already set up, and the code below will not be
// happy with them.
if (!classMetadata->isTypeMetadata())
return {classMetadata->Superclass, MetadataState::Complete};
#endif
MetadataState metadataState;
if (knownMetadataState)
metadataState = *knownMetadataState;
else
metadataState = tryGetCompleteMetadataNonblocking(classMetadata);
if (metadataState == MetadataState::Complete) {
// The subclass metadata is complete. Fetch and return the superclass.
auto *superMetadata = getMetadataForClass(classMetadata->Superclass);
return {superMetadata, MetadataState::Complete};
} else if (metadataState == MetadataState::NonTransitiveComplete) {
// The subclass metadata is complete, but, unlike above, not transitively.
// Its Superclass field is valid, so just read that field to get to the
// superclass to proceed to the next step.
auto *superMetadata = getMetadataForClass(classMetadata->Superclass);
auto superState = tryGetCompleteMetadataNonblocking(superMetadata);
return {superMetadata, superState};
} else if (instantiateSuperclassMetadata) {
// The subclass metadata is either LayoutComplete or Abstract, so the
// Superclass field is not valid. To get to the superclass, make the
// expensive call to getSuperclassMetadata which demangles the superclass
// name from the nominal type descriptor to get the metadata for the
// superclass.
MetadataRequest request(MetadataState::Abstract,
/*non-blocking*/ true);
return getSuperclassMetadata(request, classMetadata);
} else {
// The Superclass field is not valid and the caller did not request
// instantiation. Return a NULL superclass and Abstract to indicate that a
// superclass exists but is not yet instantiated.
return {nullptr, MetadataState::Abstract};
}
}
struct MaybeIncompleteSuperclassIterator {
const Metadata *metadata;
std::optional<MetadataState> state;
bool instantiateSuperclassMetadata;
MaybeIncompleteSuperclassIterator(const Metadata *metadata,
bool instantiateSuperclassMetadata)
: metadata(metadata), state(std::nullopt),
instantiateSuperclassMetadata(instantiateSuperclassMetadata) {}
MaybeIncompleteSuperclassIterator &operator++() {
auto response = getSuperclassForMaybeIncompleteMetadata(
metadata, state, instantiateSuperclassMetadata);
metadata = response.Value;
state = response.State;
return *this;
}
const Metadata *operator*() const { return metadata; }
bool operator!=(const MaybeIncompleteSuperclassIterator rhs) const {
return metadata != rhs.metadata;
}
};
/// Take the type reference inside a protocol conformance record and fetch the
/// canonical metadata pointer for the type it refers to.
/// Returns nil for universal or generic type references.
template <>
const Metadata *
ProtocolConformanceDescriptor::getCanonicalTypeMetadata() const {
switch (getTypeKind()) {
case TypeReferenceKind::IndirectObjCClass:
case TypeReferenceKind::DirectObjCClassName:
#if SWIFT_OBJC_INTEROP
// The class may be ObjC, in which case we need to instantiate its Swift
// metadata. The class additionally may be weak-linked, so we have to check
// for null.
if (auto cls = TypeRef.getObjCClass(getTypeKind()))
return getMetadataForClass(cls);
#endif
return nullptr;
case TypeReferenceKind::DirectTypeDescriptor:
case TypeReferenceKind::IndirectTypeDescriptor: {
if (auto anyType = getTypeDescriptor()) {
if (auto type = dyn_cast<TypeContextDescriptor>(anyType)) {
if (!type->isGeneric()) {
if (auto accessFn = type->getAccessFunction())
return accessFn(MetadataState::Abstract).Value;
}
} else if (auto protocol = dyn_cast<ProtocolDescriptor>(anyType)) {
return _getSimpleProtocolTypeMetadata(protocol);
}
}
return nullptr;
}
}
swift_unreachable("Unhandled TypeReferenceKind in switch.");
}
namespace {
/// Describes the result of looking in the conformance cache.
struct ConformanceLookupResult {
/// The actual witness table, which will be NULL if the type does not
/// conform.
const WitnessTable *witnessTable = nullptr;
/// The global actor to which this conformance is isolated, or NULL for
/// a nonisolated conformances.
const Metadata *globalActorIsolationType = nullptr;
/// When the conformance is global-actor-isolated, this is the conformance
/// of globalActorIsolationType to GlobalActor.
const WitnessTable *globalActorIsolationWitnessTable = nullptr;
ConformanceLookupResult() { }
ConformanceLookupResult(std::nullptr_t) { }
ConformanceLookupResult(const WitnessTable *witnessTable,
const Metadata *globalActorIsolationType,
const WitnessTable *globalActorIsolationWitnessTable)
: witnessTable(witnessTable),
globalActorIsolationType(globalActorIsolationType),
globalActorIsolationWitnessTable(globalActorIsolationWitnessTable) { }
explicit operator bool() const { return witnessTable != nullptr; }
/// Given a type and conformance descriptor, form a conformance lookup
/// result.
static ConformanceLookupResult fromConformance(
const Metadata *type,
const ProtocolConformanceDescriptor *conformanceDescriptor);
};
}
/// Determine the global actor isolation for the given witness table.
///
/// Returns true if an error occurred, false if global actor isolation was
/// successfully computed (which can mean "not isolated").
static bool _checkWitnessTableIsolation(
const Metadata *type,
const WitnessTable *wtable,
llvm::ArrayRef<const void *> conditionalArgs,
ConformanceExecutionContext &context
);
template<>
const WitnessTable *
ProtocolConformanceDescriptor::getWitnessTable(
const Metadata *type,
ConformanceExecutionContext &context
) const {
// If needed, check the conditional requirements.
llvm::SmallVector<const void *, 8> conditionalArgs;
llvm::ArrayRef<GenericParamDescriptor> genericParams;
if (auto typeDescriptor = type->getTypeContextDescriptor())
genericParams = typeDescriptor->getGenericParams();
if (hasConditionalRequirements() || !genericParams.empty()) {
SubstGenericParametersFromMetadata substitutions(type);
auto error = _checkGenericRequirements(
genericParams, getConditionalRequirements(), conditionalArgs,
[&substitutions](unsigned depth, unsigned index) {
return substitutions.getMetadata(depth, index).Ptr;
},
[&substitutions](unsigned fullOrdinal, unsigned keyOrdinal) {
return substitutions.getMetadataKeyArgOrdinal(keyOrdinal).Ptr;
},
[&substitutions](const Metadata *type, unsigned index) {
return substitutions.getWitnessTable(type, index);
},
&context);
if (error)
return nullptr;
}
#if SWIFT_STDLIB_USE_RELATIVE_PROTOCOL_WITNESS_TABLES
auto wtable = (const WitnessTable *)
swift_getWitnessTableRelative(this, type, conditionalArgs.data());
#else
auto wtable = swift_getWitnessTable(this, type, conditionalArgs.data());
#endif
if (!wtable)
return nullptr;
// Check the global-actor isolation for this conformance, combining it with
// any global-actor isolation determined based on the conditional
// requirements above.
if (_checkWitnessTableIsolation(type, wtable, conditionalArgs, context))
return nullptr;
return wtable;
}
ConformanceLookupResult ConformanceLookupResult::fromConformance(
const Metadata *type,
const ProtocolConformanceDescriptor *conformanceDescriptor) {
ConformanceExecutionContext context;
auto wtable = conformanceDescriptor->getWitnessTable(type, context);
return {
wtable,
context.globalActorIsolationType,
context.globalActorIsolationWitnessTable
};
}
/// Determine the global actor isolation for the given witness table.
///
/// Returns true if an error occurred, false if global actor isolation was
/// successfully computed (which can mean "not isolated").
static bool _checkWitnessTableIsolation(
const Metadata *type,
const WitnessTable *wtable,
llvm::ArrayRef<const void *> conditionalArgs,
ConformanceExecutionContext &context
) {
#if SWIFT_STDLIB_USE_RELATIVE_PROTOCOL_WITNESS_TABLES
auto description = lookThroughOptionalConditionalWitnessTable(
reinterpret_cast<const RelativeWitnessTable *>(wtable))
->getDescription();
#else
auto description = wtable->getDescription();
#endif
// If there's no protocol conformance descriptor, do nothing.
if (!description)
return false;
// If this conformance doesn't have global actor isolation, we're done.
if (!description->hasGlobalActorIsolation())
return false;
// Resolve the global actor type.
SubstGenericParametersFromMetadata substitutions(type);
auto result = swift_getTypeByMangledName(
MetadataState::Abstract, description->getGlobalActorType(),
conditionalArgs.data(),
[&substitutions](unsigned depth, unsigned index) {
return substitutions.getMetadata(depth, index).Ptr;
},
[&substitutions](const Metadata *type, unsigned index) {
return substitutions.getWitnessTable(type, index);
});
if (result.isError())
return true;
auto myGlobalActorIsolationType = result.getType().getMetadata();
if (!myGlobalActorIsolationType)
return true;
// If the global actor isolation from this conformance conflicts with
// the one we already have, fail.
if (context.globalActorIsolationType &&
context.globalActorIsolationType != myGlobalActorIsolationType)
return true;
// Dig out the witness table.
auto myConformance = description->getGlobalActorConformance();
if (!myConformance)
return true;
auto myWitnessTable = ConformanceLookupResult::fromConformance(
myGlobalActorIsolationType, myConformance);
if (!myWitnessTable)
return true;
context.globalActorIsolationType = myGlobalActorIsolationType;
context.globalActorIsolationWitnessTable = myWitnessTable.witnessTable;
return false;
}
namespace {
struct ConformanceSection {
const ProtocolConformanceRecord *Begin, *End;
ConformanceSection(const ProtocolConformanceRecord *begin,
const ProtocolConformanceRecord *end)
: Begin(begin), End(end) {}
ConformanceSection(const void *ptr, uintptr_t size) {
auto bytes = reinterpret_cast<const char *>(ptr);
Begin = reinterpret_cast<const ProtocolConformanceRecord *>(ptr);
End = reinterpret_cast<const ProtocolConformanceRecord *>(bytes + size);
}
const ProtocolConformanceRecord *begin() const {
return Begin;
}
const ProtocolConformanceRecord *end() const {
return End;
}
};
struct ConformanceCacheKey {
const Metadata *Type;
const ProtocolDescriptor *Proto;
ConformanceCacheKey(const Metadata *type, const ProtocolDescriptor *proto)
: Type(type), Proto(proto) {
assert(type);
}
friend llvm::hash_code hash_value(const ConformanceCacheKey &key) {
return llvm::hash_combine(key.Type, key.Proto);
}
};
struct ConformanceCacheEntry {
public:
/// Storage used when we have global actor isolation on the conformance.
struct ExtendedStorage {
/// The protocol to which the type conforms.
const ProtocolDescriptor *Proto;
/// The global actor to which this conformance is isolated, or NULL for
/// a nonisolated conformances.
const Metadata *globalActorIsolationType = nullptr;
/// When the conformance is global-actor-isolated, this is the conformance
/// of globalActorIsolationType to GlobalActor.
const WitnessTable *globalActorIsolationWitnessTable = nullptr;
/// The next pointer in the list of extended storage allocations.
ExtendedStorage *next = nullptr;
};
const Metadata *Type;
llvm::PointerUnion<const ProtocolDescriptor *, ExtendedStorage *>
ProtoOrStorage;
/// The witness table.
const WitnessTable *Witness;
public:
ConformanceCacheEntry(ConformanceCacheKey key,
ConformanceLookupResult result,
std::atomic<ExtendedStorage *> &storageHead)
: Type(key.Type), Witness(result.witnessTable)
{
if (!result.globalActorIsolationType) {
ProtoOrStorage = key.Proto;
return;
}
// Allocate extended storage.
void *memory = malloc(sizeof(ExtendedStorage));
auto storage = new (memory) ExtendedStorage{
key.Proto, result.globalActorIsolationType,
result.globalActorIsolationWitnessTable
};
ProtoOrStorage = storage;
// Add the storage pointer to the list of extended storage allocations
// so that we can free them later.
auto head = storageHead.load(std::memory_order_relaxed);
while (true) {
storage->next = head;
if (storageHead.compare_exchange_weak(
head, storage, std::memory_order_release,
std::memory_order_relaxed))
break;
};
}
bool matchesKey(const ConformanceCacheKey &key) const {
return Type == key.Type && getProtocol() == key.Proto;
}
friend llvm::hash_code hash_value(const ConformanceCacheEntry &entry) {
return hash_value(entry.getKey());
}
/// Get the protocol.
const ProtocolDescriptor *getProtocol() const {
if (auto proto = ProtoOrStorage.dyn_cast<const ProtocolDescriptor *>())
return proto;
if (auto storage = ProtoOrStorage.dyn_cast<ExtendedStorage *>())
return storage->Proto;
return nullptr;
}
/// Get the conformance cache key.
ConformanceCacheKey getKey() const {
return ConformanceCacheKey(Type, getProtocol());
}
/// Get the cached witness table, or null if we cached failure.
const WitnessTable *getWitnessTable() const {
return Witness;
}
ConformanceLookupResult getResult() const {
if (ProtoOrStorage.is<const ProtocolDescriptor *>())
return ConformanceLookupResult { Witness, nullptr, nullptr };
if (auto storage = ProtoOrStorage.dyn_cast<ExtendedStorage *>()) {
return ConformanceLookupResult(
Witness, storage->globalActorIsolationType,
storage->globalActorIsolationWitnessTable);
}
return nullptr;
}
};
} // end anonymous namespace
// Conformance Cache.
struct ConformanceState {
ConcurrentReadableHashMap<ConformanceCacheEntry> Cache;
ConcurrentReadableArray<ConformanceSection> SectionsToScan;
/// The head of an intrusive linked list that keeps track of all of the
/// conformance cache entries that require extended storage.
std::atomic<ConformanceCacheEntry::ExtendedStorage *> ExtendedStorageHead{nullptr};
bool scanSectionsBackwards;
#if USE_DYLD_SHARED_CACHE_CONFORMANCE_TABLES
uintptr_t dyldSharedCacheStart;
uintptr_t dyldSharedCacheEnd;
bool hasOverriddenImage;
bool validateDyldResults;
// Only populated when validateDyldResults is enabled.
ConcurrentReadableArray<ConformanceSection> DyldOptimizedSections;
bool inSharedCache(const void *ptr) {
auto uintPtr = reinterpret_cast<uintptr_t>(ptr);
return dyldSharedCacheStart <= uintPtr && uintPtr < dyldSharedCacheEnd;
}
bool dyldOptimizationsActive() { return dyldSharedCacheStart != 0; }
#else
bool dyldOptimizationsActive() { return false; }
#endif
ConformanceState() {
scanSectionsBackwards =
runtime::bincompat::useLegacyProtocolConformanceReverseIteration();
#if USE_DYLD_SHARED_CACHE_CONFORMANCE_TABLES
if (__builtin_available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)) {
if (runtime::environment::SWIFT_DEBUG_ENABLE_SHARED_CACHE_PROTOCOL_CONFORMANCES()) {
if (&_dyld_swift_optimizations_version) {
if (_dyld_swift_optimizations_version() ==
DYLD_EXPECTED_SWIFT_OPTIMIZATIONS_VERSION) {
size_t length;
dyldSharedCacheStart =
(uintptr_t)_dyld_get_shared_cache_range(&length);
dyldSharedCacheEnd =
dyldSharedCacheStart ? dyldSharedCacheStart + length : 0;
validateDyldResults = runtime::environment::
SWIFT_DEBUG_VALIDATE_SHARED_CACHE_PROTOCOL_CONFORMANCES();
DYLD_CONFORMANCES_LOG("Shared cache range is %#lx-%#lx",
dyldSharedCacheStart, dyldSharedCacheEnd);
} else {
DYLD_CONFORMANCES_LOG("Disabling dyld protocol conformance "
"optimizations due to unknown "
"optimizations version %u",
_dyld_swift_optimizations_version());
dyldSharedCacheStart = 0;
dyldSharedCacheEnd = 0;
}
}
}
}
#endif
// This must run last, as it triggers callbacks that require
// ConformanceState to be set up.
initializeProtocolConformanceLookup();
}
void cacheResult(const Metadata *type, const ProtocolDescriptor *proto,
ConformanceLookupResult result, size_t sectionsCount) {
Cache.getOrInsert(ConformanceCacheKey(type, proto),
[&](ConformanceCacheEntry *entry, bool created) {
// Create the entry if needed. If it already exists,
// we're done.
if (!created)
return false;
// Check the current sections count against what was
// passed in. If a section count was passed in and they
// don't match, then this is not an authoritative entry
// and it may have been obsoleted, because the new
// sections could contain a conformance in a more
// specific type.
//
// If they DO match, then we can safely add. Another
// thread might be adding new sections at this point,
// but we will not race with them. That other thread
// will add the new sections, then clear the cache. When
// it clears the cache, it will block waiting for this
// code to complete and relinquish Cache's writer lock.
// If we cache a stale entry, it will be immediately
// cleared.
if (sectionsCount > 0 &&
SectionsToScan.snapshot().count() != sectionsCount)
return false; // abandon the new entry
::new (entry) ConformanceCacheEntry(
ConformanceCacheKey(type, proto), result,
ExtendedStorageHead);
return true; // keep the new entry
});
}
#ifndef NDEBUG
void verify() const SWIFT_USED;
#endif
};
#ifndef NDEBUG
void ConformanceState::verify() const {
// Iterate over all of the sections and verify all of the protocol
// descriptors.
auto &Self = const_cast<ConformanceState &>(*this);
for (const auto &Section : Self.SectionsToScan.snapshot()) {
for (const auto &Record : Section) {
Record.get()->verify();
}
}
}
#endif
static Lazy<ConformanceState> Conformances;
const void * const swift::_swift_debug_protocolConformanceStatePointer =
&Conformances;
static void _registerProtocolConformances(ConformanceState &C,
ConformanceSection section) {
C.SectionsToScan.push_back(section);
// Blow away the conformances cache to get rid of any negative entries that
// may now be obsolete.
C.Cache.clear([&](ConcurrentFreeListNode *&freeListHead) {
// The extended storage for conformance entries will need to be freed
// eventually. Put it on the concurrent free list so the cache will do so.
auto storageHead = C.ExtendedStorageHead.load(std::memory_order_relaxed);
while (storageHead) {
auto current = storageHead;
auto newHead = current->next;
if (C.ExtendedStorageHead.compare_exchange_weak(
storageHead, newHead, std::memory_order_release,
std::memory_order_relaxed)) {
ConcurrentFreeListNode::add(&freeListHead, current);
}
}
});
}
void swift::addImageProtocolConformanceBlockCallbackUnsafe(
const void *baseAddress,
const void *conformances, uintptr_t conformancesSize) {
assert(conformancesSize % sizeof(ProtocolConformanceRecord) == 0 &&
"conformances section not a multiple of ProtocolConformanceRecord");
// Conformance cache should always be sufficiently initialized by this point.
auto &C = Conformances.unsafeGetAlreadyInitialized();
#if USE_DYLD_SHARED_CACHE_CONFORMANCE_TABLES
// If any image in the shared cache is overridden, we need to scan all
// conformance sections in the shared cache. The pre-built table does NOT work
// if the protocol, type, or descriptor are in overridden images. Example:
//
// libX.dylib: struct S {}
// libY.dylib: protocol P {}
// libZ.dylib: extension S: P {}
//
// If libX or libY are overridden, then dyld will not return the S: P
// conformance from libZ. But that conformance still exists and we must still
// return it! Therefore we must scan libZ (and all other dylibs) even though
// it is not overridden.
if (!dyld_shared_cache_some_image_overridden()) {
// Sections in the shared cache are ignored in favor of the shared cache's
// pre-built tables.
if (C.inSharedCache(conformances)) {
DYLD_CONFORMANCES_LOG(
"Skipping conformances section %p in the shared cache", conformances);
if (C.validateDyldResults)
C.DyldOptimizedSections.push_back(
ConformanceSection{conformances, conformancesSize});
return;
#if DYLD_FIND_PROTOCOL_ON_DISK_CONFORMANCE_DEFINED
} else if (&_dyld_has_preoptimized_swift_protocol_conformances &&
_dyld_has_preoptimized_swift_protocol_conformances(
reinterpret_cast<const mach_header *>(baseAddress))) {
// dyld may optimize images outside the shared cache. Skip those too.
DYLD_CONFORMANCES_LOG(
"Skipping conformances section %p optimized by dyld", conformances);
if (C.validateDyldResults)
C.DyldOptimizedSections.push_back(
ConformanceSection{conformances, conformancesSize});
return;
#endif
} else {
DYLD_CONFORMANCES_LOG(
"Adding conformances section %p outside the shared cache",
conformances);
}
}
#endif
// If we have a section, enqueue the conformances for lookup.
_registerProtocolConformances(
C, ConformanceSection{conformances, conformancesSize});
}
void swift::addImageProtocolConformanceBlockCallback(
const void *baseAddress,
const void *conformances, uintptr_t conformancesSize) {
Conformances.get();
addImageProtocolConformanceBlockCallbackUnsafe(baseAddress,
conformances,
conformancesSize);
}
void
swift::swift_registerProtocolConformances(const ProtocolConformanceRecord *begin,
const ProtocolConformanceRecord *end){
auto &C = Conformances.get();
_registerProtocolConformances(C, ConformanceSection{begin, end});
}
/// Search for a conformance descriptor in the ConformanceCache.
/// First element of the return value is `true` if the result is authoritative
/// i.e. the result is for the type itself and not a superclass. If `false`
/// then we cached a conformance on a superclass, but that may be overridden.
/// A return value of `{ false, { } }` indicates nothing was cached.
static std::pair<bool, ConformanceLookupResult>
searchInConformanceCache(const Metadata *type,
const ProtocolDescriptor *protocol,
bool instantiateSuperclassMetadata) {
auto &C = Conformances.get();
auto origType = type;
auto snapshot = C.Cache.snapshot();
MaybeIncompleteSuperclassIterator superclassIterator{
type, instantiateSuperclassMetadata};
for (; auto type = superclassIterator.metadata; ++superclassIterator) {
if (auto *Value = snapshot.find(ConformanceCacheKey(type, protocol))) {
return { type == origType, Value->getResult() };
}
}
// We did not find a cache entry.
return { false, ConformanceLookupResult{} };
}
/// Get the appropriate context descriptor for a type. If the descriptor is a
/// foreign type descriptor, also return its identity string.
static std::pair<const ContextDescriptor *, llvm::StringRef>
getContextDescriptor(const Metadata *conformingType) {
const auto *description = conformingType->getTypeContextDescriptor();
if (description) {
if (description->hasForeignMetadataInitialization()) {
auto identity = ParsedTypeIdentity::parse(description).FullIdentity;
return {description, identity};
}
return {description, {}};
}
// Handle single-protocol existential types for self-conformance.
auto *existentialType = dyn_cast<ExistentialTypeMetadata>(conformingType);
if (existentialType == nullptr ||
existentialType->getProtocols().size() != 1 ||
existentialType->getSuperclassConstraint() != nullptr)
return {nullptr, {}};
auto proto = existentialType->getProtocols()[0];
#if SWIFT_OBJC_INTEROP
if (proto.isObjC())
return {nullptr, {}};
#endif
return {proto.getSwiftProtocol(), {}};
}
namespace {
/// Describes a protocol conformance "candidate" that can be checked
/// against a type metadata.
class ConformanceCandidate {
const void *candidate;
bool candidateIsMetadata;
public:
ConformanceCandidate() : candidate(0), candidateIsMetadata(false) { }
ConformanceCandidate(const ProtocolConformanceDescriptor &conformance)
: ConformanceCandidate()
{
if (auto description = conformance.getTypeDescriptor()) {
candidate = description;
candidateIsMetadata = false;
return;
}
if (auto metadata = conformance.getCanonicalTypeMetadata()) {
candidate = metadata;
candidateIsMetadata = true;
return;
}
}
/// Whether the conforming type exactly matches the conformance candidate.
bool matches(const Metadata *conformingType) const {
// Check whether the types match.
if (candidateIsMetadata && conformingType == candidate)
return true;
// Check whether the nominal type descriptors match.
if (!candidateIsMetadata) {
const auto *description = std::get<const ContextDescriptor *>(
getContextDescriptor(conformingType));
auto candidateDescription =
static_cast<const ContextDescriptor *>(candidate);
if (description && equalContexts(description, candidateDescription))
return true;
}
return false;
}
/// Retrieve the type that matches the conformance candidate, which may
/// be a superclass of the given type. Returns null if this type does not
/// match this conformance, along with the final metadata state of the
/// superclass iterator.
std::pair<const Metadata *, std::optional<MetadataState>>
getMatchingType(const Metadata *conformingType,
bool instantiateSuperclassMetadata) const {
MaybeIncompleteSuperclassIterator superclassIterator{
conformingType, instantiateSuperclassMetadata};
for (; auto conformingType = superclassIterator.metadata;
++superclassIterator) {
if (matches(conformingType))
return {conformingType, std::nullopt};
}
return {nullptr, superclassIterator.state};
}
};
}
static void validateDyldResults(
ConformanceState &C, const Metadata *type,
const ProtocolDescriptor *protocol,
ConformanceLookupResult dyldCachedWitnessTable,
const ProtocolConformanceDescriptor *dyldCachedConformanceDescriptor,
bool instantiateSuperclassMetadata) {
#if USE_DYLD_SHARED_CACHE_CONFORMANCE_TABLES
if (!C.dyldOptimizationsActive() || !C.validateDyldResults)
return;
llvm::SmallVector<const ProtocolConformanceDescriptor *, 8> conformances;
for (auto §ion : C.DyldOptimizedSections.snapshot()) {
for (const auto &record : section) {
auto &descriptor = *record.get();
if (descriptor.getProtocol() != protocol)
continue;
ConformanceCandidate candidate(descriptor);
if (std::get<const Metadata *>(
candidate.getMatchingType(type, instantiateSuperclassMetadata)))