-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathMetadataLookup.cpp
2520 lines (2153 loc) · 88 KB
/
MetadataLookup.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
//===--- MetadataLookup.cpp - Swift Language Type Name Lookup -------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Implementations of runtime functions for looking up a type by name.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Lazy.h"
#include "swift/Demangling/Demangler.h"
#include "swift/Demangling/TypeDecoder.h"
#include "swift/Reflection/Records.h"
#include "swift/ABI/TypeIdentity.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/Concurrent.h"
#include "swift/Runtime/Debug.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Runtime/Mutex.h"
#include "swift/Strings.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/StringExtras.h"
#include "Private.h"
#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "ImageInspection.h"
#include <functional>
#include <vector>
#include <list>
using namespace swift;
using namespace Demangle;
using namespace reflection;
#if SWIFT_OBJC_INTEROP
#include <objc/runtime.h>
#include <objc/message.h>
#include <objc/objc.h>
#include <dlfcn.h>
#endif
/// A Demangler suitable for resolving runtime type metadata strings.
template <class Base = Demangler>
class DemanglerForRuntimeTypeResolution : public Base {
public:
using Base::demangleSymbol;
using Base::demangleType;
// Force callers to explicitly pass `nullptr` to demangleSymbol or
// demangleType if they don't want to demangle symbolic references.
NodePointer demangleSymbol(StringRef symbolName) = delete;
NodePointer demangleType(StringRef typeName) = delete;
NodePointer demangleTypeRef(StringRef symbolName) {
// Resolve symbolic references to type contexts into the absolute address of
// the type context descriptor, so that if we see a symbolic reference in
// the mangled name we can immediately find the associated metadata.
return Base::demangleType(symbolName,
ResolveAsSymbolicReference(*this));
}
};
/// Resolve the relative reference in a mangled symbolic reference.
static uintptr_t resolveSymbolicReferenceOffset(SymbolicReferenceKind kind,
Directness isIndirect,
int32_t offset,
const void *base) {
auto ptr = detail::applyRelativeOffset(base, offset);
// Indirect references may be authenticated in a way appropriate for the
// referent.
if (isIndirect == Directness::Indirect) {
switch (kind) {
case SymbolicReferenceKind::Context: {
ContextDescriptor *contextPtr =
*(const TargetSignedContextPointer<InProcess> *)ptr;
return (uintptr_t)contextPtr;
}
case SymbolicReferenceKind::AccessorFunctionReference: {
swift_unreachable("should not be indirectly referenced");
}
}
swift_unreachable("unknown symbolic reference kind");
} else {
return ptr;
}
}
NodePointer
ResolveAsSymbolicReference::operator()(SymbolicReferenceKind kind,
Directness isIndirect,
int32_t offset,
const void *base) {
// Resolve the absolute pointer to the entity being referenced.
auto ptr = resolveSymbolicReferenceOffset(kind, isIndirect, offset, base);
// Figure out this symbolic reference's grammatical role.
Node::Kind nodeKind;
bool isType;
switch (kind) {
case Demangle::SymbolicReferenceKind::Context: {
auto descriptor = (const ContextDescriptor *)ptr;
switch (descriptor->getKind()) {
case ContextDescriptorKind::Protocol:
nodeKind = Node::Kind::ProtocolSymbolicReference;
isType = false;
break;
case ContextDescriptorKind::OpaqueType:
nodeKind = Node::Kind::OpaqueTypeDescriptorSymbolicReference;
isType = false;
break;
default:
if (auto typeContext = dyn_cast<TypeContextDescriptor>(descriptor)) {
nodeKind = Node::Kind::TypeSymbolicReference;
isType = true;
break;
}
// References to other kinds of context aren't yet implemented.
return nullptr;
}
break;
}
case Demangle::SymbolicReferenceKind::AccessorFunctionReference: {
// Save the pointer to the accessor function. We can't demangle it any
// further as AST, but the consumer of the demangle tree may be able to
// invoke the function to resolve the thing they're trying to access.
nodeKind = Node::Kind::AccessorFunctionReference;
isType = false;
#if SWIFT_PTRAUTH
// The pointer refers to an accessor function, which we need to sign.
ptr = (uintptr_t)ptrauth_sign_unauthenticated((void*)ptr,
ptrauth_key_function_pointer, 0);
#endif
break;
}
}
auto node = Dem.createNode(nodeKind, ptr);
if (isType) {
auto typeNode = Dem.createNode(Node::Kind::Type);
typeNode->addChild(node, Dem);
node = typeNode;
}
return node;
}
static NodePointer
_buildDemanglingForSymbolicReference(SymbolicReferenceKind kind,
const void *resolvedReference,
Demangler &Dem) {
switch (kind) {
case SymbolicReferenceKind::Context:
return _buildDemanglingForContext(
(const ContextDescriptor *)resolvedReference, {}, Dem);
case SymbolicReferenceKind::AccessorFunctionReference:
#if SWIFT_PTRAUTH
// The pointer refers to an accessor function, which we need to sign.
resolvedReference = ptrauth_sign_unauthenticated(resolvedReference,
ptrauth_key_function_pointer, 0);
#endif
return Dem.createNode(Node::Kind::AccessorFunctionReference,
(uintptr_t)resolvedReference);
}
swift_unreachable("invalid symbolic reference kind");
}
NodePointer
ResolveToDemanglingForContext::operator()(SymbolicReferenceKind kind,
Directness isIndirect,
int32_t offset,
const void *base) {
auto ptr = resolveSymbolicReferenceOffset(kind, isIndirect, offset, base);
return _buildDemanglingForSymbolicReference(kind, (const void *)ptr, Dem);
}
NodePointer
ExpandResolvedSymbolicReferences::operator()(SymbolicReferenceKind kind,
const void *ptr) {
return _buildDemanglingForSymbolicReference(kind, (const void *)ptr, Dem);
}
#pragma mark Nominal type descriptor cache
// Type Metadata Cache.
namespace {
struct TypeMetadataSection {
const TypeMetadataRecord *Begin, *End;
const TypeMetadataRecord *begin() const {
return Begin;
}
const TypeMetadataRecord *end() const {
return End;
}
};
struct NominalTypeDescriptorCacheEntry {
private:
const char *Name;
size_t NameLength;
const ContextDescriptor *Description;
public:
NominalTypeDescriptorCacheEntry(const llvm::StringRef name,
const ContextDescriptor *description)
: Description(description) {
char *nameCopy = reinterpret_cast<char *>(malloc(name.size()));
memcpy(nameCopy, name.data(), name.size());
Name = nameCopy;
NameLength = name.size();
}
const ContextDescriptor *getDescription() const { return Description; }
bool matchesKey(llvm::StringRef aName) {
return aName == llvm::StringRef{Name, NameLength};
}
friend llvm::hash_code
hash_value(const NominalTypeDescriptorCacheEntry &value) {
return hash_value(llvm::StringRef{value.Name, value.NameLength});
}
template <class... T>
static size_t getExtraAllocationSize(T &&... ignored) {
return 0;
}
};
} // end anonymous namespace
struct TypeMetadataPrivateState {
ConcurrentReadableHashMap<NominalTypeDescriptorCacheEntry> NominalCache;
ConcurrentReadableArray<TypeMetadataSection> SectionsToScan;
TypeMetadataPrivateState() {
initializeTypeMetadataRecordLookup();
}
};
static Lazy<TypeMetadataPrivateState> TypeMetadataRecords;
static void
_registerTypeMetadataRecords(TypeMetadataPrivateState &T,
const TypeMetadataRecord *begin,
const TypeMetadataRecord *end) {
T.SectionsToScan.push_back(TypeMetadataSection{begin, end});
}
void swift::addImageTypeMetadataRecordBlockCallbackUnsafe(
const void *records, uintptr_t recordsSize) {
assert(recordsSize % sizeof(TypeMetadataRecord) == 0
&& "weird-sized type metadata section?!");
// If we have a section, enqueue the type metadata for lookup.
auto recordBytes = reinterpret_cast<const char *>(records);
auto recordsBegin
= reinterpret_cast<const TypeMetadataRecord*>(records);
auto recordsEnd
= reinterpret_cast<const TypeMetadataRecord*>(recordBytes + recordsSize);
// Type metadata cache should always be sufficiently initialized by this
// point. Attempting to go through get() may also lead to an infinite loop,
// since we register records during the initialization of
// TypeMetadataRecords.
_registerTypeMetadataRecords(TypeMetadataRecords.unsafeGetAlreadyInitialized(),
recordsBegin, recordsEnd);
}
void swift::addImageTypeMetadataRecordBlockCallback(const void *records,
uintptr_t recordsSize) {
TypeMetadataRecords.get();
addImageTypeMetadataRecordBlockCallbackUnsafe(records, recordsSize);
}
void
swift::swift_registerTypeMetadataRecords(const TypeMetadataRecord *begin,
const TypeMetadataRecord *end) {
auto &T = TypeMetadataRecords.get();
_registerTypeMetadataRecords(T, begin, end);
}
static const ContextDescriptor *
_findContextDescriptor(Demangle::NodePointer node,
Demangle::Demangler &Dem);
/// Find the context descriptor for the type extended by the given extension.
///
/// If \p maybeExtension isn't actually an extension context, returns nullptr.
static const ContextDescriptor *
_findExtendedTypeContextDescriptor(const ContextDescriptor *maybeExtension,
Demangler &demangler,
Demangle::NodePointer *demangledNode
= nullptr) {
auto extension = dyn_cast<ExtensionContextDescriptor>(maybeExtension);
if (!extension)
return nullptr;
Demangle::NodePointer localNode;
Demangle::NodePointer &node = demangledNode ? *demangledNode : localNode;
auto mangledName = extension->getMangledExtendedContext();
node = demangler.demangleType(mangledName,
ResolveAsSymbolicReference(demangler));
if (!node)
return nullptr;
if (node->getKind() == Node::Kind::Type) {
if (node->getNumChildren() < 1)
return nullptr;
node = node->getChild(0);
}
if (Demangle::isSpecialized(node)) {
node = Demangle::getUnspecialized(node, demangler);
}
return _findContextDescriptor(node, demangler);
}
/// Recognize imported tag types, which have a special mangling rule.
///
/// This should be kept in sync with the AST mangler and with
/// buildContextDescriptorMangling in MetadataReader.
bool swift::_isCImportedTagType(const TypeContextDescriptor *type,
const ParsedTypeIdentity &identity) {
// Tag types are always imported as structs or enums.
if (type->getKind() != ContextDescriptorKind::Enum &&
type->getKind() != ContextDescriptorKind::Struct)
return false;
// Not a typedef imported as a nominal type.
if (identity.isCTypedef())
return false;
// Not a related entity.
if (identity.isAnyRelatedEntity())
return false;
// Imported from C.
return type->Parent->isCImportedContext();
}
ParsedTypeIdentity
ParsedTypeIdentity::parse(const TypeContextDescriptor *type) {
ParsedTypeIdentity result;
// The first component is the user-facing name and (unless overridden)
// the ABI name.
StringRef component = type->Name.get();
result.UserFacingName = component;
// If we don't have import info, we're done.
if (!type->getTypeContextDescriptorFlags().hasImportInfo()) {
result.FullIdentity = result.UserFacingName;
return result;
}
// Otherwise, start parsing the import information.
result.ImportInfo.emplace();
// The identity starts with the user-facing name.
const char *startOfIdentity = component.begin();
const char *endOfIdentity = component.end();
#ifndef NDEBUG
enum {
AfterName,
AfterABIName,
AfterSymbolNamespace,
AfterRelatedEntityName,
AfterIdentity,
} stage = AfterName;
#endif
while (true) {
// Parse the next component. If it's empty, we're done.
component = StringRef(component.end() + 1);
if (component.empty()) break;
// Update the identity bounds and assert that the identity
// components are in the right order.
auto kind = TypeImportComponent(component[0]);
if (kind == TypeImportComponent::ABIName) {
#ifndef NDEBUG
assert(stage < AfterABIName);
stage = AfterABIName;
assert(result.UserFacingName != component.drop_front(1) &&
"user-facing name was same as the ABI name");
#endif
startOfIdentity = component.begin() + 1;
endOfIdentity = component.end();
} else if (kind == TypeImportComponent::SymbolNamespace) {
#ifndef NDEBUG
assert(stage < AfterSymbolNamespace);
stage = AfterSymbolNamespace;
#endif
endOfIdentity = component.end();
} else if (kind == TypeImportComponent::RelatedEntityName) {
#ifndef NDEBUG
assert(stage < AfterRelatedEntityName);
stage = AfterRelatedEntityName;
#endif
endOfIdentity = component.end();
} else {
#ifndef NDEBUG
// Anything else is assumed to not be part of the identity.
stage = AfterIdentity;
#endif
}
// Collect the component, whatever it is.
result.ImportInfo->collect</*asserting*/true>(component);
}
assert(stage != AfterName && "no components?");
// Record the full identity.
result.FullIdentity =
StringRef(startOfIdentity, endOfIdentity - startOfIdentity);
return result;
}
#if SWIFT_OBJC_INTEROP
/// Determine whether the two demangle trees both refer to the same
/// Objective-C class or protocol referenced by name.
static bool sameObjCTypeManglings(Demangle::NodePointer node1,
Demangle::NodePointer node2) {
// Entities need to be of the same kind.
if (node1->getKind() != node2->getKind())
return false;
auto name1 = Demangle::getObjCClassOrProtocolName(node1);
if (!name1) return false;
auto name2 = Demangle::getObjCClassOrProtocolName(node2);
if (!name2) return false;
return *name1 == *name2;
}
#endif
bool
swift::_contextDescriptorMatchesMangling(const ContextDescriptor *context,
Demangle::NodePointer node) {
while (context) {
if (node->getKind() == Demangle::Node::Kind::Type)
node = node->getChild(0);
// We can directly match symbolic references to the current context.
if (node) {
if (node->getKind() == Demangle::Node::Kind::TypeSymbolicReference
|| node->getKind() == Demangle::Node::Kind::ProtocolSymbolicReference){
if (equalContexts(context,
reinterpret_cast<const ContextDescriptor *>(node->getIndex()))) {
return true;
}
}
}
switch (context->getKind()) {
case ContextDescriptorKind::Module: {
auto module = cast<ModuleContextDescriptor>(context);
// Match to a mangled module name.
if (node->getKind() != Demangle::Node::Kind::Module)
return false;
if (!node->getText().equals(module->Name.get()))
return false;
node = nullptr;
break;
}
case ContextDescriptorKind::Extension: {
auto extension = cast<ExtensionContextDescriptor>(context);
// Check whether the extension context matches the mangled context.
if (node->getKind() != Demangle::Node::Kind::Extension)
return false;
if (node->getNumChildren() < 2)
return false;
// Check that the context being extended matches as well.
auto extendedContextNode = node->getChild(1);
DemanglerForRuntimeTypeResolution<> demangler;
auto extendedDescriptorFromNode =
_findContextDescriptor(extendedContextNode, demangler);
Demangle::NodePointer extendedContextDemangled;
auto extendedDescriptorFromDemangled =
_findExtendedTypeContextDescriptor(extension, demangler,
&extendedContextDemangled);
// Determine whether the contexts match.
bool contextsMatch =
extendedDescriptorFromNode && extendedDescriptorFromDemangled &&
equalContexts(extendedDescriptorFromNode,
extendedDescriptorFromDemangled);
#if SWIFT_OBJC_INTEROP
// If we have manglings of the same Objective-C type, the contexts match.
if (!contextsMatch &&
(!extendedDescriptorFromNode || !extendedDescriptorFromDemangled) &&
sameObjCTypeManglings(extendedContextNode,
extendedContextDemangled)) {
contextsMatch = true;
}
#endif
if (!contextsMatch)
return false;
// Check whether the generic signature of the extension matches the
// mangled constraints, if any.
if (node->getNumChildren() >= 3) {
// NB: If we ever support extensions with independent generic arguments
// like `extension <T> Array where Element == Optional<T>`, we'd need
// to look at the mangled context name to match up generic arguments.
// That would probably need a new extension mangling form, though.
// TODO
}
// The parent context of the extension should match in the mangling and
// context descriptor.
node = node->getChild(0);
break;
}
case ContextDescriptorKind::Protocol:
// Match a protocol context.
if (node->getKind() == Demangle::Node::Kind::Protocol) {
auto proto = llvm::cast<ProtocolDescriptor>(context);
auto nameNode = node->getChild(1);
if (nameNode->getKind() != Demangle::Node::Kind::Identifier)
return false;
if (nameNode->getText() == proto->Name.get()) {
node = node->getChild(0);
break;
}
}
return false;
default:
if (auto type = llvm::dyn_cast<TypeContextDescriptor>(context)) {
llvm::Optional<ParsedTypeIdentity> _identity;
auto getIdentity = [&]() -> const ParsedTypeIdentity & {
if (_identity) return *_identity;
_identity = ParsedTypeIdentity::parse(type);
return *_identity;
};
switch (node->getKind()) {
// If the mangled name doesn't indicate a type kind, accept anything.
// Otherwise, try to match them up.
case Demangle::Node::Kind::OtherNominalType:
break;
case Demangle::Node::Kind::Structure:
// We allow non-structs to match Kind::Structure if they are
// imported C tag types. This is necessary because we artificially
// make imported C tag types Kind::Structure.
if (type->getKind() != ContextDescriptorKind::Struct &&
!_isCImportedTagType(type, getIdentity()))
return false;
break;
case Demangle::Node::Kind::Class:
if (type->getKind() != ContextDescriptorKind::Class)
return false;
break;
case Demangle::Node::Kind::Enum:
if (type->getKind() != ContextDescriptorKind::Enum)
return false;
break;
case Demangle::Node::Kind::TypeAlias:
if (!getIdentity().isCTypedef())
return false;
break;
default:
return false;
}
auto nameNode = node->getChild(1);
// Declarations synthesized by the Clang importer get a small tag
// string in addition to their name.
if (nameNode->getKind() == Demangle::Node::Kind::RelatedEntityDeclName){
if (!getIdentity().isRelatedEntity(
nameNode->getFirstChild()->getText()))
return false;
nameNode = nameNode->getChild(1);
} else if (getIdentity().isAnyRelatedEntity()) {
return false;
}
// We should only match public or internal declarations with stable
// names. The runtime metadata for private declarations would be
// anonymized.
if (nameNode->getKind() == Demangle::Node::Kind::Identifier) {
if (nameNode->getText() != getIdentity().getABIName())
return false;
node = node->getChild(0);
break;
}
return false;
}
// We don't know about this kind of context, or it doesn't have a stable
// name we can match to.
return false;
}
context = context->Parent;
}
// We should have reached the top of the node tree at the same time we reached
// the top of the context tree.
if (node)
return false;
return true;
}
// returns the nominal type descriptor for the type named by typeName
static const ContextDescriptor *
_searchTypeMetadataRecords(TypeMetadataPrivateState &T,
Demangle::NodePointer node) {
for (auto §ion : T.SectionsToScan.snapshot()) {
for (const auto &record : section) {
if (auto context = record.getContextDescriptor()) {
if (_contextDescriptorMatchesMangling(context, node)) {
return context;
}
}
}
}
return nullptr;
}
#define DESCRIPTOR_MANGLING_SUFFIX_Structure Mn
#define DESCRIPTOR_MANGLING_SUFFIX_Enum Mn
#define DESCRIPTOR_MANGLING_SUFFIX_Protocol Mp
#define DESCRIPTOR_MANGLING_SUFFIX_(X) X
#define DESCRIPTOR_MANGLING_SUFFIX(KIND) \
DESCRIPTOR_MANGLING_SUFFIX_(DESCRIPTOR_MANGLING_SUFFIX_ ## KIND)
#define DESCRIPTOR_MANGLING_(CHAR, SUFFIX) \
$sS ## CHAR ## SUFFIX
#define DESCRIPTOR_MANGLING(CHAR, SUFFIX) DESCRIPTOR_MANGLING_(CHAR, SUFFIX)
#define STANDARD_TYPE(KIND, MANGLING, TYPENAME) \
extern "C" const ContextDescriptor DESCRIPTOR_MANGLING(MANGLING, DESCRIPTOR_MANGLING_SUFFIX(KIND));
#if !SWIFT_OBJC_INTEROP
# define OBJC_INTEROP_STANDARD_TYPE(KIND, MANGLING, TYPENAME)
#endif
#include "swift/Demangling/StandardTypesMangling.def"
static const ContextDescriptor *
_findContextDescriptor(Demangle::NodePointer node,
Demangle::Demangler &Dem) {
NodePointer symbolicNode = node;
if (symbolicNode->getKind() == Node::Kind::Type)
symbolicNode = symbolicNode->getChild(0);
// If we have a symbolic reference to a context, resolve it immediately.
if (symbolicNode->getKind() == Node::Kind::TypeSymbolicReference) {
return cast<TypeContextDescriptor>(
(const ContextDescriptor *)symbolicNode->getIndex());
}
// Fast-path lookup for standard library type references with short manglings.
if (symbolicNode->getNumChildren() >= 2
&& symbolicNode->getChild(0)->getKind() == Node::Kind::Module
&& symbolicNode->getChild(0)->getText().equals("Swift")
&& symbolicNode->getChild(1)->getKind() == Node::Kind::Identifier) {
auto name = symbolicNode->getChild(1)->getText();
#define STANDARD_TYPE(KIND, MANGLING, TYPENAME) \
if (name.equals(#TYPENAME)) { \
return &DESCRIPTOR_MANGLING(MANGLING, DESCRIPTOR_MANGLING_SUFFIX(KIND)); \
}
#if !SWIFT_OBJC_INTEROP
# define OBJC_INTEROP_STANDARD_TYPE(KIND, MANGLING, TYPENAME)
#endif
#include "swift/Demangling/StandardTypesMangling.def"
}
const ContextDescriptor *foundContext = nullptr;
auto &T = TypeMetadataRecords.get();
// Nothing to resolve if have a generic parameter.
if (symbolicNode->getKind() == Node::Kind::DependentGenericParamType)
return nullptr;
StringRef mangledName =
Demangle::mangleNode(node, ExpandResolvedSymbolicReferences(Dem), Dem);
// Look for an existing entry.
// Find the bucket for the metadata entry.
{
auto snapshot = T.NominalCache.snapshot();
if (auto Value = snapshot.find(mangledName))
return Value->getDescription();
}
// Check type metadata records
// Scan any newly loaded images for context descriptors, then try the context
foundContext = _searchTypeMetadataRecords(T, node);
// Check protocol conformances table. Note that this has no support for
// resolving generic types yet.
if (!foundContext)
foundContext = _searchConformancesByMangledTypeName(node);
if (foundContext)
T.NominalCache.getOrInsert(mangledName, [&](NominalTypeDescriptorCacheEntry
*entry,
bool created) {
if (created)
new (entry) NominalTypeDescriptorCacheEntry{mangledName, foundContext};
return true;
});
return foundContext;
}
#pragma mark Protocol descriptor cache
namespace {
struct ProtocolSection {
const ProtocolRecord *Begin, *End;
const ProtocolRecord *begin() const {
return Begin;
}
const ProtocolRecord *end() const {
return End;
}
};
struct ProtocolDescriptorCacheEntry {
private:
const char *Name;
size_t NameLength;
const ProtocolDescriptor *Description;
public:
ProtocolDescriptorCacheEntry(const llvm::StringRef name,
const ProtocolDescriptor *description)
: Description(description) {
char *nameCopy = reinterpret_cast<char *>(malloc(name.size()));
memcpy(nameCopy, name.data(), name.size());
Name = nameCopy;
NameLength = name.size();
}
const ProtocolDescriptor *getDescription() const { return Description; }
bool matchesKey(llvm::StringRef aName) {
return aName == llvm::StringRef{Name, NameLength};
}
friend llvm::hash_code
hash_value(const ProtocolDescriptorCacheEntry &value) {
return hash_value(llvm::StringRef{value.Name, value.NameLength});
}
template <class... T>
static size_t getExtraAllocationSize(T &&... ignored) {
return 0;
}
};
struct ProtocolMetadataPrivateState {
ConcurrentReadableHashMap<ProtocolDescriptorCacheEntry> ProtocolCache;
ConcurrentReadableArray<ProtocolSection> SectionsToScan;
ProtocolMetadataPrivateState() {
initializeProtocolLookup();
}
};
static Lazy<ProtocolMetadataPrivateState> Protocols;
}
static void
_registerProtocols(ProtocolMetadataPrivateState &C,
const ProtocolRecord *begin,
const ProtocolRecord *end) {
C.SectionsToScan.push_back(ProtocolSection{begin, end});
}
void swift::addImageProtocolsBlockCallbackUnsafe(const void *protocols,
uintptr_t protocolsSize) {
assert(protocolsSize % sizeof(ProtocolRecord) == 0 &&
"protocols section not a multiple of ProtocolRecord");
// If we have a section, enqueue the protocols for lookup.
auto protocolsBytes = reinterpret_cast<const char *>(protocols);
auto recordsBegin
= reinterpret_cast<const ProtocolRecord *>(protocols);
auto recordsEnd
= reinterpret_cast<const ProtocolRecord *>(protocolsBytes + protocolsSize);
// Conformance cache should always be sufficiently initialized by this point.
_registerProtocols(Protocols.unsafeGetAlreadyInitialized(),
recordsBegin, recordsEnd);
}
void swift::addImageProtocolsBlockCallback(const void *protocols,
uintptr_t protocolsSize) {
Protocols.get();
addImageProtocolsBlockCallbackUnsafe(protocols, protocolsSize);
}
void swift::swift_registerProtocols(const ProtocolRecord *begin,
const ProtocolRecord *end) {
auto &C = Protocols.get();
_registerProtocols(C, begin, end);
}
static const ProtocolDescriptor *
_searchProtocolRecords(ProtocolMetadataPrivateState &C,
NodePointer node) {
for (auto §ion : C.SectionsToScan.snapshot()) {
for (const auto &record : section) {
if (auto protocol = record.Protocol.getPointer()) {
if (_contextDescriptorMatchesMangling(protocol, node))
return protocol;
}
}
}
return nullptr;
}
static const ProtocolDescriptor *
_findProtocolDescriptor(NodePointer node,
Demangle::Demangler &Dem,
std::string &mangledName) {
const ProtocolDescriptor *foundProtocol = nullptr;
auto &T = Protocols.get();
// If we have a symbolic reference to a context, resolve it immediately.
NodePointer symbolicNode = node;
if (symbolicNode->getKind() == Node::Kind::Type)
symbolicNode = symbolicNode->getChild(0);
if (symbolicNode->getKind() == Node::Kind::ProtocolSymbolicReference)
return cast<ProtocolDescriptor>(
(const ContextDescriptor *)symbolicNode->getIndex());
mangledName =
Demangle::mangleNode(node, ExpandResolvedSymbolicReferences(Dem), Dem).str();
// Look for an existing entry.
// Find the bucket for the metadata entry.
{
auto snapshot = T.ProtocolCache.snapshot();
if (auto Value = snapshot.find(mangledName))
return Value->getDescription();
}
// Check type metadata records
foundProtocol = _searchProtocolRecords(T, node);
if (foundProtocol) {
T.ProtocolCache.getOrInsert(mangledName, [&](ProtocolDescriptorCacheEntry
*entry,
bool created) {
if (created)
new (entry) ProtocolDescriptorCacheEntry{mangledName, foundProtocol};
return true;
});
}
return foundProtocol;
}
#pragma mark Type field descriptor cache
namespace {
struct FieldDescriptorCacheEntry {
private:
const Metadata *Type;
const FieldDescriptor *Description;
public:
FieldDescriptorCacheEntry(const Metadata *type,
const FieldDescriptor *description)
: Type(type), Description(description) {}
const FieldDescriptor *getDescription() { return Description; }
int compareWithKey(const Metadata *other) const {
auto a = (uintptr_t)Type;
auto b = (uintptr_t)other;
return a == b ? 0 : (a < b ? -1 : 1);
}
template <class... Args>
static size_t getExtraAllocationSize(Args &&... ignored) {
return 0;
}
};
} // namespace
#pragma mark Metadata lookup via mangled name
llvm::Optional<unsigned>
swift::_depthIndexToFlatIndex(unsigned depth, unsigned index,
llvm::ArrayRef<unsigned> paramCounts) {
// Out-of-bounds depth.
if (depth >= paramCounts.size()) return None;
// Compute the flat index.
unsigned flatIndex = index + (depth == 0 ? 0 : paramCounts[depth - 1]);
// Out-of-bounds index.
if (flatIndex >= paramCounts[depth]) return None;
return flatIndex;
}
/// Gather generic parameter counts from a context descriptor.
///
/// \returns true if the innermost descriptor is generic.
bool swift::_gatherGenericParameterCounts(
const ContextDescriptor *descriptor,
llvm::SmallVectorImpl<unsigned> &genericParamCounts,
Demangler &BorrowFrom) {
DemanglerForRuntimeTypeResolution<> demangler;
demangler.providePreallocatedMemory(BorrowFrom);
if (auto extension = _findExtendedTypeContextDescriptor(descriptor,
demangler)) {
// If we have a nominal type extension descriptor, extract the extended type
// and use that. If the extension is not nominal, then we can use the
// extension's own signature.
descriptor = extension;
}
// Once we hit a non-generic descriptor, we're done.
if (!descriptor->isGeneric()) return false;
// Recurse to record the parent context's generic parameters.
auto parent = descriptor->Parent.get();
(void)_gatherGenericParameterCounts(parent, genericParamCounts, demangler);
// Record a new level of generic parameters if the count exceeds the
// previous count.
unsigned parentCount = parent->getNumGenericParams();
unsigned myCount = descriptor->getNumGenericParams();
if (myCount > parentCount) {
genericParamCounts.push_back(myCount);
return true;
}
return false;
}
/// Retrieve the generic parameters introduced in this context.
static llvm::ArrayRef<GenericParamDescriptor>
getLocalGenericParams(const ContextDescriptor *context) {
if (!context->isGeneric())
return { };
// Determine where to start looking at generic parameters.
unsigned startParamIndex;
if (auto parent = context->Parent.get())
startParamIndex = parent->getNumGenericParams();
else
startParamIndex = 0;
auto genericContext = context->getGenericContext();
return genericContext->getGenericParams().slice(startParamIndex);
}