-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Metadata.h
5183 lines (4376 loc) · 189 KB
/
Metadata.h
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
//===--- Metadata.h - Swift Language ABI Metadata Support -------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Swift ABI describing metadata.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_ABI_METADATA_H
#define SWIFT_ABI_METADATA_H
#include <atomic>
#include <iterator>
#include <string>
#include <type_traits>
#include <utility>
#include <string.h>
#include "llvm/ADT/ArrayRef.h"
#include "swift/Strings.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Once.h"
#include "swift/ABI/GenericContext.h"
#include "swift/ABI/MetadataRef.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/ABI/System.h"
#include "swift/ABI/TargetLayout.h"
#include "swift/ABI/TrailingObjects.h"
#include "swift/ABI/ValueWitnessTable.h"
#include "swift/Basic/Malloc.h"
#include "swift/Basic/FlaggedPointer.h"
#include "swift/Basic/RelativePointer.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/Basic/Unreachable.h"
#include "swift/shims/HeapObject.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Casting.h"
namespace swift {
template <typename Runtime> struct TargetGenericMetadataInstantiationCache;
template <typename Runtime> struct TargetAnyClassMetadata;
template <typename Runtime> struct TargetAnyClassMetadataObjCInterop;
template <typename Runtime, typename TargetAnyClassMetadataVariant>
struct TargetClassMetadata;
template <typename Runtime> struct TargetStructMetadata;
template <typename Runtime> struct TargetOpaqueMetadata;
template <typename Runtime> struct TargetValueMetadata;
template <typename Runtime> struct TargetForeignClassMetadata;
template <typename Runtime> struct TargetForeignReferenceTypeMetadata;
template <typename Runtime>
struct swift_ptrauth_struct_context_descriptor(ContextDescriptor)
TargetContextDescriptor;
template <typename Runtime>
class swift_ptrauth_struct_context_descriptor(TypeContextDescriptor)
TargetTypeContextDescriptor;
template <typename Runtime>
class swift_ptrauth_struct_context_descriptor(ClassDescriptor)
TargetClassDescriptor;
template <typename Runtime>
class swift_ptrauth_struct_context_descriptor(ValueTypeDescriptor)
TargetValueTypeDescriptor;
template <typename Runtime>
class swift_ptrauth_struct_context_descriptor(EnumDescriptor)
TargetEnumDescriptor;
template <typename Runtime>
class swift_ptrauth_struct_context_descriptor(StructDescriptor)
TargetStructDescriptor;
template <typename Runtime> struct TargetGenericMetadataPattern;
template <typename Runtime> struct TargetProtocolConformanceDescriptor;
struct HeapObject;
class WeakReference;
struct UnownedReference;
using HeapObjectDestroyer =
SWIFT_CC(swift) void(SWIFT_CONTEXT HeapObject *);
/// The result of requesting type metadata. Generally the return value of
/// a function.
///
/// For performance and ABI matching across Swift/C++, functions returning
/// this type must use SWIFT_CC so that the components are returned as separate
/// values.
struct MetadataResponse {
/// The requested metadata.
const Metadata *Value;
/// The current state of the metadata returned. Always use this
/// instead of trying to inspect the metadata directly to see if it
/// satisfies the request. An incomplete metadata may be getting
/// initialized concurrently. But this can generally be ignored if
/// the metadata request was for abstract metadata or if the request
/// is blocking.
MetadataState State;
};
/// A dependency on the metadata progress of other type, indicating that
/// initialization of a metadata cannot progress until another metadata
/// reaches a particular state.
///
/// For performance, functions returning this type should use SWIFT_CC so
/// that the components are returned as separate values.
struct MetadataDependency {
/// Either null, indicating that initialization was successful, or
/// a metadata on which initialization depends for further progress.
const Metadata *Value;
/// The state that Metadata needs to be in before initialization
/// can continue.
MetadataState Requirement;
MetadataDependency() : Value(nullptr) {}
MetadataDependency(const Metadata *metadata, MetadataState requirement)
: Value(metadata), Requirement(requirement) {}
explicit operator bool() const { return Value != nullptr; }
bool operator==(MetadataDependency other) const {
assert(Value && other.Value);
return Value == other.Value &&
Requirement == other.Requirement;
}
};
/// Prefix of a metadata header, containing a pointer to the
/// type layout string.
template <typename Runtime>
struct TargetTypeMetadataLayoutPrefix {
TargetSignedPointer<Runtime, const uint8_t *
__ptrauth_swift_type_layout_string>
layoutString;
};
/// The header before a metadata object which appears on all type
/// metadata. Note that heap metadata are not necessarily type
/// metadata, even for objects of a heap type: for example, objects of
/// Objective-C type possess a form of heap metadata (an Objective-C
/// Class pointer), but this metadata lacks the type metadata header.
/// This case can be distinguished using the isTypeMetadata() flag
/// on ClassMetadata.
template <typename Runtime>
struct TargetTypeMetadataHeaderBase {
/// A pointer to the value-witnesses for this type. This is only
/// present for type metadata.
TargetPointer<Runtime, const TargetValueWitnessTable<Runtime>> ValueWitnesses;
};
template <typename Runtime>
struct TargetTypeMetadataHeader
: TargetTypeMetadataLayoutPrefix<Runtime>,
TargetTypeMetadataHeaderBase<Runtime> {
TargetTypeMetadataHeader() = default;
constexpr TargetTypeMetadataHeader(
const TargetTypeMetadataLayoutPrefix<Runtime> &layout,
const TargetTypeMetadataHeaderBase<Runtime> &header)
: TargetTypeMetadataLayoutPrefix<Runtime>(layout),
TargetTypeMetadataHeaderBase<Runtime>(header) {}
};
using TypeMetadataHeader = TargetTypeMetadataHeader<InProcess>;
/// A "full" metadata pointer is simply an adjusted address point on a
/// metadata object; it points to the beginning of the metadata's
/// allocation, rather than to the canonical address point of the
/// metadata object.
template <class T> struct FullMetadata : T::HeaderType, T {
typedef typename T::HeaderType HeaderType;
FullMetadata() = default;
constexpr FullMetadata(const HeaderType &header, const T &metadata)
: HeaderType(header), T(metadata) {}
template <class... Args>
constexpr FullMetadata(const HeaderType &header, Args &&...metadataArgs)
: HeaderType(header), T(std::forward<Args>(metadataArgs)...) {}
};
/// Given a canonical metadata pointer, produce the adjusted metadata pointer.
template <class T>
static inline FullMetadata<T> *asFullMetadata(T *metadata) {
return (FullMetadata<T>*) (((typename T::HeaderType*) metadata) - 1);
}
template <class T>
static inline const FullMetadata<T> *asFullMetadata(const T *metadata) {
return asFullMetadata(const_cast<T*>(metadata));
}
// std::result_of is busted in Xcode 5. This is a simplified reimplementation
// that isn't SFINAE-safe.
namespace {
template<typename T> struct _ResultOf;
template<typename R, typename...A>
struct _ResultOf<R(*)(A...)> {
using type = R;
};
}
using TypeContextDescriptor = TargetTypeContextDescriptor<InProcess>;
template<template <typename Runtime> class ObjCInteropKind, unsigned PointerSize>
using ExternalTypeContextDescriptor = TargetTypeContextDescriptor<External<ObjCInteropKind<RuntimeTarget<PointerSize>>>>;
// FIXME: https://github.com/apple/swift/issues/43763
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
/// Bounds for metadata objects.
template <typename Runtime>
struct TargetMetadataBounds {
using StoredSize = typename Runtime::StoredSize;
/// The negative extent of the metadata, in words.
uint32_t NegativeSizeInWords;
/// The positive extent of the metadata, in words.
uint32_t PositiveSizeInWords;
/// Return the total size of the metadata in bytes, including both
/// negatively- and positively-offset members.
StoredSize getTotalSizeInBytes() const {
return (StoredSize(NegativeSizeInWords) + StoredSize(PositiveSizeInWords))
* sizeof(void*);
}
/// Return the offset of the address point of the metadata from its
/// start, in bytes.
StoredSize getAddressPointInBytes() const {
return StoredSize(NegativeSizeInWords) * sizeof(void*);
}
};
using MetadataBounds = TargetMetadataBounds<InProcess>;
/// The common structure of all type metadata.
template <typename Runtime>
struct TargetMetadata {
using StoredPointer = typename Runtime::StoredPointer;
/// The basic header type.
typedef TargetTypeMetadataHeader<Runtime> HeaderType;
constexpr TargetMetadata()
: Kind(static_cast<StoredPointer>(MetadataKind::Class)) {}
constexpr TargetMetadata(MetadataKind Kind)
: Kind(static_cast<StoredPointer>(Kind)) {}
#if SWIFT_OBJC_INTEROP
protected:
constexpr TargetMetadata(TargetAnyClassMetadataObjCInterop<Runtime> *isa)
: Kind(reinterpret_cast<StoredPointer>(isa)) {}
#endif
private:
/// The kind. Only valid for non-class metadata; getKind() must be used to get
/// the kind value.
StoredPointer Kind;
public:
/// Get the metadata kind.
MetadataKind getKind() const {
return getEnumeratedMetadataKind(Kind);
}
/// Set the metadata kind.
void setKind(MetadataKind kind) {
Kind = static_cast<StoredPointer>(kind);
}
protected:
const TargetAnyClassMetadata<Runtime> *getClassISA() const {
return reinterpret_cast<const TargetAnyClassMetadata<Runtime> *>(Kind);
}
void setClassISA(const TargetAnyClassMetadata<Runtime> *isa) {
Kind = reinterpret_cast<StoredPointer>(isa);
}
public:
/// Is this a class object--the metadata record for a Swift class (which also
/// serves as the class object), or the class object for an ObjC class (which
/// is not metadata)?
bool isClassObject() const {
return static_cast<MetadataKind>(getKind()) == MetadataKind::Class;
}
/// Does the given metadata kind represent metadata for some kind of class?
static bool isAnyKindOfClass(MetadataKind k) {
switch (k) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
return true;
default:
return false;
}
}
/// Is this metadata for an existential type?
bool isAnyExistentialType() const {
switch (getKind()) {
case MetadataKind::ExistentialMetatype:
case MetadataKind::Existential:
return true;
default:
return false;
}
}
/// Is this either type metadata or a class object for any kind of class?
bool isAnyClass() const {
return isAnyKindOfClass(getKind());
}
const uint8_t *getLayoutString() const {
assert(hasLayoutString());
// Classes should not have layout strings
assert(!isAnyClass());
return asFullMetadata(this)->layoutString;
}
const TargetValueWitnessTable<Runtime> *getValueWitnesses() const {
return asFullMetadata(this)->ValueWitnesses;
}
const TypeLayout *getTypeLayout() const {
return getValueWitnesses()->getTypeLayout();
}
void setValueWitnesses(const ValueWitnessTable *table) {
asFullMetadata(this)->ValueWitnesses = table;
}
void setLayoutString(const uint8_t *layoutString) {
if (isAnyClass()) {
asFullMetadata(reinterpret_cast<TargetAnyClassMetadata<Runtime> *>(this))
->layoutString = layoutString;
} else {
asFullMetadata(this)->layoutString = layoutString;
}
}
bool hasLayoutString() const {
if (auto *contextDescriptor = getTypeContextDescriptor()) {
return contextDescriptor->hasLayoutString();
}
return false;
}
// Define forwarders for value witnesses. These invoke this metadata's value
// witness table with itself as the 'self' parameter.
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define FUNCTION_VALUE_WITNESS(WITNESS, UPPER, RET_TYPE, PARAM_TYPES) \
template<typename...A> \
_ResultOf<ValueWitnessTypes::WITNESS ## Unsigned>::type \
vw_##WITNESS(A &&...args) const { \
return getValueWitnesses()->WITNESS(std::forward<A>(args)..., this); \
}
#define DATA_VALUE_WITNESS(LOWER, UPPER, TYPE)
#include "swift/ABI/ValueWitness.def"
unsigned vw_getEnumTag(const OpaqueValue *value) const {
return getValueWitnesses()->_asEVWT()->getEnumTag(const_cast<OpaqueValue*>(value), this);
}
void vw_destructiveProjectEnumData(OpaqueValue *value) const {
getValueWitnesses()->_asEVWT()->destructiveProjectEnumData(value, this);
}
void vw_destructiveInjectEnumTag(OpaqueValue *value, unsigned tag) const {
getValueWitnesses()->_asEVWT()->destructiveInjectEnumTag(value, tag, this);
}
size_t vw_size() const {
return getValueWitnesses()->getSize();
}
size_t vw_alignment() const {
return getValueWitnesses()->getAlignment();
}
size_t vw_stride() const {
return getValueWitnesses()->getStride();
}
unsigned vw_getNumExtraInhabitants() const {
return getValueWitnesses()->getNumExtraInhabitants();
}
/// Allocate an out-of-line buffer if values of this type don't fit in the
/// ValueBuffer.
/// NOTE: This is not a box for copy-on-write existentials.
OpaqueValue *allocateBufferIn(ValueBuffer *buffer) const;
/// Get the address of the memory previously allocated in the ValueBuffer.
/// NOTE: This is not a box for copy-on-write existentials.
OpaqueValue *projectBufferFrom(ValueBuffer *buffer) const;
/// Deallocate an out-of-line buffer stored in 'buffer' if values of this type
/// are not stored inline in the ValueBuffer.
void deallocateBufferIn(ValueBuffer *buffer) const;
// Allocate an out-of-line buffer box (reference counted) if values of this
// type don't fit in the ValueBuffer.
// NOTE: This *is* a box for copy-on-write existentials.
OpaqueValue *allocateBoxForExistentialIn(ValueBuffer *Buffer) const;
// Deallocate an out-of-line buffer box if one is present.
void deallocateBoxForExistentialIn(ValueBuffer *Buffer) const;
/// Get the nominal type descriptor if this metadata describes a nominal type,
/// or return null if it does not.
ConstTargetMetadataPointer<Runtime, TargetTypeContextDescriptor>
getTypeContextDescriptor() const {
switch (getKind()) {
case MetadataKind::Class: {
const auto cls =
static_cast<const TargetClassMetadataType<Runtime> *>(this);
if (!cls->isTypeMetadata())
return nullptr;
if (cls->isArtificialSubclass())
return nullptr;
return cls->getDescription();
}
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
return static_cast<const TargetValueMetadata<Runtime> *>(this)
->Description;
case MetadataKind::ForeignClass:
return static_cast<const TargetForeignClassMetadata<Runtime> *>(this)
->Description;
case MetadataKind::ForeignReferenceType:
return static_cast<const TargetForeignReferenceTypeMetadata<Runtime> *>(this)
->Description;
default:
return nullptr;
}
}
/// Get the class object for this type if it has one, or return null if the
/// type is not a class (or not a class with a class object).
const TargetClassMetadataType<Runtime> *
getClassObject() const;
/// Retrieve the generic arguments of this type, if it has any.
ConstTargetMetadataPointer<Runtime, swift::TargetMetadata> const *
getGenericArgs() const {
auto description = getTypeContextDescriptor();
if (!description)
return nullptr;
auto generics = description->getGenericContext();
if (!generics)
return nullptr;
auto asWords = reinterpret_cast<
ConstTargetMetadataPointer<Runtime, swift::TargetMetadata> const *>(this);
return asWords + description->getGenericArgumentOffset();
}
bool satisfiesClassConstraint() const;
const TypeContextDescriptor *getDescription() const;
bool isStaticallySpecializedGenericMetadata() const;
bool isCanonicalStaticallySpecializedGenericMetadata() const;
#if SWIFT_OBJC_INTEROP
/// Get the ObjC class object for this type if it has one, or return null if
/// the type is not a class (or not a class with a class object).
/// This is allowed for InProcess values only.
template <typename R = Runtime>
typename std::enable_if<std::is_same<R, InProcess>::value, Class>::type
getObjCClassObject() const {
return reinterpret_cast<Class>(
const_cast<TargetClassMetadata<
InProcess, TargetAnyClassMetadataObjCInterop<InProcess>> *>(
getClassObject()));
}
#endif
#ifndef NDEBUG
[[deprecated("Only meant for use in the debugger")]] void dump() const;
#endif
protected:
friend struct TargetOpaqueMetadata<Runtime>;
/// Metadata should not be publicly copied or moved.
constexpr TargetMetadata(const TargetMetadata &) = default;
TargetMetadata &operator=(const TargetMetadata &) = default;
constexpr TargetMetadata(TargetMetadata &&) = default;
TargetMetadata &operator=(TargetMetadata &&) = default;
};
/// The common structure of opaque metadata. Adds nothing.
template <typename Runtime>
struct TargetOpaqueMetadata {
typedef TargetTypeMetadataHeaderBase<Runtime> HeaderType;
// We have to represent this as a member so we can list-initialize it.
TargetMetadata<Runtime> base;
};
/// The prefix on a heap metadata.
template <typename Runtime>
struct TargetHeapMetadataHeaderPrefix {
/// Destroy the object, returning the allocated size of the object
/// or 0 if the object shouldn't be deallocated.
TargetSignedPointer<Runtime, HeapObjectDestroyer *
__ptrauth_swift_heap_object_destructor>
destroy;
};
using HeapMetadataHeaderPrefix =
TargetHeapMetadataHeaderPrefix<InProcess>;
/// The header present on all heap metadata.
template <typename Runtime>
struct TargetHeapMetadataHeader
: TargetTypeMetadataLayoutPrefix<Runtime>,
TargetHeapMetadataHeaderPrefix<Runtime>,
TargetTypeMetadataHeaderBase<Runtime> {
constexpr TargetHeapMetadataHeader(
const TargetTypeMetadataLayoutPrefix<Runtime> &typeLayoutPrefix,
const TargetHeapMetadataHeaderPrefix<Runtime> &heapPrefix,
const TargetTypeMetadataHeaderBase<Runtime> &typePrefix)
: TargetTypeMetadataLayoutPrefix<Runtime>(typeLayoutPrefix),
TargetHeapMetadataHeaderPrefix<Runtime>(heapPrefix),
TargetTypeMetadataHeaderBase<Runtime>(typePrefix) {}
};
using HeapMetadataHeader =
TargetHeapMetadataHeader<InProcess>;
/// The common structure of all metadata for heap-allocated types. A
/// pointer to one of these can be retrieved by loading the 'isa'
/// field of any heap object, whether it was managed by Swift or by
/// Objective-C. However, when loading from an Objective-C object,
/// this metadata may not have the heap-metadata header, and it may
/// not be the Swift type metadata for the object's dynamic type.
template <typename Runtime>
struct TargetHeapMetadata : TargetMetadata<Runtime> {
using HeaderType = TargetHeapMetadataHeader<Runtime>;
TargetHeapMetadata() = default;
constexpr TargetHeapMetadata(MetadataKind kind)
: TargetMetadata<Runtime>(kind) {}
constexpr TargetHeapMetadata(TargetAnyClassMetadataObjCInterop<Runtime> *isa)
: TargetMetadata<Runtime>(isa) {}
HeapObjectDestroyer *getHeapObjectDestroyer() const {
return asFullMetadata(this)->destroy;
}
void setHeapObjectDestroyer(HeapObjectDestroyer *destroy) {
asFullMetadata(this)->destroy = destroy;
}
};
using HeapMetadata = TargetHeapMetadata<InProcess>;
/// An opaque descriptor describing a class or protocol method. References to
/// these descriptors appear in the method override table of a class context
/// descriptor, or a resilient witness table pattern, respectively.
///
/// Clients should not assume anything about the contents of this descriptor
/// other than it having 4 byte alignment.
template <typename Runtime>
struct TargetMethodDescriptor {
/// Flags describing the method.
MethodDescriptorFlags Flags;
/// The method implementation.
union {
TargetCompactFunctionPointer<Runtime, void> Impl;
TargetRelativeDirectPointer<Runtime, void> AsyncImpl;
};
// TODO: add method types or anything else needed for reflection.
void *getImpl() const {
if (Flags.isAsync()) {
return AsyncImpl.get();
} else {
return Impl.get();
}
}
};
using MethodDescriptor = TargetMethodDescriptor<InProcess>;
/// Header for a class vtable descriptor. This is a variable-sized
/// structure that describes how to find and parse a vtable
/// within the type metadata for a class.
template <typename Runtime>
struct TargetVTableDescriptorHeader {
using StoredPointer = typename Runtime::StoredPointer;
private:
/// The offset of the vtable for this class in its metadata, if any,
/// in words.
///
/// If this class has a resilient superclass, this offset is relative to the
/// the start of the immediate class's metadata. Otherwise, it is relative
/// to the metadata address point.
uint32_t VTableOffset;
public:
/// The number of vtable entries. This is the number of MethodDescriptor
/// records following the vtable header in the class's nominal type
/// descriptor, which is equal to the number of words this subclass's vtable
/// entries occupy in instantiated class metadata.
uint32_t VTableSize;
uint32_t getVTableOffset(const TargetClassDescriptor<Runtime> *description) const {
if (description->hasResilientSuperclass()) {
auto bounds = description->getMetadataBounds();
return (bounds.ImmediateMembersOffset / sizeof(StoredPointer)
+ VTableOffset);
}
return VTableOffset;
}
};
template<typename Runtime> struct TargetMethodDescriptor;
template<typename Runtime>
using TargetRelativeMethodDescriptorPointer =
RelativeIndirectablePointer<const TargetMethodDescriptor<Runtime>,
/*nullable*/ true>;
using RelativeMethodDescriptorPointer =
TargetRelativeMethodDescriptorPointer<InProcess>;
template<typename Runtime> struct TargetProtocolRequirement;
template<typename Runtime>
using TargetRelativeProtocolRequirementPointer =
RelativeIndirectablePointer<const TargetProtocolRequirement<Runtime>,
/*nullable*/ true>;
using RelativeProtocolRequirementPointer =
TargetRelativeProtocolRequirementPointer<InProcess>;
/// An entry in the method override table, referencing a method from one of our
/// ancestor classes, together with an implementation.
template <typename Runtime>
struct TargetMethodOverrideDescriptor {
/// The class containing the base method.
TargetRelativeContextPointer<Runtime> Class;
/// The base method.
TargetRelativeMethodDescriptorPointer<Runtime> Method;
/// The implementation of the override.
union {
TargetCompactFunctionPointer<Runtime, void, /*nullable*/ true> Impl;
TargetRelativeDirectPointer<Runtime, void, /*nullable*/ true> AsyncImpl;
};
void *getImpl() const {
auto *baseMethod = Method.get();
assert(baseMethod && "no base method");
if (baseMethod->Flags.isAsync()) {
return AsyncImpl.get();
} else {
return Impl.get();
}
}
};
/// Header for a class vtable override descriptor. This is a variable-sized
/// structure that provides implementations for overrides of methods defined
/// in superclasses.
template <typename Runtime>
struct TargetOverrideTableHeader {
/// The number of MethodOverrideDescriptor records following the vtable
/// override header in the class's nominal type descriptor.
uint32_t NumEntries;
};
/// The bounds of a class metadata object.
///
/// This type is a currency type and is not part of the ABI.
/// See TargetStoredClassMetadataBounds for the type of the class
/// metadata bounds variable.
template <typename Runtime>
struct TargetClassMetadataBounds : TargetMetadataBounds<Runtime> {
using StoredPointer = typename Runtime::StoredPointer;
using StoredSize = typename Runtime::StoredSize;
using StoredPointerDifference = typename Runtime::StoredPointerDifference;
using TargetMetadataBounds<Runtime>::NegativeSizeInWords;
using TargetMetadataBounds<Runtime>::PositiveSizeInWords;
using TargetClassMetadata = TargetClassMetadataType<Runtime>;
/// The offset from the address point of the metadata to the immediate
/// members.
StoredPointerDifference ImmediateMembersOffset;
constexpr TargetClassMetadataBounds() = default;
constexpr TargetClassMetadataBounds(
StoredPointerDifference immediateMembersOffset,
uint32_t negativeSizeInWords, uint32_t positiveSizeInWords)
: TargetMetadataBounds<Runtime>{negativeSizeInWords, positiveSizeInWords},
ImmediateMembersOffset(immediateMembersOffset) {}
/// Return the basic bounds of all Swift class metadata.
/// The immediate members offset will not be meaningful.
static constexpr TargetClassMetadataBounds<Runtime> forSwiftRootClass() {
using MetadataTy = FullMetadata<TargetClassMetadataType<Runtime>>;
return forAddressPointAndSize(sizeof(typename MetadataTy::HeaderType),
sizeof(MetadataTy));
}
/// Return the bounds of a Swift class metadata with the given address
/// point and size (both in bytes).
/// The immediate members offset will not be meaningful.
static constexpr TargetClassMetadataBounds<Runtime>
forAddressPointAndSize(StoredSize addressPoint, StoredSize totalSize) {
return {
// Immediate offset in bytes.
StoredPointerDifference(totalSize - addressPoint),
// Negative size in words.
uint32_t(addressPoint / sizeof(StoredPointer)),
// Positive size in words.
uint32_t((totalSize - addressPoint) / sizeof(StoredPointer))
};
}
/// Adjust these bounds for a subclass with the given immediate-members
/// section.
void adjustForSubclass(bool areImmediateMembersNegative,
uint32_t numImmediateMembers) {
if (areImmediateMembersNegative) {
NegativeSizeInWords += numImmediateMembers;
ImmediateMembersOffset =
-StoredPointerDifference(NegativeSizeInWords) * sizeof(StoredPointer);
} else {
ImmediateMembersOffset = PositiveSizeInWords * sizeof(StoredPointer);
PositiveSizeInWords += numImmediateMembers;
}
}
};
using ClassMetadataBounds =
TargetClassMetadataBounds<InProcess>;
/// The portion of a class metadata object that is compatible with
/// all classes, even non-Swift ones.
template <typename Runtime>
struct TargetAnyClassMetadata : public TargetHeapMetadata<Runtime> {
using StoredPointer = typename Runtime::StoredPointer;
using StoredSize = typename Runtime::StoredSize;
using TargetClassMetadata = TargetClassMetadataType<Runtime>;
protected:
constexpr TargetAnyClassMetadata(
TargetAnyClassMetadataObjCInterop<Runtime> *isa,
TargetClassMetadata *superclass)
: TargetHeapMetadata<Runtime>(isa), Superclass(superclass) {}
public:
constexpr TargetAnyClassMetadata(TargetClassMetadata *superclass)
: TargetHeapMetadata<Runtime>(MetadataKind::Class),
Superclass(superclass) {}
// Note that ObjC classes do not have a metadata header.
/// The metadata for the superclass. This is null for the root class.
TargetSignedPointer<Runtime, const TargetClassMetadata *
__ptrauth_swift_objc_superclass>
Superclass;
/// Is this object a valid swift type metadata? That is, can it be
/// safely downcast to ClassMetadata?
bool isTypeMetadata() const {
return true;
}
/// A different perspective on the same bit.
bool isPureObjC() const {
return !isTypeMetadata();
}
};
/// This is the class metadata object for all classes (Swift and ObjC) in a
/// runtime that has Objective-C interoperability.
template <typename Runtime>
struct TargetAnyClassMetadataObjCInterop
: public TargetAnyClassMetadata<Runtime> {
using StoredPointer = typename Runtime::StoredPointer;
using StoredSize = typename Runtime::StoredSize;
using TargetClassMetadataObjCInterop =
// swift:: qualifier works around an MSVC quirk
swift::TargetClassMetadata<Runtime, TargetAnyClassMetadataObjCInterop<Runtime>>;
constexpr TargetAnyClassMetadataObjCInterop(
TargetAnyClassMetadataObjCInterop<Runtime> *isa,
TargetClassMetadataObjCInterop *superclass)
: TargetAnyClassMetadata<Runtime>(isa, superclass),
CacheData{nullptr, nullptr},
Data(SWIFT_CLASS_IS_SWIFT_MASK) {}
constexpr TargetAnyClassMetadataObjCInterop(
TargetClassMetadataObjCInterop *superclass)
: TargetAnyClassMetadata<Runtime>(superclass), CacheData{nullptr,
nullptr},
Data(SWIFT_CLASS_IS_SWIFT_MASK) {}
// Allow setting the metadata kind to a class ISA on class metadata.
using TargetMetadata<Runtime>::getClassISA;
using TargetMetadata<Runtime>::setClassISA;
/// The cache data is used for certain dynamic lookups; it is owned
/// by the runtime and generally needs to interoperate with
/// Objective-C's use.
TargetPointer<Runtime, void> CacheData[2];
/// The data pointer is used for out-of-line metadata and is
/// generally opaque, except that the compiler sets the low bit in
/// order to indicate that this is a Swift metatype and therefore
/// that the type metadata header is present.
StoredSize Data;
static constexpr StoredPointer offsetToData() {
return offsetof(TargetAnyClassMetadataObjCInterop, Data);
}
/// Is this object a valid swift type metadata? That is, can it be
/// safely downcast to ClassMetadata?
bool isTypeMetadata() const {
return (Data & SWIFT_CLASS_IS_SWIFT_MASK);
}
/// A different perspective on the same bit
bool isPureObjC() const {
return !isTypeMetadata();
}
};
using AnyClassMetadata = TargetAnyClassMetadataType<InProcess>;
using ClassIVarDestroyer =
SWIFT_CC(swift) void(SWIFT_CONTEXT HeapObject *);
/// The structure of all class metadata. This structure is embedded
/// directly within the class's heap metadata structure and therefore
/// cannot be extended without an ABI break.
///
/// Note that the layout of this type is compatible with the layout of
/// an Objective-C class.
///
/// If the Runtime supports Objective-C interoperability, this class inherits
/// from TargetAnyClassMetadataObjCInterop, otherwise it inherits from
/// TargetAnyClassMetadata.
template <typename Runtime, typename TargetAnyClassMetadataVariant>
struct TargetClassMetadata : public TargetAnyClassMetadataVariant {
using StoredPointer = typename Runtime::StoredPointer;
using StoredSize = typename Runtime::StoredSize;
TargetClassMetadata() = default;
constexpr TargetClassMetadata(const TargetAnyClassMetadataVariant &base,
ClassFlags flags,
ClassIVarDestroyer *ivarDestroyer,
StoredPointer size, StoredPointer addressPoint,
StoredPointer alignMask,
StoredPointer classSize,
StoredPointer classAddressPoint)
: TargetAnyClassMetadataVariant(base), Flags(flags),
InstanceAddressPoint(addressPoint), InstanceSize(size),
InstanceAlignMask(alignMask), Reserved(0), ClassSize(classSize),
ClassAddressPoint(classAddressPoint), Description(nullptr),
IVarDestroyer(ivarDestroyer) {}
// The remaining fields are valid only when isTypeMetadata().
// The Objective-C runtime knows the offsets to some of these fields.
// Be careful when accessing them.
/// Swift-specific class flags.
ClassFlags Flags;
/// The address point of instances of this type.
uint32_t InstanceAddressPoint;
/// The required size of instances of this type.
/// 'InstanceAddressPoint' bytes go before the address point;
/// 'InstanceSize - InstanceAddressPoint' bytes go after it.
uint32_t InstanceSize;
/// The alignment mask of the address point of instances of this type.
uint16_t InstanceAlignMask;
/// Reserved for runtime use.
uint16_t Reserved;
/// The total size of the class object, including prefix and suffix
/// extents.
uint32_t ClassSize;
/// The offset of the address point within the class object.
uint32_t ClassAddressPoint;
// Description is by far the most likely field for a client to try
// to access directly, so we force access to go through accessors.
private:
/// An out-of-line Swift-specific description of the type, or null
/// if this is an artificial subclass. We currently provide no
/// supported mechanism for making a non-artificial subclass
/// dynamically.
TargetSignedPointer<Runtime, const TargetClassDescriptor<Runtime> * __ptrauth_swift_type_descriptor> Description;
public:
/// A function for destroying instance variables, used to clean up after an
/// early return from a constructor. If null, no clean up will be performed
/// and all ivars must be trivial.
TargetSignedPointer<Runtime, ClassIVarDestroyer * __ptrauth_swift_heap_object_destructor> IVarDestroyer;
// After this come the class members, laid out as follows:
// - class members for the superclass (recursively)
// - metadata reference for the parent, if applicable
// - generic parameters for this class
// - class variables (if we choose to support these)
// - "tabulated" virtual methods
using TargetAnyClassMetadataVariant::isTypeMetadata;
ConstTargetMetadataPointer<Runtime, TargetClassDescriptor>
getDescription() const {
assert(isTypeMetadata());
return Description;
}
typename Runtime::StoredSignedPointer
getDescriptionAsSignedPointer() const {
assert(isTypeMetadata());
return Description;
}
void setDescription(const TargetClassDescriptor<Runtime> *description) {
Description = description;
}
// [NOTE: Dynamic-subclass-KVO]
//
// Using Objective-C runtime, KVO can modify object behavior without needing
// to modify the object's code. This is done by dynamically creating an
// artificial subclass of the object's type.
//
// The isa pointer of the observed object is swapped out to point to
// the artificial subclass, which has the following properties:
// - Setters for observed keys are overridden to additionally post
// notifications.
// - The `-class` method is overridden to return the original class type
// instead of the artificial subclass type.
//
// For more details, see:
// https://www.mikeash.com/pyblog/friday-qa-2009-01-23.html
/// Is this class an artificial subclass, such as one dynamically
/// created for various dynamic purposes like KVO?
/// See [NOTE: Dynamic-subclass-KVO]
bool isArtificialSubclass() const {
assert(isTypeMetadata());
return Description == nullptr;
}
void setArtificialSubclass() {
assert(isTypeMetadata());
Description = nullptr;
}
ClassFlags getFlags() const {
assert(isTypeMetadata());
return Flags;
}
void setFlags(ClassFlags flags) {
assert(isTypeMetadata());
Flags = flags;
}
StoredSize getInstanceSize() const {
assert(isTypeMetadata());
return InstanceSize;
}
void setInstanceSize(StoredSize size) {
assert(isTypeMetadata());
InstanceSize = size;
}
StoredPointer getInstanceAddressPoint() const {
assert(isTypeMetadata());
return InstanceAddressPoint;
}
void setInstanceAddressPoint(StoredSize size) {
assert(isTypeMetadata());