/
Reflection.mm
1220 lines (1064 loc) · 39.2 KB
/
Reflection.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Fallthrough.h"
#include "swift/Runtime/Reflection.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Basic/Demangle.h"
#include "Debug.h"
#include "Private.h"
#include <cassert>
#include <cstring>
#include <new>
#include <string>
#include <regex>
#include <dlfcn.h>
#if SWIFT_OBJC_INTEROP
#include "swift/Runtime/ObjCBridge.h"
#include <Foundation/Foundation.h>
#include <objc/objc.h>
#include <objc/runtime.h>
#endif
using namespace swift;
#if SWIFT_OBJC_INTEROP
// Declare the debugQuickLookObject selector.
@interface DeclareSelectors
- (id)debugQuickLookObject;
@end
@class SwiftObject;
#endif
namespace {
/// The layout of protocol<>.
using Any = OpaqueExistentialContainer;
/// A Reflectable witness table.
struct ReflectableWitnessTable {
/// func getMirror() -> Mirror
Mirror (*getMirror)(OpaqueValue *self, const Metadata *Self);
};
struct MagicMirrorData;
struct String;
extern "C" void swift_stringFromUTF8InRawMemory(String *out,
const char *start,
intptr_t len);
struct String {
// Keep the details of String's implementation opaque to the runtime.
const void *x, *y, *z;
/// Keep String trivial on the C++ side so we can control its instantiation.
String() = default;
/// Wrap a string literal in a swift String.
template<size_t N>
explicit String(const char (&s)[N]) {
swift_stringFromUTF8InRawMemory(this, s, N-1);
}
/// Copy an ASCII string into a swift String on the heap.
explicit String(const char *ptr, size_t size) {
swift_stringFromUTF8InRawMemory(this, ptr, size);
}
explicit String(const char *ptr)
: String(ptr, strlen(ptr))
{}
/// Create a Swift String from two concatenated nul-terminated strings.
explicit String(const char *ptr1, const char *ptr2) {
size_t len1 = strlen(ptr1);
size_t len2 = strlen(ptr2);
char *concatenated = static_cast<char *>(malloc(len1 + len2));
memcpy(concatenated, ptr1, len1);
memcpy(concatenated + len1, ptr2, len2);
swift_stringFromUTF8InRawMemory(this, concatenated, len1 + len2);
free(concatenated);
}
#if SWIFT_OBJC_INTEROP
explicit String(NSString *s)
// FIXME: Use the usual NSString bridging entry point.
: String([s UTF8String])
{}
#endif
};
struct Array {
// Keep the details of Array's implementation opaque to the runtime.
const void *x;
};
struct QuickLookObject {
struct RawData {
Array Data;
String Type;
};
struct Rectangle {
double x, y, w, h;
};
struct Point {
double x, y;
};
struct Interval {
uint64_t loc,len;
};
union {
String TextOrURL;
int64_t Int;
uint64_t UInt;
float Float;
double Double;
Any Any;
RawData Raw;
Rectangle Rect;
Point PointOrSize;
bool Logical;
Interval Range;
};
enum class Tag : uint8_t {
Text,
Int,
UInt,
Float,
Double,
Image,
Sound,
Color,
BezierPath,
AttributedString,
Rectangle,
Point,
Size,
Logical,
Range,
View,
Sprite,
URL,
Raw,
} Kind;
};
struct StringMirrorTuple {
String first;
Mirror second;
};
struct OptionalQuickLookObject {
union {
struct {
union {
String TextOrURL;
int64_t Int;
uint64_t UInt;
float Float;
double Double;
Any Any;
QuickLookObject::RawData Raw;
QuickLookObject::Rectangle Rect;
QuickLookObject::Point PointOrSize;
bool Logical;
QuickLookObject::Interval Range;
};
QuickLookObject::Tag Kind;
bool isNone;
} optional;
QuickLookObject payload;
};
};
/// A Mirror witness table for use by MagicMirror.
struct MirrorWitnessTable;
/// The protocol descriptor for Reflectable from the stdlib.
extern "C" const ProtocolDescriptor _TMpSs11Reflectable;
// This structure needs to mirror _MagicMirrorData in the stdlib.
struct MagicMirrorData {
/// The owner pointer for the buffer the value lives in. For class values
/// this is the class instance itself. The mirror owns a strong reference to
/// this object.
HeapObject *Owner;
/// The pointer to the value. The mirror does not own the referenced value.
const OpaqueValue *Value;
/// The type metadata for the referenced value. For an ObjC witness, this is
/// the ObjC class.
const Metadata *Type;
};
static_assert(sizeof(MagicMirrorData) == sizeof(ValueBuffer),
"MagicMirrorData doesn't exactly fill a ValueBuffer");
/// A magic implementation of Mirror that can use runtime metadata to walk an
/// arbitrary object.
///
/// This type is layout-compatible with a Swift existential container for the
/// MirrorType protocol.
class MagicMirror {
public:
// The data for the mirror.
MagicMirrorData Data;
// The existential header.
const Metadata *Self;
const MirrorWitnessTable *MirrorWitness;
MagicMirror() = default;
/// Build a new MagicMirror for type T by taking ownership of the referenced
/// value.
MagicMirror(OpaqueValue *value, const Metadata *T, bool take);
/// Build a new MagicMirror for type T, sharing ownership with an existing
/// heap object, which is retained.
MagicMirror(HeapObject *owner, const OpaqueValue *value, const Metadata *T);
};
static_assert(alignof(MagicMirror) == alignof(Mirror),
"MagicMirror layout does not match existential container");
static_assert(sizeof(MagicMirror) == sizeof(Mirror),
"MagicMirror layout does not match existential container");
static_assert(offsetof(MagicMirror, Data) == offsetof(OpaqueExistentialContainer, Buffer),
"MagicMirror layout does not match existential container");
static_assert(offsetof(MagicMirror, Self) == offsetof(OpaqueExistentialContainer, Type),
"MagicMirror layout does not match existential container");
static_assert(offsetof(MagicMirror, MirrorWitness) ==
offsetof(Mirror, MirrorWitness),
"MagicMirror layout does not match existential container");
// -- Build an Any from an arbitrary value unowned-referenced by a mirror.
extern "C"
Any swift_MagicMirrorData_value(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
Any result;
result.Type = type;
type->vw_initializeBufferWithCopy(&result.Buffer,
const_cast<OpaqueValue*>(value));
#if !SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
swift_release(owner);
#endif
return result;
}
extern "C"
const Metadata *swift_MagicMirrorData_valueType(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
auto r = swift_getDynamicType(const_cast<OpaqueValue*>(value), type);
#if !SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
swift_release(owner);
#endif
return r;
}
#if SWIFT_OBJC_INTEROP
extern "C"
Any swift_MagicMirrorData_objcValue(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
Any result;
void *object = *reinterpret_cast<void * const *>(value);
auto isa = _swift_getClass(object);
result.Type = swift_getObjCClassMetadata(isa);
*reinterpret_cast<void **>(&result.Buffer) = swift_unknownRetain(object);
#if !SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
swift_release(owner);
#endif
return result;
}
#endif
extern "C"
void swift_MagicMirrorData_summary(const Metadata *T, String *result) {
switch (T->getKind()) {
case MetadataKind::Class:
new (result) String("(Class)");
break;
case MetadataKind::Struct:
new (result) String("(Struct)");
break;
case MetadataKind::Enum:
new (result) String("(Enum Value)");
break;
case MetadataKind::Opaque:
new (result) String("(Opaque Value)");
break;
case MetadataKind::Tuple:
new (result) String("(Tuple)");
break;
case MetadataKind::Function:
new (result) String("(Function)");
break;
case MetadataKind::ThinFunction:
new (result) String("(Thin Function)");
break;
case MetadataKind::PolyFunction:
new (result) String("(Polymorphic Function)");
break;
case MetadataKind::Existential:
new (result) String("(Existential)");
break;
case MetadataKind::Metatype:
new (result) String("(Metatype)");
break;
case MetadataKind::ObjCClassWrapper:
new (result) String("(Objective-C Class Wrapper)");
break;
case MetadataKind::ExistentialMetatype:
new (result) String("(ExistentialMetatype)");
break;
case MetadataKind::ForeignClass:
new (result) String("(Foreign Class)");
break;
case MetadataKind::Block:
new (result) String("(Block)");
break;
case MetadataKind::HeapLocalVariable:
new (result) String("(Heap Local Variable)");
break;
}
}
extern "C"
const Metadata *swift_MagicMirrorData_objcValueType(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
void *object = *reinterpret_cast<void * const *>(value);
auto isa = _swift_getClass(object);
#if !SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
swift_release(owner);
#endif
return swift_getObjCClassMetadata(isa);
}
// -- Tuple destructuring.
extern "C"
intptr_t swift_TupleMirror_count(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
auto Tuple = static_cast<const TupleTypeMetadata *>(type);
#if !SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
swift_release(owner);
#endif
return Tuple->NumElements;
}
/// \param owner passed at +1, consumed.
/// \param value passed unowned.
extern "C"
StringMirrorTuple swift_TupleMirror_subscript(intptr_t i,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
StringMirrorTuple result;
auto Tuple = static_cast<const TupleTypeMetadata *>(type);
if (i < 0 || (size_t)i > Tuple->NumElements)
swift::crash("Swift mirror subscript bounds check failure");
// The name is the stringized element number '.0'.
char buf[32];
snprintf(buf, 31, ".%zd", i);
buf[31] = 0;
result.first = String(buf, strlen(buf));
// Get a Mirror for the nth element.
auto &elt = Tuple->getElements()[i];
auto bytes = reinterpret_cast<const char*>(value);
auto eltData = reinterpret_cast<const OpaqueValue *>(bytes + elt.Offset);
#if SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
// This retain matches the -1 in swift_unsafeReflectAny.
swift_retain(owner);
#endif
// 'owner' is consumed by this call.
result.second = swift_unsafeReflectAny(owner, eltData, elt.Type);
return result;
}
// -- Struct destructuring.
extern "C"
intptr_t swift_StructMirror_count(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
auto Struct = static_cast<const StructMetadata *>(type);
#if !SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
swift_release(owner);
#endif
return Struct->Description->Struct.NumFields;
}
extern "C"
StringMirrorTuple swift_StructMirror_subscript(intptr_t i,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
StringMirrorTuple result;
auto Struct = static_cast<const StructMetadata *>(type);
if (i < 0 || (size_t)i > Struct->Description->Struct.NumFields)
swift::crash("Swift mirror subscript bounds check failure");
// Load the type and offset from their respective vectors.
auto fieldType = Struct->getFieldTypes()[i];
auto fieldOffset = Struct->getFieldOffsets()[i];
auto bytes = reinterpret_cast<const char*>(value);
auto fieldData = reinterpret_cast<const OpaqueValue *>(bytes + fieldOffset);
// Get the field name from the doubly-null-terminated list.
const char *fieldName = Struct->Description->Struct.FieldNames;
for (size_t j = 0; j < (size_t)i; ++j) {
while (*fieldName++);
}
result.first = String(fieldName);
#if SWIFT_RUNTIME_ENABLE_GUARANTEED_SELF
// This matches the -1 in swift_unsafeReflectAny.
swift_retain(owner);
#endif
// 'owner' is consumed by this call.
result.second = swift_unsafeReflectAny(owner, fieldData, fieldType);
return result;
}
// -- Class destructuring.
static bool classHasSuperclass(const ClassMetadata *c) {
#if SWIFT_OBJC_INTEROP
// A class does not have a superclass if its ObjC superclass is the
// "SwiftObject" root class.
return c->SuperClass
&& (Class)c->SuperClass != NSClassFromString(@"SwiftObject");
#else
// In non-objc mode, the test is just if it has a non-null superclass.
return c->SuperClass != nullptr;
#endif
}
static Mirror getMirrorForSuperclass(const ClassMetadata *sup,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type);
extern "C"
intptr_t swift_ClassMirror_count(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
auto Clas = static_cast<const ClassMetadata*>(type);
swift_release(owner);
auto count = Clas->getDescription()->Class.NumFields;
// If the class has a superclass, the superclass instance is treated as the
// first child.
if (classHasSuperclass(Clas))
count += 1;
return count;
}
/// \param owner passed at +1, consumed.
/// \param value passed unowned.
extern "C"
StringMirrorTuple swift_ClassMirror_subscript(intptr_t i,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
StringMirrorTuple result;
auto Clas = static_cast<const ClassMetadata*>(type);
if (classHasSuperclass(Clas)) {
// If the class has a superclass, the superclass instance is treated as the
// first child.
if (i == 0) {
// FIXME: Put superclass name here
result.first = String("super");
result.second
= getMirrorForSuperclass(Clas->SuperClass, owner, value, type);
return result;
}
--i;
}
if (i < 0 || (size_t)i > Clas->getDescription()->Class.NumFields)
swift::crash("Swift mirror subscript bounds check failure");
// Load the type and offset from their respective vectors.
auto fieldType = Clas->getFieldTypes()[i];
// FIXME: If the class has ObjC heritage, get the field offset using the ObjC
// metadata, because we don't update the field offsets in the face of
// resilient base classes.
uintptr_t fieldOffset;
if (usesNativeSwiftReferenceCounting(Clas)) {
fieldOffset = Clas->getFieldOffsets()[i];
} else {
#if SWIFT_OBJC_INTEROP
Ivar *ivars = class_copyIvarList((Class)Clas, nullptr);
fieldOffset = ivar_getOffset(ivars[i]);
free(ivars);
#else
swift::crash("Object appears to be Objective-C, but no runtime.");
#endif
}
auto bytes = *reinterpret_cast<const char * const*>(value);
auto fieldData = reinterpret_cast<const OpaqueValue *>(bytes + fieldOffset);
// Get the field name from the doubly-null-terminated list.
const char *fieldName = Clas->getDescription()->Class.FieldNames;
for (size_t j = 0; j < (size_t)i; ++j) {
while (*fieldName++);
}
result.first = String(fieldName);
// 'owner' is consumed by this call.
result.second = swift_unsafeReflectAny(owner, fieldData, fieldType);
return result;
}
// -- Mirror witnesses for ObjC classes.
extern "C" const FullMetadata<Metadata> _TMdSb; // Bool
extern "C" const FullMetadata<Metadata> _TMdSi; // Int
extern "C" const FullMetadata<Metadata> _TMdSu; // UInt
extern "C" const FullMetadata<Metadata> _TMdSf; // Float
extern "C" const FullMetadata<Metadata> _TMdSd; // Double
extern "C" const FullMetadata<Metadata> _TMdVSs4Int8;
extern "C" const FullMetadata<Metadata> _TMdVSs5Int16;
extern "C" const FullMetadata<Metadata> _TMdVSs5Int32;
extern "C" const FullMetadata<Metadata> _TMdVSs5Int64;
extern "C" const FullMetadata<Metadata> _TMdVSs5UInt8;
extern "C" const FullMetadata<Metadata> _TMdVSs6UInt16;
extern "C" const FullMetadata<Metadata> _TMdVSs6UInt32;
extern "C" const FullMetadata<Metadata> _TMdVSs6UInt64;
// Set to 1 to enable reflection of objc ivars.
#define REFLECT_OBJC_IVARS 0
/// Map an ObjC type encoding string to a Swift type metadata object.
///
#if REFLECT_OBJC_IVARS
static const Metadata *getMetadataForEncoding(const char *encoding) {
switch (*encoding) {
case 'c': // char
return &_TMdVSs4Int8;
case 's': // short
return &_TMdVSs5Int16;
case 'i': // int
return &_TMdVSs5Int32;
case 'l': // long
return &_TMdSi;
case 'q': // long long
return &_TMdVSs5Int64;
case 'C': // unsigned char
return &_TMdVSs5UInt8;
case 'S': // unsigned short
return &_TMdVSs6UInt16;
case 'I': // unsigned int
return &_TMdVSs6UInt32;
case 'L': // unsigned long
return &_TMdSu;
case 'Q': // unsigned long long
return &_TMdVSs6UInt64;
case 'B': // _Bool
return &_TMdSb;
case '@': { // Class
// TODO: Better metadata?
const OpaqueMetadata *M = &_TMdBO;
return &M->base;
}
default: // TODO
// Return 'void' as the type of fields we don't understand.
return &_TMdT_;
}
}
#endif
/// \param owner passed at +1, consumed.
/// \param value passed unowned.
extern "C"
intptr_t swift_ObjCMirror_count(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
#if REFLECT_OBJC_IVARS
auto isa = (Class)type;
unsigned count;
// Don't reflect ivars of classes that lie about their layout.
if (objcClassLiesAboutLayout(isa)) {
count = 0;
} else {
// Copying the ivar list just to free it is lame, but we have
// nowhere to save it.
Ivar *ivars = class_copyIvarList(isa, &count);
free(ivars);
}
// The superobject counts as a child.
if (_swift_getSuperclass((const ClassMetadata*) isa))
count += 1;
swift_release(owner);
return count;
#else
// ObjC makes no guarantees about the state of ivars, so we can't safely
// introspect them in the general case.
swift_release(owner);
return 0;
#endif
}
#if SWIFT_OBJC_INTEROP
static Mirror ObjC_getMirrorForSuperclass(Class sup,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type);
extern "C"
StringMirrorTuple swift_ObjCMirror_subscript(intptr_t i,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
#if REFLECT_OBJC_IVARS
id object = *reinterpret_cast<const id *>(value);
auto isa = (Class)type;
// If there's a superclass, it becomes the first child.
if (auto sup = (Class) _swift_getSuperclass((const ClassMetadata*) isa)) {
if (i == 0) {
StringMirrorTuple result;
const char *supName = class_getName(sup);
result.first = String(supName, strlen(supName));
result.second = ObjC_getMirrorForSuperclass(sup, owner, value, type);
return result;
}
--i;
}
// Copying the ivar list just to free it is lame, but we have
// no room to save it.
unsigned count;
Ivar *ivars;
// Don't reflect ivars of classes that lie about their layout.
if (objcClassLiesAboutLayout(isa)) {
count = 0;
ivars = nullptr;
} else {
// Copying the ivar list just to free it is lame, but we have
// nowhere to save it.
ivars = class_copyIvarList(isa, &count);
}
if (i < 0 || (uintptr_t)i >= (uintptr_t)count)
swift::crash("Swift mirror subscript bounds check failure");
const char *name = ivar_getName(ivars[i]);
ptrdiff_t offset = ivar_getOffset(ivars[i]);
const char *typeEncoding = ivar_getTypeEncoding(ivars[i]);
free(ivars);
const OpaqueValue *ivar =
reinterpret_cast<const OpaqueValue *>(
reinterpret_cast<const char*>(object) + offset);
const Metadata *ivarType = getMetadataForEncoding(typeEncoding);
StringMirrorTuple result;
result.first = String(name, strlen(name));
// 'owner' is consumed by this call.
result.second = swift_unsafeReflectAny(owner, ivar, ivarType);
return result;
#else
// ObjC makes no guarantees about the state of ivars, so we can't safely
// introspect them in the general case.
abort();
#endif
}
extern "C"
OptionalQuickLookObject swift_ClassMirror_quickLookObject(HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
OptionalQuickLookObject result;
memset(&result, 0, sizeof(result));
id object = [*reinterpret_cast<const id *>(value) retain];
swift_release(owner);
if ([object respondsToSelector:@selector(debugQuickLookObject)]) {
id quickLookObject = [object debugQuickLookObject];
[quickLookObject retain];
[object release];
object = quickLookObject;
}
// NSNumbers quick-look as integers or doubles, depending on type.
if ([object isKindOfClass:[NSNumber class]]) {
NSNumber *n = object;
switch ([n objCType][0]) {
case 'd': // double
result.payload.Double = [n doubleValue];
result.payload.Kind = QuickLookObject::Tag::Double;
break;
case 'f': // float
result.payload.Float = [n floatValue];
result.payload.Kind = QuickLookObject::Tag::Float;
break;
case 'Q': // unsigned long long
result.payload.UInt = [n unsignedLongLongValue];
result.payload.Kind = QuickLookObject::Tag::UInt;
break;
// FIXME: decimals?
default:
result.payload.Int = [n longLongValue];
result.payload.Kind = QuickLookObject::Tag::Int;
break;
}
[object release];
result.optional.isNone = false;
return result;
}
// Various other framework types are used for rich representations.
/// Store an ObjC reference into an Any.
auto initializeAnyWithTakeOfObject = [](Any &any, id obj) {
any.Type = swift_getObjCClassMetadata(_swift_getClass((const void*) obj));
*reinterpret_cast<id *>(&any.Buffer) = obj;
};
if ([object isKindOfClass:NSClassFromString(@"NSAttributedString")]) {
initializeAnyWithTakeOfObject(result.payload.Any, object);
result.payload.Kind = QuickLookObject::Tag::AttributedString;
result.optional.isNone = false;
return result;
} else if ([object isKindOfClass:NSClassFromString(@"NSImage")]
|| [object isKindOfClass:NSClassFromString(@"UIImage")]
|| [object isKindOfClass:NSClassFromString(@"NSImageView")]
|| [object isKindOfClass:NSClassFromString(@"UIImageView")]
|| [object isKindOfClass:NSClassFromString(@"CIImage")]
|| [object isKindOfClass:NSClassFromString(@"NSBitmapImageRep")]) {
initializeAnyWithTakeOfObject(result.payload.Any, object);
result.payload.Kind = QuickLookObject::Tag::Image;
result.optional.isNone = false;
return result;
} else if ([object isKindOfClass:NSClassFromString(@"NSColor")]
|| [object isKindOfClass:NSClassFromString(@"UIColor")]) {
initializeAnyWithTakeOfObject(result.payload.Any, object);
result.payload.Kind = QuickLookObject::Tag::Color;
result.optional.isNone = false;
return result;
} else if ([object isKindOfClass:NSClassFromString(@"NSBezierPath")]
|| [object isKindOfClass:NSClassFromString(@"UIBezierPath")]) {
initializeAnyWithTakeOfObject(result.payload.Any, object);
result.payload.Kind = QuickLookObject::Tag::BezierPath;
result.optional.isNone = false;
return result;
} else if ([object isKindOfClass:[NSString class]]) {
result.payload.TextOrURL = String((NSString*)object);
[object release];
result.payload.Kind = QuickLookObject::Tag::Text;
result.optional.isNone = false;
return result;
}
// Return none if we didn't get a suitable object.
[object release];
result.optional.isNone = true;
return result;
}
#endif
// -- MagicMirror implementation.
// TODO: There are other non-Apple platforms that underscore asm symbols.
#if __APPLE__
# define UNDERSCORE "_"
#else
# define UNDERSCORE
#endif
// Addresses of the type metadata and Mirror witness tables for the primitive
// mirrors.
extern "C" const FullMetadata<Metadata> OpaqueMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs13_OpaqueMirror");
extern "C" const MirrorWitnessTable OpaqueMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs13_OpaqueMirrorSs10MirrorTypeSs");
extern "C" const FullMetadata<Metadata> TupleMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs12_TupleMirror");
extern "C" const MirrorWitnessTable TupleMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs12_TupleMirrorSs10MirrorTypeSs");
extern "C" const FullMetadata<Metadata> StructMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs13_StructMirror");
extern "C" const MirrorWitnessTable StructMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs13_StructMirrorSs10MirrorTypeSs");
extern "C" const FullMetadata<Metadata> ClassMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs12_ClassMirror");
extern "C" const MirrorWitnessTable ClassMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs12_ClassMirrorSs10MirrorTypeSs");
extern "C" const FullMetadata<Metadata> ClassSuperMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs17_ClassSuperMirror");
extern "C" const MirrorWitnessTable ClassSuperMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs17_ClassSuperMirrorSs10MirrorTypeSs");
extern "C" const FullMetadata<Metadata> MetatypeMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs15_MetatypeMirror");
extern "C" const MirrorWitnessTable MetatypeMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs15_MetatypeMirrorSs10MirrorTypeSs");
#if SWIFT_OBJC_INTEROP
extern "C" const FullMetadata<Metadata> ObjCMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs11_ObjCMirror");
extern "C" const MirrorWitnessTable ObjCMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs11_ObjCMirrorSs10MirrorTypeSs");
extern "C" const FullMetadata<Metadata> ObjCSuperMirrorMetadata
__asm__(UNDERSCORE "_TMdVSs16_ObjCSuperMirror");
extern "C" const MirrorWitnessTable ObjCSuperMirrorWitnessTable
__asm__(UNDERSCORE "_TWPVSs16_ObjCSuperMirrorSs10MirrorTypeSs");
#endif
#undef UNDERSCORE
/// \param owner passed at +1, consumed.
/// \param value passed unowned.
static Mirror getMirrorForSuperclass(const ClassMetadata *sup,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
#if SWIFT_OBJC_INTEROP
// If the superclass is natively ObjC, cut over to the ObjC mirror
// implementation.
if (!sup->isTypeMetadata())
return ObjC_getMirrorForSuperclass((Class)sup, owner, value, type);
#endif
Mirror resultBuf;
MagicMirror *result = ::new (&resultBuf) MagicMirror;
result->Self = &ClassSuperMirrorMetadata;
result->MirrorWitness = &ClassSuperMirrorWitnessTable;
result->Data.Owner = owner;
result->Data.Type = sup;
result->Data.Value = value;
return resultBuf;
}
#if SWIFT_OBJC_INTEROP
/// \param owner passed at +1, consumed.
/// \param value passed unowned.
static Mirror ObjC_getMirrorForSuperclass(Class sup,
HeapObject *owner,
const OpaqueValue *value,
const Metadata *type) {
Mirror resultBuf;
MagicMirror *result = ::new (&resultBuf) MagicMirror;
result->Self = &ObjCSuperMirrorMetadata;
result->MirrorWitness = &ObjCSuperMirrorWitnessTable;
result->Data.Owner = owner;
result->Data.Type = reinterpret_cast<ClassMetadata*>(sup);
result->Data.Value = value;
return resultBuf;
}
#endif
// (type being mirrored, mirror type, mirror witness)
using MirrorTriple
= std::tuple<const Metadata *, const Metadata *, const MirrorWitnessTable *>;
static MirrorTriple
getImplementationForClass(const OpaqueValue *Value) {
// Get the runtime type of the object.
const void *obj = *reinterpret_cast<const void * const *>(Value);
auto isa = _swift_getClass(obj);
// Look through artificial subclasses.
while (isa->isTypeMetadata() && isa->isArtificialSubclass()) {
isa = isa->SuperClass;
}
#if SWIFT_OBJC_INTEROP
// If this is a pure ObjC class, reflect it using ObjC's runtime facilities.
if (!isa->isTypeMetadata())
return {isa, &ObjCMirrorMetadata, &ObjCMirrorWitnessTable};
#endif
// Otherwise, use the native Swift facilities.
return std::make_tuple(
isa, &ClassMirrorMetadata, &ClassMirrorWitnessTable);
}
/// Get the magic mirror witnesses appropriate to a particular type.
static MirrorTriple
getImplementationForType(const Metadata *T, const OpaqueValue *Value) {
switch (T->getKind()) {
case MetadataKind::Tuple:
return std::make_tuple(
T, &TupleMirrorMetadata, &TupleMirrorWitnessTable);
case MetadataKind::Struct:
return std::make_tuple(
T, &StructMirrorMetadata, &StructMirrorWitnessTable);
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
case MetadataKind::Class: {
return getImplementationForClass(Value);
}
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype: {
return std::make_tuple(T, &MetatypeMirrorMetadata,
&MetatypeMirrorWitnessTable);
}
case MetadataKind::Opaque: {
#if SWIFT_OBJC_INTEROP
// If this is the Builtin.UnknownObject type, use the dynamic type of the
// object reference.
if (T == &_TMdBO.base) {
return getImplementationForClass(Value);
}
#endif
// If this is the Builtin.NativeObject type, and the heap object is a
// class instance, use the dynamic type of the object reference.
if (T == &_TMdBo.base) {
const HeapObject *obj
= *reinterpret_cast<const HeapObject * const*>(Value);
if (obj->metadata->getKind() == MetadataKind::Class)
return getImplementationForClass(Value);
}
SWIFT_FALLTHROUGH;
}
/// TODO: Implement specialized mirror witnesses for all kinds.
case MetadataKind::Enum:
case MetadataKind::Function:
case MetadataKind::ThinFunction:
case MetadataKind::Block:
case MetadataKind::Existential:
return std::make_tuple(
T, &OpaqueMirrorMetadata, &OpaqueMirrorWitnessTable);
// Types can't have these kinds.
case MetadataKind::PolyFunction:
case MetadataKind::HeapLocalVariable:
swift::crash("Swift mirror lookup failure");
}
}
/// MagicMirror ownership-taking whole-value constructor.
///
/// \param owner passed at +1, consumed.
MagicMirror::MagicMirror(OpaqueValue *value, const Metadata *T,
bool take) {
// Put value types into a box so we can take stable interior pointers.
// TODO: Specialize behavior here. If the value is a swift-refcounted class
// we don't need to put it in a box to point into it.
BoxPair box = swift_allocBox(T);
if (take)
T->vw_initializeWithTake(box.value, value);