-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
TypeCast.cs
1296 lines (1082 loc) · 53.8 KB
/
TypeCast.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Internal.Runtime;
namespace System.Runtime
{
/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// **** WARNING ****
//
// A large portion of the logic present in this file is duplicated
// in src\System.Private.Reflection.Execution\Internal\Reflection\Execution\TypeLoader\TypeCast.cs
// (for dynamic type builder). If you make changes here make sure they are reflected there.
//
// **** WARNING ****
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
[EagerStaticClassConstruction]
internal static class TypeCast
{
#if DEBUG
private const int InitialCacheSize = 8; // MUST BE A POWER OF TWO
private const int MaximumCacheSize = 512; // make this lower than release to make it easier to reach this in tests.
#else
private const int InitialCacheSize = 128; // MUST BE A POWER OF TWO
private const int MaximumCacheSize = 4096; // 4096 * sizeof(CastCacheEntry) is 98304 bytes on 64bit. We will rarely need this much though.
#endif // DEBUG
private static CastCache s_castCache = new CastCache(InitialCacheSize, MaximumCacheSize);
[Flags]
internal enum AssignmentVariation
{
/// <summary>
/// Conversion from an object. In the terminology of ECMA335 the relationship is called "compatible-with".
/// This is the relation used by castclass and isinst (III.4.3).
/// Value types are compatible with Object, ValueType and Enum (if applicable) and implemented interfaces.
/// </summary>
BoxedSource = 0,
/// <summary>
/// Type compatibility of unboxed types. Used for checking compatibility of type parameters.
/// Value types are compatible only if equivalent.
/// </summary>
Unboxed = 1,
/// <summary>
/// Allow identically sized integral types and enums to be considered equivalent.
/// Used when checking type compatibility of array element types.
/// </summary>
AllowSizeEquivalence = 2,
}
// IsInstanceOf test used for unusual cases (naked type parameters, variant generic types)
// Unlike the IsInstanceOfInterface and IsInstanceOfClass functions,
// this test must deal with all kinds of type tests
[RuntimeExport("RhTypeCast_IsInstanceOfAny")]
public static unsafe object? IsInstanceOfAny(MethodTable* pTargetType, object? obj)
{
if (obj != null)
{
MethodTable* mt = obj.GetMethodTable();
if (mt != pTargetType)
{
CastResult result = s_castCache.TryGet((nuint)mt + (int)AssignmentVariation.BoxedSource, (nuint)pTargetType);
if (result == CastResult.CanCast)
{
// do nothing
}
else if (result == CastResult.CannotCast)
{
obj = null;
}
else
{
goto slowPath;
}
}
}
return obj;
slowPath:
// fall through to the slow helper
return IsInstanceOfAny_NoCacheLookup(pTargetType, obj);
}
[RuntimeExport("RhTypeCast_IsInstanceOfInterface")]
public static unsafe object? IsInstanceOfInterface(MethodTable* pTargetType, object? obj)
{
Debug.Assert(pTargetType->IsInterface);
Debug.Assert(!pTargetType->HasGenericVariance);
const int unrollSize = 4;
if (obj != null)
{
MethodTable* mt = obj.GetMethodTable();
nint interfaceCount = mt->NumInterfaces;
if (interfaceCount != 0)
{
MethodTable** interfaceMap = mt->InterfaceMap;
if (interfaceCount < unrollSize)
{
// If not enough for unrolled, jmp straight to small loop
// as we already know there is one or more interfaces so don't need to check again.
goto few;
}
do
{
if (interfaceMap[0] == pTargetType ||
interfaceMap[1] == pTargetType ||
interfaceMap[2] == pTargetType ||
interfaceMap[3] == pTargetType)
{
goto done;
}
interfaceMap += unrollSize;
interfaceCount -= unrollSize;
} while (interfaceCount >= unrollSize);
if (interfaceCount == 0)
{
// If none remaining, skip the short loop
goto extra;
}
few:
do
{
if (interfaceMap[0] == pTargetType)
{
goto done;
}
// Assign next offset
interfaceMap++;
interfaceCount--;
} while (interfaceCount > 0);
extra:
if (mt->IsIDynamicInterfaceCastable)
{
goto slowPath;
}
}
obj = null;
}
done:
return obj;
slowPath:
return IsInstanceOfInterface_Helper(pTargetType, obj);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe object? IsInstanceOfInterface_Helper(MethodTable* pTargetType, object? obj)
{
// If object type implements IDynamicInterfaceCastable then there's one more way to check whether it implements
// the interface.
if (!IsInstanceOfInterfaceViaIDynamicInterfaceCastable(pTargetType, obj, throwing: false))
obj = null;
return obj;
}
[RuntimeExport("RhTypeCast_IsInstanceOfClass")]
public static unsafe object? IsInstanceOfClass(MethodTable* pTargetType, object? obj)
{
Debug.Assert(!pTargetType->IsParameterizedType, "IsInstanceOfClass called with parameterized MethodTable");
Debug.Assert(!pTargetType->IsFunctionPointer, "IsInstanceOfClass called with function pointer MethodTable");
Debug.Assert(!pTargetType->IsInterface, "IsInstanceOfClass called with interface MethodTable");
Debug.Assert(!pTargetType->HasGenericVariance, "IsInstanceOfClass with variant MethodTable");
if (obj == null || obj.GetMethodTable() == pTargetType)
return obj;
if (!obj.GetMethodTable()->IsCanonical)
{
// Arrays should be the only non-canonical types that can exist on GC heap
Debug.Assert(obj.GetMethodTable()->IsArray);
// arrays can be cast to System.Object or System.Array
if (WellKnownEETypes.IsValidArrayBaseType(pTargetType))
goto done;
// They don't cast to any other class
goto fail;
}
MethodTable* mt = obj.GetMethodTable()->NonArrayBaseType;
for (; ; )
{
if (mt == pTargetType)
goto done;
if (mt == null)
break;
mt = mt->NonArrayBaseType;
if (mt == pTargetType)
goto done;
if (mt == null)
break;
mt = mt->NonArrayBaseType;
if (mt == pTargetType)
goto done;
if (mt == null)
break;
mt = mt->NonArrayBaseType;
if (mt == pTargetType)
goto done;
if (mt == null)
break;
mt = mt->NonArrayBaseType;
}
fail:
obj = null;
done:
return obj;
}
[RuntimeExport("RhTypeCast_IsInstanceOfException")]
public static unsafe bool IsInstanceOfException(MethodTable* pTargetType, object? obj)
{
// Based on IsInstanceOfClass
if (obj == null)
return false;
MethodTable* pObjType = obj.GetMethodTable();
if (pObjType == pTargetType)
return true;
// arrays can be cast to System.Object and System.Array
if (pObjType->IsArray)
return WellKnownEETypes.IsValidArrayBaseType(pTargetType);
while (true)
{
pObjType = pObjType->NonArrayBaseType;
if (pObjType == null)
return false;
if (pObjType == pTargetType)
return true;
}
}
// ChkCast test used for unusual cases (naked type parameters, variant generic types)
// Unlike the ChkCastInterface and ChkCastClass functions,
// this test must deal with all kinds of type tests
[RuntimeExport("RhTypeCast_CheckCastAny")]
public static unsafe object CheckCastAny(MethodTable* pTargetType, object obj)
{
CastResult result;
if (obj != null)
{
MethodTable* mt = obj.GetMethodTable();
if (mt != pTargetType)
{
result = s_castCache.TryGet((nuint)mt, (nuint)pTargetType);
if (result != CastResult.CanCast)
{
goto slowPath;
}
}
}
return obj;
slowPath:
// fall through to the slow helper
object objRet = CheckCastAny_NoCacheLookup(pTargetType, obj);
// Make sure that the fast helper have not lied
Debug.Assert(result != CastResult.CannotCast);
return objRet;
}
[RuntimeExport("RhTypeCast_CheckCastInterface")]
public static unsafe object CheckCastInterface(MethodTable* pTargetType, object obj)
{
Debug.Assert(pTargetType->IsInterface);
Debug.Assert(!pTargetType->HasGenericVariance);
const int unrollSize = 4;
if (obj != null)
{
MethodTable* mt = obj.GetMethodTable();
nint interfaceCount = mt->NumInterfaces;
if (interfaceCount == 0)
{
goto slowPath;
}
MethodTable** interfaceMap = mt->InterfaceMap;
if (interfaceCount < unrollSize)
{
// If not enough for unrolled, jmp straight to small loop
// as we already know there is one or more interfaces so don't need to check again.
goto few;
}
do
{
if (interfaceMap[0] == pTargetType ||
interfaceMap[1] == pTargetType ||
interfaceMap[2] == pTargetType ||
interfaceMap[3] == pTargetType)
{
goto done;
}
// Assign next offset
interfaceMap += unrollSize;
interfaceCount -= unrollSize;
} while (interfaceCount >= unrollSize);
if (interfaceCount == 0)
{
// If none remaining, skip the short loop
goto slowPath;
}
few:
do
{
if (interfaceMap[0] == pTargetType)
{
goto done;
}
// Assign next offset
interfaceMap++;
interfaceCount--;
} while (interfaceCount > 0);
goto slowPath;
}
done:
return obj;
slowPath:
return CheckCastInterface_Helper(pTargetType, obj);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe object CheckCastInterface_Helper(MethodTable* pTargetType, object obj)
{
// If object type implements IDynamicInterfaceCastable then there's one more way to check whether it implements
// the interface.
if (obj.GetMethodTable()->IsIDynamicInterfaceCastable
&& IsInstanceOfInterfaceViaIDynamicInterfaceCastable(pTargetType, obj, throwing: true))
{
return obj;
}
// Throw the invalid cast exception defined by the classlib, using the input MethodTable* to find the
// correct classlib.
return ThrowInvalidCastException(pTargetType);
}
[RuntimeExport("RhTypeCast_CheckCastClass")]
public static unsafe object CheckCastClass(MethodTable* pTargetType, object obj)
{
Debug.Assert(!pTargetType->IsParameterizedType, "CheckCastClass called with parameterized MethodTable");
Debug.Assert(!pTargetType->IsFunctionPointer, "CheckCastClass called with function pointer MethodTable");
Debug.Assert(!pTargetType->IsInterface, "CheckCastClass called with interface MethodTable");
Debug.Assert(!pTargetType->HasGenericVariance, "CheckCastClass with variant MethodTable");
if (obj == null || obj.GetMethodTable() == pTargetType)
{
return obj;
}
return CheckCastClassSpecial(pTargetType, obj);
}
// Optimized helper for classes. Assumes that the trivial cases
// has been taken care of by the inlined check
[RuntimeExport("RhTypeCast_CheckCastClassSpecial")]
private static unsafe object CheckCastClassSpecial(MethodTable* pTargetType, object obj)
{
Debug.Assert(!pTargetType->IsParameterizedType, "CheckCastClass called with parameterized MethodTable");
Debug.Assert(!pTargetType->IsFunctionPointer, "CheckCastClass called with function pointer MethodTable");
Debug.Assert(!pTargetType->IsInterface, "CheckCastClass called with interface MethodTable");
Debug.Assert(!pTargetType->HasGenericVariance, "CheckCastClass with variant MethodTable");
MethodTable* mt = obj.GetMethodTable();
Debug.Assert(mt != pTargetType, "The check for the trivial cases should be inlined by the JIT");
if (!mt->IsCanonical)
{
// Arrays should be the only non-canonical types that can exist on GC heap
Debug.Assert(mt->IsArray);
// arrays can be cast to System.Object or System.Array
if (WellKnownEETypes.IsValidArrayBaseType(pTargetType))
goto done;
// They don't cast to any other class
goto fail;
}
for (; ; )
{
mt = mt->NonArrayBaseType;
if (mt == pTargetType)
goto done;
if (mt == null)
break;
mt = mt->NonArrayBaseType;
if (mt == pTargetType)
goto done;
if (mt == null)
break;
mt = mt->NonArrayBaseType;
if (mt == pTargetType)
goto done;
if (mt == null)
break;
mt = mt->NonArrayBaseType;
if (mt == pTargetType)
goto done;
if (mt == null)
break;
}
goto fail;
done:
return obj;
fail:
return ThrowInvalidCastException(pTargetType);
}
private static unsafe bool IsInstanceOfInterfaceViaIDynamicInterfaceCastable(MethodTable* pTargetType, object obj, bool throwing)
{
var pfnIsInterfaceImplemented = (delegate*<object, MethodTable*, bool, bool>)
pTargetType->GetClasslibFunction(ClassLibFunctionId.IDynamicCastableIsInterfaceImplemented);
return pfnIsInterfaceImplemented(obj, pTargetType, throwing);
}
internal static unsafe bool IsDerived(MethodTable* pDerivedType, MethodTable* pBaseType)
{
Debug.Assert(!pDerivedType->IsArray, "did not expect array type");
Debug.Assert(!pDerivedType->IsParameterizedType, "did not expect parameterType");
Debug.Assert(!pDerivedType->IsFunctionPointer, "did not expect function pointer");
Debug.Assert(!pBaseType->IsArray, "did not expect array type");
Debug.Assert(!pBaseType->IsInterface, "did not expect interface type");
Debug.Assert(!pBaseType->IsParameterizedType, "did not expect parameterType");
Debug.Assert(!pBaseType->IsFunctionPointer, "did not expect function pointer");
Debug.Assert(pBaseType->IsCanonical || pBaseType->IsGenericTypeDefinition, "unexpected MethodTable");
Debug.Assert(pDerivedType->IsCanonical || pDerivedType->IsGenericTypeDefinition, "unexpected MethodTable");
// If a generic type definition reaches this function, then the function should return false unless the types are equivalent.
// This works as the NonArrayBaseType of a GenericTypeDefinition is always null.
do
{
if (pDerivedType == pBaseType)
return true;
pDerivedType = pDerivedType->NonArrayBaseType;
}
while (pDerivedType != null);
return false;
}
private static unsafe bool ImplementsInterface(MethodTable* pObjType, MethodTable* pTargetType, EETypePairList* pVisited)
{
Debug.Assert(!pTargetType->IsParameterizedType, "did not expect parameterized type");
Debug.Assert(!pTargetType->IsFunctionPointer, "did not expect function pointer type");
Debug.Assert(pTargetType->IsInterface, "IsInstanceOfInterface called with non-interface MethodTable");
int numInterfaces = pObjType->NumInterfaces;
MethodTable** interfaceMap = pObjType->InterfaceMap;
for (int i = 0; i < numInterfaces; i++)
{
MethodTable* pInterfaceType = interfaceMap[i];
if (pInterfaceType == pTargetType)
{
return true;
}
}
// We did not find the interface type in the list of supported interfaces. There's still one
// chance left: if the target interface is generic and one or more of its type parameters is co or
// contra variant then the object can still match if it implements a different instantiation of
// the interface with type compatible generic arguments.
//
// Interfaces which are only variant for arrays have the HasGenericVariance flag set even if they
// are not variant.
bool fArrayCovariance = pObjType->IsArray;
if (pTargetType->HasGenericVariance)
{
// Grab details about the instantiation of the target generic interface.
MethodTable* pTargetGenericType = pTargetType->GenericDefinition;
MethodTableList targetInstantiation = pTargetType->GenericArguments;
int targetArity = (int)pTargetType->GenericArity;
GenericVariance* pTargetVarianceInfo = pTargetType->GenericVariance;
Debug.Assert(pTargetVarianceInfo != null, "did not expect empty variance info");
for (int i = 0; i < numInterfaces; i++)
{
MethodTable* pInterfaceType = interfaceMap[i];
// We can ignore interfaces which are not also marked as having generic variance
// unless we're dealing with array covariance.
//
// Interfaces which are only variant for arrays have the HasGenericVariance flag set even if they
// are not variant.
if (pInterfaceType->HasGenericVariance)
{
MethodTable* pInterfaceGenericType = pInterfaceType->GenericDefinition;
// If the generic types aren't the same then the types aren't compatible.
if (pInterfaceGenericType != pTargetGenericType)
continue;
// Grab instantiation details for the candidate interface.
MethodTableList interfaceInstantiation = pInterfaceType->GenericArguments;
int interfaceArity = (int)pInterfaceType->GenericArity;
GenericVariance* pInterfaceVarianceInfo = pInterfaceType->GenericVariance;
Debug.Assert(pInterfaceVarianceInfo != null, "did not expect empty variance info");
// The types represent different instantiations of the same generic type. The
// arity of both had better be the same.
Debug.Assert(targetArity == interfaceArity, "arity mismatch between generic instantiations");
// Compare the instantiations to see if they're compatible taking variance into account.
if (TypeParametersAreCompatible(targetArity,
interfaceInstantiation,
targetInstantiation,
pTargetVarianceInfo,
fArrayCovariance,
pVisited))
return true;
}
}
}
return false;
}
// Compare two types to see if they are compatible via generic variance.
private static unsafe bool TypesAreCompatibleViaGenericVariance(MethodTable* pSourceType, MethodTable* pTargetType, EETypePairList* pVisited)
{
MethodTable* pTargetGenericType = pTargetType->GenericDefinition;
MethodTable* pSourceGenericType = pSourceType->GenericDefinition;
// If the generic types aren't the same then the types aren't compatible.
if (pSourceGenericType == pTargetGenericType)
{
// Get generic instantiation metadata for both types.
MethodTableList targetInstantiation = pTargetType->GenericArguments;
int targetArity = (int)pTargetType->GenericArity;
GenericVariance* pTargetVarianceInfo = pTargetType->GenericVariance;
Debug.Assert(pTargetVarianceInfo != null, "did not expect empty variance info");
MethodTableList sourceInstantiation = pSourceType->GenericArguments;
int sourceArity = (int)pSourceType->GenericArity;
GenericVariance* pSourceVarianceInfo = pSourceType->GenericVariance;
Debug.Assert(pSourceVarianceInfo != null, "did not expect empty variance info");
// The types represent different instantiations of the same generic type. The
// arity of both had better be the same.
Debug.Assert(targetArity == sourceArity, "arity mismatch between generic instantiations");
// Compare the instantiations to see if they're compatible taking variance into account.
if (TypeParametersAreCompatible(targetArity,
sourceInstantiation,
targetInstantiation,
pTargetVarianceInfo,
false,
pVisited))
{
return true;
}
}
return false;
}
// Compare two sets of generic type parameters to see if they're assignment compatible taking generic
// variance into account. It's assumed they've already had their type definition matched (which
// implies their arities are the same as well). The fForceCovariance argument tells the method to
// override the defined variance of each parameter and instead assume it is covariant. This is used to
// implement covariant array interfaces.
internal static unsafe bool TypeParametersAreCompatible(int arity,
MethodTableList sourceInstantiation,
MethodTableList targetInstantiation,
GenericVariance* pVarianceInfo,
bool fForceCovariance,
EETypePairList* pVisited)
{
// Walk through the instantiations comparing the cast compatibility of each pair
// of type args.
for (int i = 0; i < arity; i++)
{
MethodTable* pTargetArgType = targetInstantiation[i];
MethodTable* pSourceArgType = sourceInstantiation[i];
GenericVariance varType;
if (fForceCovariance)
varType = GenericVariance.ArrayCovariant;
else
varType = pVarianceInfo[i];
switch (varType)
{
case GenericVariance.NonVariant:
// Non-variant type params need to be identical.
if (pSourceArgType != pTargetArgType)
return false;
break;
case GenericVariance.Covariant:
// For covariance (or out type params in C#) the object must implement an
// interface with a more derived type arg than the target interface. Or
// the object interface can have a type arg that is an interface
// implemented by the target type arg.
// For instance:
// class Foo : ICovariant<String> is ICovariant<Object>
// class Foo : ICovariant<Bar> is ICovariant<IBar>
// class Foo : ICovariant<IBar> is ICovariant<Object>
if (!AreTypesAssignableInternal(pSourceArgType, pTargetArgType, AssignmentVariation.Unboxed, pVisited))
return false;
break;
case GenericVariance.ArrayCovariant:
// For array covariance the object must be an array with a type arg
// that is more derived than that the target interface, or be a primitive
// (or enum) with the same size.
// For instance:
// string[,,] is object[,,]
// int[,,] is uint[,,]
// This call is just like the call for Covariance above except true is passed
// to the fAllowSizeEquivalence parameter to allow the int/uint matching to work
if (!AreTypesAssignableInternal(pSourceArgType, pTargetArgType, AssignmentVariation.AllowSizeEquivalence, pVisited))
return false;
break;
case GenericVariance.Contravariant:
// For contravariance (or in type params in C#) the object must implement
// an interface with a less derived type arg than the target interface. Or
// the object interface can have a type arg that is a class implementing
// the interface that is the target type arg.
// For instance:
// class Foo : IContravariant<Object> is IContravariant<String>
// class Foo : IContravariant<IBar> is IContravariant<Bar>
// class Foo : IContravariant<Object> is IContravariant<IBar>
if (!AreTypesAssignableInternal(pTargetArgType, pSourceArgType, AssignmentVariation.Unboxed, pVisited))
return false;
break;
default:
Debug.Assert(false, "unknown generic variance type");
break;
}
}
return true;
}
[RuntimeExport("RhTypeCast_CheckArrayStore")]
public static unsafe void CheckArrayStore(object array, object obj)
{
if (array == null || obj == null)
{
return;
}
Debug.Assert(array.GetMethodTable()->IsArray, "first argument must be an array");
MethodTable* arrayElemType = array.GetMethodTable()->RelatedParameterType;
if (AreTypesAssignableInternal(obj.GetMethodTable(), arrayElemType, AssignmentVariation.BoxedSource, null))
return;
// If object type implements IDynamicInterfaceCastable then there's one more way to check whether it implements
// the interface.
if (obj.GetMethodTable()->IsIDynamicInterfaceCastable && IsInstanceOfInterfaceViaIDynamicInterfaceCastable(arrayElemType, obj, throwing: false))
return;
// Throw the array type mismatch exception defined by the classlib, using the input array's MethodTable*
// to find the correct classlib.
throw array.GetMethodTable()->GetClasslibException(ExceptionIDs.ArrayTypeMismatch);
}
internal struct ArrayElement
{
public object Value;
}
//
// Array stelem/ldelema helpers with RyuJIT conventions
//
[RuntimeExport("RhpStelemRef")]
public static unsafe void StelemRef(Array array, nint index, object obj)
{
// This is supported only on arrays
Debug.Assert(array.GetMethodTable()->IsArray, "first argument must be an array");
#if INPLACE_RUNTIME
// this will throw appropriate exceptions if array is null or access is out of range.
ref object element = ref Unsafe.As<ArrayElement[]>(array)[index].Value;
#else
if (array is null)
{
// TODO: If both array and obj are null, we're likely going to throw Redhawk's NullReferenceException.
// This should blame the caller.
throw obj.GetMethodTable()->GetClasslibException(ExceptionIDs.NullReference);
}
if ((uint)index >= (uint)array.Length)
{
throw array.GetMethodTable()->GetClasslibException(ExceptionIDs.IndexOutOfRange);
}
ref object rawData = ref Unsafe.As<byte, object>(ref Unsafe.As<RawArrayData>(array).Data);
ref object element = ref Unsafe.Add(ref rawData, index);
#endif
MethodTable* elementType = array.GetMethodTable()->RelatedParameterType;
if (obj == null)
goto assigningNull;
if (elementType != obj.GetMethodTable())
goto notExactMatch;
doWrite:
InternalCalls.RhpAssignRef(ref element, obj);
return;
assigningNull:
element = null;
return;
notExactMatch:
#if INPLACE_RUNTIME
// This optimization only makes sense for inplace runtime where there's only one System.Object.
if (array.GetMethodTable() == MethodTable.Of<object[]>())
goto doWrite;
#endif
StelemRef_Helper(ref element, elementType, obj);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void StelemRef_Helper(ref object element, MethodTable* elementType, object obj)
{
CastResult result = s_castCache.TryGet((nuint)obj.GetMethodTable() + (int)AssignmentVariation.BoxedSource, (nuint)elementType);
if (result == CastResult.CanCast)
{
InternalCalls.RhpAssignRef(ref element, obj);
return;
}
StelemRef_Helper_NoCacheLookup(ref element, elementType, obj);
}
private static unsafe void StelemRef_Helper_NoCacheLookup(ref object element, MethodTable* elementType, object obj)
{
object? castedObj = IsInstanceOfAny_NoCacheLookup(elementType, obj);
if (castedObj != null)
{
InternalCalls.RhpAssignRef(ref element, obj);
return;
}
// Throw the array type mismatch exception defined by the classlib, using the input array's
// MethodTable* to find the correct classlib.
throw elementType->GetClasslibException(ExceptionIDs.ArrayTypeMismatch);
}
[RuntimeExport("RhpLdelemaRef")]
public static unsafe ref object LdelemaRef(Array array, nint index, IntPtr elementType)
{
Debug.Assert(array is null || array.GetMethodTable()->IsArray, "first argument must be an array");
#if INPLACE_RUNTIME
// this will throw appropriate exceptions if array is null or access is out of range.
ref object element = ref Unsafe.As<ArrayElement[]>(array)[index].Value;
#else
if (array is null)
{
throw ((MethodTable*)elementType)->GetClasslibException(ExceptionIDs.NullReference);
}
if ((uint)index >= (uint)array.Length)
{
throw ((MethodTable*)elementType)->GetClasslibException(ExceptionIDs.IndexOutOfRange);
}
ref object rawData = ref Unsafe.As<byte, object>(ref Unsafe.As<RawArrayData>(array).Data);
ref object element = ref Unsafe.Add(ref rawData, index);
#endif
MethodTable* elemType = (MethodTable*)elementType;
MethodTable* arrayElemType = array.GetMethodTable()->RelatedParameterType;
if (elemType == arrayElemType)
{
return ref element;
}
return ref ThrowArrayMismatchException(array);
}
// This weird structure is for parity with CoreCLR - allows potentially to be tailcalled
private static unsafe ref object ThrowArrayMismatchException(Array array)
{
// Throw the array type mismatch exception defined by the classlib, using the input array's MethodTable*
// to find the correct classlib.
throw array.GetMethodTable()->GetClasslibException(ExceptionIDs.ArrayTypeMismatch);
}
private static unsafe object IsInstanceOfArray(MethodTable* pTargetType, object obj)
{
MethodTable* pObjType = obj.GetMethodTable();
Debug.Assert(pTargetType->IsArray, "IsInstanceOfArray called with non-array MethodTable");
// if the types match, we are done
if (pObjType == pTargetType)
{
return obj;
}
// if the object is not an array, we're done
if (!pObjType->IsArray)
{
return null;
}
// compare the array types structurally
if (pObjType->ParameterizedTypeShape != pTargetType->ParameterizedTypeShape)
{
// If the shapes are different, there's one more case to check for: Casting SzArray to MdArray rank 1.
if (!pObjType->IsSzArray || pTargetType->ArrayRank != 1)
{
return null;
}
}
if (AreTypesAssignableInternal(pObjType->RelatedParameterType, pTargetType->RelatedParameterType,
AssignmentVariation.AllowSizeEquivalence, null))
{
return obj;
}
return null;
}
private static unsafe object CheckCastArray(MethodTable* pTargetEEType, object obj)
{
object result = IsInstanceOfArray(pTargetEEType, obj);
if (result == null)
{
// Throw the invalid cast exception defined by the classlib, using the input MethodTable*
// to find the correct classlib.
return ThrowInvalidCastException(pTargetEEType);
}
return result;
}
private static unsafe object IsInstanceOfVariantType(MethodTable* pTargetType, object obj)
{
if (!AreTypesAssignableInternal(obj.GetMethodTable(), pTargetType, AssignmentVariation.BoxedSource, null)
&& (!obj.GetMethodTable()->IsIDynamicInterfaceCastable
|| !IsInstanceOfInterfaceViaIDynamicInterfaceCastable(pTargetType, obj, throwing: false)))
{
return null;
}
return obj;
}
private static unsafe object CheckCastVariantType(MethodTable* pTargetType, object obj)
{
if (!AreTypesAssignableInternal(obj.GetMethodTable(), pTargetType, AssignmentVariation.BoxedSource, null)
&& (!obj.GetMethodTable()->IsIDynamicInterfaceCastable
|| !IsInstanceOfInterfaceViaIDynamicInterfaceCastable(pTargetType, obj, throwing: true)))
{
return ThrowInvalidCastException(pTargetType);
}
return obj;
}
private static unsafe EETypeElementType GetNormalizedIntegralArrayElementType(MethodTable* type)
{
EETypeElementType elementType = type->ElementType;
switch (elementType)
{
case EETypeElementType.Byte:
case EETypeElementType.UInt16:
case EETypeElementType.UInt32:
case EETypeElementType.UInt64:
case EETypeElementType.UIntPtr:
return elementType - 1;
}
return elementType;
}
// Would not be inlined, but still need to mark NoInlining so that it doesn't throw off tail calls
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe object ThrowInvalidCastException(MethodTable* pMT)
{
throw pMT->GetClasslibException(ExceptionIDs.InvalidCast);
}
internal unsafe struct EETypePairList
{
private MethodTable* _eetype1;
private MethodTable* _eetype2;
private EETypePairList* _next;
public EETypePairList(MethodTable* pEEType1, MethodTable* pEEType2, EETypePairList* pNext)
{
_eetype1 = pEEType1;
_eetype2 = pEEType2;
_next = pNext;
}
public static bool Exists(EETypePairList* pList, MethodTable* pEEType1, MethodTable* pEEType2)
{
while (pList != null)
{
if (pList->_eetype1 == pEEType1 && pList->_eetype2 == pEEType2)
return true;
if (pList->_eetype1 == pEEType2 && pList->_eetype2 == pEEType1)
return true;
pList = pList->_next;
}
return false;
}
}
//
// Determines if a value of the source type can be assigned to a location of the target type.
// It does not handle IDynamicInterfaceCastable, and cannot since we do not have an actual object instance here.
// This routine assumes that the source type is boxed, i.e. a value type source is presumed to be
// compatible with Object and ValueType and an enum source is additionally compatible with Enum.
//
[RuntimeExport("RhTypeCast_AreTypesAssignable")]
public static unsafe bool AreTypesAssignable(MethodTable* pSourceType, MethodTable* pTargetType)
{