/
TypeBuilder.cs
1360 lines (1095 loc) · 58.5 KB
/
TypeBuilder.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;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.NativeFormat;
using Internal.TypeSystem;
namespace Internal.Runtime.TypeLoader
{
using DynamicGenericsRegistrationData = TypeLoaderEnvironment.DynamicGenericsRegistrationData;
using GenericTypeEntry = TypeLoaderEnvironment.GenericTypeEntry;
using GenericMethodEntry = TypeLoaderEnvironment.GenericMethodEntry;
using MethodDescBasedGenericMethodLookup = TypeLoaderEnvironment.MethodDescBasedGenericMethodLookup;
internal static class LowLevelListExtensions
{
public static void Expand<T>(this LowLevelList<T> list, int count)
{
if (list.Capacity < count)
list.Capacity = count;
while (list.Count < count)
list.Add(default(T));
}
public static bool HasSetBits(this LowLevelList<bool> list)
{
for (int index = 0; index < list.Count; index++)
{
if (list[index])
return true;
}
return false;
}
}
internal class TypeBuilder
{
public TypeBuilder()
{
TypeLoaderEnvironment.Instance.VerifyTypeLoaderLockHeld();
}
/// <summary>
/// The StaticClassConstructionContext for a type is encoded in the negative space
/// of the NonGCStatic fields of a type.
/// </summary>
public static unsafe int ClassConstructorOffset => -sizeof(System.Runtime.CompilerServices.StaticClassConstructionContext);
private LowLevelList<TypeDesc> _typesThatNeedTypeHandles = new LowLevelList<TypeDesc>();
private LowLevelList<InstantiatedMethod> _methodsThatNeedDictionaries = new LowLevelList<InstantiatedMethod>();
private LowLevelList<TypeDesc> _typesThatNeedPreparation;
#if DEBUG
private bool _finalTypeBuilding;
#endif
// Helper exception to abort type building if we do not find the generic type template
internal class MissingTemplateException : Exception
{
public MissingTemplateException()
// Cannot afford calling into resource manager from here, even to get the default message for System.Exception.
// This exception is always caught and rethrown as something more user friendly.
: base("Template is missing") { }
}
internal static bool RetrieveMethodDictionaryIfPossible(InstantiatedMethod method)
{
if (method.RuntimeMethodDictionary != IntPtr.Zero)
return true;
TypeLoaderLogger.WriteLine("Looking for method dictionary for method " + method.ToString() + " ... ");
IntPtr methodDictionary;
if (TypeLoaderEnvironment.Instance.TryLookupGenericMethodDictionary(new MethodDescBasedGenericMethodLookup(method), out methodDictionary))
{
TypeLoaderLogger.WriteLine("Found DICT = " + methodDictionary.LowLevelToString() + " for method " + method.ToString());
method.AssociateWithRuntimeMethodDictionary(methodDictionary);
return true;
}
return false;
}
/// <summary>
/// Register the type for preparation. The preparation will be done once the current type is prepared.
/// This is the preferred way to get a dependent type prepared because of it avoids issues with cycles and recursion.
/// </summary>
public void RegisterForPreparation(TypeDesc type)
{
TypeLoaderLogger.WriteLine("Register for preparation " + type.ToString() + " ...");
// If this type has type handle, do nothing and return
if (type.RetrieveRuntimeTypeHandleIfPossible())
return;
var state = type.GetOrCreateTypeBuilderState();
// If this type was already inspected, do nothing and return.
if (state.NeedsTypeHandle)
return;
state.NeedsTypeHandle = true;
if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
return;
_typesThatNeedPreparation ??= new LowLevelList<TypeDesc>();
_typesThatNeedPreparation.Add(type);
}
/// <summary>
/// Collects all dependencies that need to be created in order to create
/// the method that was passed in.
/// </summary>
public void PrepareMethod(MethodDesc method)
{
TypeLoaderLogger.WriteLine("Preparing method " + method.ToString() + " ...");
RegisterForPreparation(method.OwningType);
if (method.Instantiation.Length == 0)
return;
InstantiatedMethod genericMethod = (InstantiatedMethod)method;
if (RetrieveMethodDictionaryIfPossible(genericMethod))
return;
// If this method was already inspected, do nothing and return
if (genericMethod.NeedsDictionary)
return;
genericMethod.NeedsDictionary = true;
if (genericMethod.IsCanonicalMethod(CanonicalFormKind.Any))
return;
_methodsThatNeedDictionaries.Add(genericMethod);
foreach (var type in genericMethod.Instantiation)
RegisterForPreparation(type);
ParseNativeLayoutInfo(genericMethod);
}
private void InsertIntoNeedsTypeHandleList(TypeDesc type)
{
if ((type is DefType) || (type is ArrayType) || (type is PointerType) || (type is ByRefType))
{
_typesThatNeedTypeHandles.Add(type);
}
}
/// <summary>
/// Collects all dependencies that need to be created in order to create
/// the type that was passed in.
/// </summary>
internal void PrepareType(TypeDesc type)
{
TypeLoaderLogger.WriteLine("Preparing type " + type.ToString() + " ...");
TypeBuilderState state = type.GetTypeBuilderStateIfExist();
bool hasTypeHandle = type.RetrieveRuntimeTypeHandleIfPossible();
// If this type has type handle, do nothing and return unless we should prepare even in the presence of a type handle
if (hasTypeHandle)
return;
state ??= type.GetOrCreateTypeBuilderState();
// If this type was already prepared, do nothing unless we are re-preparing it for the purpose of loading the field layout
if (state.HasBeenPrepared)
{
return;
}
state.HasBeenPrepared = true;
state.NeedsTypeHandle = true;
if (!hasTypeHandle)
{
InsertIntoNeedsTypeHandleList(type);
}
bool noExtraPreparation = false; // Set this to true for types which don't need other types to be prepared. I.e GenericTypeDefinitions
if (type is DefType typeAsDefType)
{
if (typeAsDefType.HasInstantiation)
{
if (typeAsDefType.IsTypeDefinition)
{
noExtraPreparation = true;
}
else
{
// This call to ComputeTemplate will find the native layout info for the type, and the template
// For metadata loaded types, a template will not exist, but we may find the NativeLayout describing the generic dictionary
TypeDesc.ComputeTemplate(state, false);
Debug.Assert(state.TemplateType == null || (state.TemplateType is DefType && !state.TemplateType.RuntimeTypeHandle.IsNull()));
// Collect dependencies
// We need the instantiation arguments to register a generic type
foreach (var instArg in typeAsDefType.Instantiation)
RegisterForPreparation(instArg);
ParseNativeLayoutInfo(state, type);
}
}
if (!noExtraPreparation)
state.PrepareStaticGCLayout();
}
else if (type is ParameterizedType)
{
PrepareType(((ParameterizedType)type).ParameterType);
if (type is ArrayType typeAsArrayType)
{
if (typeAsArrayType.IsSzArray && !typeAsArrayType.ElementType.IsPointer)
{
TypeDesc.ComputeTemplate(state);
Debug.Assert(state.TemplateType != null && state.TemplateType is ArrayType && !state.TemplateType.RuntimeTypeHandle.IsNull());
ParseNativeLayoutInfo(state, type);
}
else
{
Debug.Assert(typeAsArrayType.IsMdArray || typeAsArrayType.ElementType.IsPointer);
}
}
}
else
{
Debug.Assert(false);
}
// Need to prepare the base type first since it is used to compute interfaces
if (!noExtraPreparation)
{
PrepareBaseTypeAndDictionaries(type);
PrepareRuntimeInterfaces(type);
TypeLoaderLogger.WriteLine("Layout for type " + type.ToString() + " complete.");
}
}
/// <summary>
/// Recursively triggers preparation for a type's runtime interfaces
/// </summary>
private void PrepareRuntimeInterfaces(TypeDesc type)
{
// Prepare all the interfaces that might be used. (This can be a superset of the
// interfaces explicitly in the NativeLayout.)
foreach (DefType interfaceType in type.RuntimeInterfaces)
{
PrepareType(interfaceType);
}
}
/// <summary>
/// Triggers preparation for a type's base types
/// </summary>
private void PrepareBaseTypeAndDictionaries(TypeDesc type)
{
DefType baseType = type.BaseType;
if (baseType == null)
return;
PrepareType(baseType);
}
private void ProcessTypesNeedingPreparation()
{
// Process the pending types
while (_typesThatNeedPreparation != null)
{
var pendingTypes = _typesThatNeedPreparation;
_typesThatNeedPreparation = null;
for (int i = 0; i < pendingTypes.Count; i++)
PrepareType(pendingTypes[i]);
}
}
internal void ParseNativeLayoutInfo(InstantiatedMethod method)
{
TypeLoaderLogger.WriteLine("Parsing NativeLayoutInfo for method " + method.ToString() + " ...");
Debug.Assert(method.Dictionary == null);
InstantiatedMethod nonTemplateMethod = method;
// Templates are always non-unboxing stubs
if (method.UnboxingStub)
{
// Strip unboxing stub, note the first parameter which is false
nonTemplateMethod = (InstantiatedMethod)method.Context.ResolveGenericMethodInstantiation(false, (DefType)method.OwningType, method.NameAndSignature, method.Instantiation, IntPtr.Zero, false);
}
uint nativeLayoutInfoToken;
NativeFormatModuleInfo nativeLayoutModule;
InstantiatedMethod templateMethod = TemplateLocator.TryGetGenericMethodTemplate(nonTemplateMethod, out nativeLayoutModule, out nativeLayoutInfoToken);
if (templateMethod == null)
{
throw new MissingTemplateException();
}
if (templateMethod.FunctionPointer != IntPtr.Zero)
{
nonTemplateMethod.SetFunctionPointer(templateMethod.FunctionPointer, isFunctionPointerUSG: false);
}
// Ensure that if this method is non-shareable from a normal canonical perspective, then
// its template MUST be a universal canonical template method
Debug.Assert(!method.IsNonSharableMethod || (method.IsNonSharableMethod && templateMethod.IsCanonicalMethod(CanonicalFormKind.Universal)));
NativeReader nativeLayoutInfoReader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(nativeLayoutModule.Handle);
var methodInfoParser = new NativeParser(nativeLayoutInfoReader, nativeLayoutInfoToken);
var context = new NativeLayoutInfoLoadContext
{
_typeSystemContext = method.Context,
_typeArgumentHandles = method.OwningType.Instantiation,
_methodArgumentHandles = method.Instantiation,
_module = nativeLayoutModule
};
BagElementKind kind;
while ((kind = methodInfoParser.GetBagElementKind()) != BagElementKind.End)
{
switch (kind)
{
case BagElementKind.DictionaryLayout:
TypeLoaderLogger.WriteLine("Found BagElementKind.DictionaryLayout");
method.SetGenericDictionary(new GenericMethodDictionary(GenericDictionaryCell.BuildDictionary(this, context, methodInfoParser.GetParserFromRelativeOffset())));
break;
default:
Debug.Fail("Unexpected BagElementKind for generic method with name " + method.NameAndSignature.Name + "! Only BagElementKind.DictionaryLayout should appear.");
throw new BadImageFormatException();
}
}
if (method.Dictionary == null)
method.SetGenericDictionary(new GenericMethodDictionary(Array.Empty<GenericDictionaryCell>()));
}
internal void ParseNativeLayoutInfo(TypeBuilderState state, TypeDesc type)
{
TypeLoaderLogger.WriteLine("Parsing NativeLayoutInfo for type " + type.ToString() + " ...");
bool isTemplateUniversalCanon = false;
if (state.TemplateType != null)
{
isTemplateUniversalCanon = state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal);
}
if (state.TemplateType == null)
{
throw new MissingTemplateException();
}
NativeParser typeInfoParser = state.GetParserForNativeLayoutInfo();
NativeLayoutInfoLoadContext context = state.NativeLayoutInfo.LoadContext;
NativeParser baseTypeParser = new NativeParser();
BagElementKind kind;
while ((kind = typeInfoParser.GetBagElementKind()) != BagElementKind.End)
{
switch (kind)
{
case BagElementKind.BaseType:
TypeLoaderLogger.WriteLine("Found BagElementKind.BaseType");
Debug.Assert(baseTypeParser.IsNull);
baseTypeParser = typeInfoParser.GetParserFromRelativeOffset();
break;
case BagElementKind.ImplementedInterfaces:
TypeLoaderLogger.WriteLine("Found BagElementKind.ImplementedInterfaces");
// Interface handling is done entirely in NativeLayoutInterfacesAlgorithm
typeInfoParser.GetUnsigned();
break;
case BagElementKind.ClassConstructorPointer:
TypeLoaderLogger.WriteLine("Found BagElementKind.ClassConstructorPointer");
state.ClassConstructorPointer = context.GetGCStaticInfo(typeInfoParser.GetUnsigned());
break;
case BagElementKind.NonGcStaticDataSize:
TypeLoaderLogger.WriteLine("Found BagElementKind.NonGcStaticDataSize");
// Use checked typecast to int to ensure there aren't any overflows/truncations (size value used in allocation of memory later)
state.NonGcDataSize = checked((int)typeInfoParser.GetUnsigned());
break;
case BagElementKind.GcStaticDataSize:
TypeLoaderLogger.WriteLine("Found BagElementKind.GcStaticDataSize");
// Use checked typecast to int to ensure there aren't any overflows/truncations (size value used in allocation of memory later)
state.GcDataSize = checked((int)typeInfoParser.GetUnsigned());
break;
case BagElementKind.ThreadStaticDataSize:
TypeLoaderLogger.WriteLine("Found BagElementKind.ThreadStaticDataSize");
// Use checked typecast to int to ensure there aren't any overflows/truncations (size value used in allocation of memory later)
state.ThreadDataSize = checked((int)typeInfoParser.GetUnsigned());
break;
case BagElementKind.GcStaticDesc:
TypeLoaderLogger.WriteLine("Found BagElementKind.GcStaticDesc");
state.GcStaticDesc = context.GetGCStaticInfo(typeInfoParser.GetUnsigned());
break;
case BagElementKind.ThreadStaticDesc:
TypeLoaderLogger.WriteLine("Found BagElementKind.ThreadStaticDesc");
state.ThreadStaticDesc = context.GetGCStaticInfo(typeInfoParser.GetUnsigned());
break;
case BagElementKind.GenericVarianceInfo:
TypeLoaderLogger.WriteLine("Found BagElementKind.GenericVarianceInfo");
NativeParser varianceInfoParser = typeInfoParser.GetParserFromRelativeOffset();
state.GenericVarianceFlags = new GenericVariance[varianceInfoParser.GetSequenceCount()];
for (int i = 0; i < state.GenericVarianceFlags.Length; i++)
state.GenericVarianceFlags[i] = checked((GenericVariance)varianceInfoParser.GetUnsigned());
break;
case BagElementKind.FieldLayout:
TypeLoaderLogger.WriteLine("Found BagElementKind.FieldLayout");
typeInfoParser.SkipInteger(); // Handled in type layout algorithm
break;
case BagElementKind.DictionaryLayout:
TypeLoaderLogger.WriteLine("Found BagElementKind.DictionaryLayout");
Debug.Assert(!isTemplateUniversalCanon, "Universal template nativelayout do not have DictionaryLayout");
Debug.Assert(state.Dictionary == null);
if (!state.TemplateType.RetrieveRuntimeTypeHandleIfPossible())
{
TypeLoaderLogger.WriteLine("ERROR: failed to get type handle for template type " + state.TemplateType.ToString());
throw new TypeBuilder.MissingTemplateException();
}
state.Dictionary = new GenericTypeDictionary(GenericDictionaryCell.BuildDictionary(this, context, typeInfoParser.GetParserFromRelativeOffset()));
break;
default:
TypeLoaderLogger.WriteLine("Found unknown BagElementKind: " + ((int)kind).LowLevelToString());
typeInfoParser.SkipInteger();
break;
}
}
type.ParseBaseType(context, baseTypeParser);
}
/// <summary>
/// Wraps information about how a type is laid out into one package. Types may have been laid out by
/// TypeBuilder (which means they have a gc bitfield), or they could be types that were laid out by NUTC
/// (which means we only have a GCDesc for them). This struct wraps both of those possibilities into
/// one package to be able to write that layout to another bitfield we are constructing. (This is for
/// struct fields.)
/// </summary>
internal unsafe struct GCLayout
{
private LowLevelList<bool> _bitfield;
private unsafe void* _gcdesc;
private int _size;
private bool _isReferenceTypeGCLayout;
public static GCLayout None { get { return new GCLayout(); } }
public static GCLayout SingleReference { get; } = new GCLayout(new LowLevelList<bool>(new bool[1] { true }), false);
public bool IsNone { get { return _bitfield == null && _gcdesc == null; } }
public GCLayout(LowLevelList<bool> bitfield, bool isReferenceTypeGCLayout)
{
Debug.Assert(bitfield != null);
_bitfield = bitfield;
_gcdesc = null;
_size = 0;
_isReferenceTypeGCLayout = isReferenceTypeGCLayout;
}
public GCLayout(RuntimeTypeHandle rtth)
{
MethodTable* MethodTable = rtth.ToEETypePtr();
Debug.Assert(MethodTable != null);
_bitfield = null;
_isReferenceTypeGCLayout = false; // This field is only used for the LowLevelList<bool> path
_gcdesc = MethodTable->ContainsGCPointers ? (void**)MethodTable - 1 : null;
_size = (int)MethodTable->BaseSize;
}
/// <summary>
/// Writes this layout to the given bitfield.
/// </summary>
/// <param name="bitfield">The bitfield to write a layout to (may be null, at which
/// point it will be created and assigned).</param>
/// <param name="offset">The offset at which we need to write the bitfield.</param>
public void WriteToBitfield(LowLevelList<bool> bitfield, int offset)
{
ArgumentNullException.ThrowIfNull(bitfield);
if (IsNone)
return;
// Ensure exactly one of these two are set.
Debug.Assert(_gcdesc != null ^ _bitfield != null);
if (_bitfield != null)
MergeBitfields(bitfield, offset);
else
WriteGCDescToBitfield(bitfield, offset);
}
private unsafe void WriteGCDescToBitfield(LowLevelList<bool> bitfield, int offset)
{
int startIndex = offset / IntPtr.Size;
void** ptr = (void**)_gcdesc;
Debug.Assert(_gcdesc != null);
// Number of series
int count = (int)*ptr-- - 1;
Debug.Assert(count >= 0);
// Ensure capacity for the values we are about to write
int capacity = startIndex + _size / IntPtr.Size - 2;
bitfield.Expand(capacity);
while (count-- >= 0)
{
int offs = (int)*ptr-- / IntPtr.Size - 1;
int len = ((int)*ptr-- + _size) / IntPtr.Size;
Debug.Assert(len > 0);
Debug.Assert(offs >= 0);
for (int i = 0; i < len; i++)
bitfield[startIndex + offs + i] = true;
}
}
private void MergeBitfields(LowLevelList<bool> outputBitfield, int offset)
{
int startIndex = offset / IntPtr.Size;
// These routines represent the GC layout after the MethodTable pointer
// in an object, but the LowLevelList<bool> bitfield logically contains
// the EETypepointer if it is describing a reference type. So, skip the
// first value.
int itemsToSkip = _isReferenceTypeGCLayout ? 1 : 0;
// Assert that we only skip a non-reported pointer.
Debug.Assert(itemsToSkip == 0 || _bitfield[0] == false);
// Ensure capacity for the values we are about to write
int capacity = startIndex + _bitfield.Count - itemsToSkip;
outputBitfield.Expand(capacity);
for (int i = itemsToSkip; i < _bitfield.Count; i++)
{
// We should never overwrite a TRUE value in the table.
Debug.Assert(!outputBitfield[startIndex + i - itemsToSkip] || _bitfield[i]);
outputBitfield[startIndex + i - itemsToSkip] = _bitfield[i];
}
}
}
private unsafe void AllocateRuntimeType(TypeDesc type)
{
TypeBuilderState state = type.GetTypeBuilderState();
Debug.Assert(type is DefType || type is ArrayType || type is PointerType || type is ByRefType);
RuntimeTypeHandle rtt = EETypeCreator.CreateEEType(type, state);
if (state.ThreadDataSize != 0)
TypeLoaderEnvironment.Instance.RegisterDynamicThreadStaticsInfo(state.HalfBakedRuntimeTypeHandle, state.ThreadStaticOffset, state.ThreadStaticDesc);
TypeLoaderLogger.WriteLine("Allocated new type " + type.ToString() + " with hashcode value = 0x" + type.GetHashCode().LowLevelToString() + " with MethodTable = " + rtt.ToIntPtr().LowLevelToString() + " of size " + rtt.ToEETypePtr()->BaseSize.LowLevelToString());
}
private static void AllocateRuntimeMethodDictionary(InstantiatedMethod method)
{
Debug.Assert(method.RuntimeMethodDictionary == IntPtr.Zero && method.Dictionary != null);
IntPtr rmd = method.Dictionary.Allocate();
method.AssociateWithRuntimeMethodDictionary(rmd);
TypeLoaderLogger.WriteLine("Allocated new method dictionary for method " + method.ToString() + " @ " + rmd.LowLevelToString());
}
//
// Returns either the registered type handle or half-baked type handle. This method should be only called
// during final phase of type building.
//
#pragma warning disable CA1822
public RuntimeTypeHandle GetRuntimeTypeHandle(TypeDesc type)
{
#if DEBUG
Debug.Assert(_finalTypeBuilding);
#endif
var rtth = type.RuntimeTypeHandle;
if (!rtth.IsNull())
return rtth;
rtth = type.GetTypeBuilderState().HalfBakedRuntimeTypeHandle;
Debug.Assert(!rtth.IsNull());
return rtth;
}
#pragma warning restore CA1822
public RuntimeTypeHandle[] GetRuntimeTypeHandles(Instantiation types)
{
if (types.Length == 0)
return Array.Empty<RuntimeTypeHandle>();
RuntimeTypeHandle[] result = new RuntimeTypeHandle[types.Length];
for (int i = 0; i < types.Length; i++)
result[i] = GetRuntimeTypeHandle(types[i]);
return result;
}
public static DefType GetBaseTypeUsingRuntimeTypeHandle(TypeDesc type)
{
type.RetrieveRuntimeTypeHandleIfPossible();
unsafe
{
RuntimeTypeHandle thBaseTypeTemplate = type.RuntimeTypeHandle.ToEETypePtr()->BaseType->ToRuntimeTypeHandle();
if (thBaseTypeTemplate.IsNull())
return null;
return (DefType)type.Context.ResolveRuntimeTypeHandle(thBaseTypeTemplate);
}
}
public static DefType GetBaseTypeThatIsCorrectForMDArrays(TypeDesc type)
{
if (type.BaseType == type.Context.GetWellKnownType(WellKnownType.Array))
{
// Use the type from the template, the metadata we have will be inaccurate for multidimensional
// arrays, as we hide the MDArray infrastructure from the metadata.
TypeDesc template = type.ComputeTemplate(false);
return GetBaseTypeUsingRuntimeTypeHandle(template ?? type);
}
return type.BaseType;
}
private void FinishInterfaces(TypeBuilderState state)
{
DefType[] interfaces = state.RuntimeInterfaces;
if (interfaces != null)
{
for (int i = 0; i < interfaces.Length; i++)
{
state.HalfBakedRuntimeTypeHandle.SetInterface(i, GetRuntimeTypeHandle(interfaces[i]));
}
}
}
private unsafe void FinishTypeDictionary(TypeDesc type)
{
TypeBuilderState state = type.GetTypeBuilderState();
if (state.Dictionary != null)
{
// First, update the dictionary slot in the type's vtable to point to the created dictionary when applicable
Debug.Assert(state.HalfBakedDictionary != IntPtr.Zero);
int dictionarySlot = EETypeCreator.GetDictionarySlotInVTable(type);
if (dictionarySlot >= 0)
{
state.HalfBakedRuntimeTypeHandle.SetDictionary(dictionarySlot, state.HalfBakedDictionary);
}
else
{
// Dictionary shouldn't be in the vtable of the type
Debug.Assert(!type.CanShareNormalGenericCode());
}
TypeLoaderLogger.WriteLine("Setting dictionary entries for type " + type.ToString() + " @ " + state.HalfBakedDictionary.LowLevelToString());
state.Dictionary.Finish(this);
}
}
private unsafe void FinishMethodDictionary(InstantiatedMethod method)
{
Debug.Assert(method.Dictionary != null);
TypeLoaderLogger.WriteLine("Setting dictionary entries for method " + method.ToString() + " @ " + method.RuntimeMethodDictionary.LowLevelToString());
method.Dictionary.Finish(this);
}
private unsafe void FinishClassConstructor(TypeDesc type, TypeBuilderState state)
{
if (!state.HasStaticConstructor)
return;
IntPtr canonicalClassConstructorFunctionPointer = state.ClassConstructorPointer.Value;
IntPtr generatedTypeStaticData = GetRuntimeTypeHandle(type).ToEETypePtr()->DynamicNonGcStaticsData;
IntPtr* generatedTypeClassConstructorSlotPointer = (IntPtr*)((byte*)generatedTypeStaticData + ClassConstructorOffset);
// Use the template type's class constructor method pointer and this type's generic type dictionary to generate a new fat pointer,
// and save that fat pointer back to this type's class constructor context offset within the non-GC static data.
IntPtr instantiationArgument = GetRuntimeTypeHandle(type).ToIntPtr();
IntPtr generatedTypeClassConstructorFatFunctionPointer = FunctionPointerOps.GetGenericMethodFunctionPointer(canonicalClassConstructorFunctionPointer, instantiationArgument);
*generatedTypeClassConstructorSlotPointer = generatedTypeClassConstructorFatFunctionPointer;
}
private void CopyDictionaryFromTypeToAppropriateSlotInDerivedType(DefType baseType, TypeBuilderState derivedTypeState)
{
var baseTypeState = baseType.GetOrCreateTypeBuilderState();
if (baseTypeState.HasDictionaryInVTable)
{
RuntimeTypeHandle baseTypeHandle = GetRuntimeTypeHandle(baseType);
// If the basetype is currently being created by the TypeBuilder, we need to get its dictionary pointer from the
// TypeBuilder state (at this point, the dictionary has not yet been set on the baseTypeHandle). If
// the basetype is not a dynamic type, or has previously been dynamically allocated in the past, the TypeBuilder
// state will have a null dictionary pointer, in which case we need to read it directly from the basetype's vtable
IntPtr dictionaryEntry = baseTypeState.HalfBakedDictionary;
if (dictionaryEntry == IntPtr.Zero)
dictionaryEntry = baseTypeHandle.GetDictionary();
Debug.Assert(dictionaryEntry != IntPtr.Zero);
// Compute the vtable slot for the dictionary entry to set
int dictionarySlot = EETypeCreator.GetDictionarySlotInVTable(baseType);
Debug.Assert(dictionarySlot >= 0);
derivedTypeState.HalfBakedRuntimeTypeHandle.SetDictionary(dictionarySlot, dictionaryEntry);
TypeLoaderLogger.WriteLine("Setting basetype " + baseType.ToString() + " dictionary on type " + derivedTypeState.TypeBeingBuilt.ToString());
}
}
private void FinishBaseTypeAndDictionaries(TypeDesc type, TypeBuilderState state)
{
DefType baseType = GetBaseTypeThatIsCorrectForMDArrays(type);
state.HalfBakedRuntimeTypeHandle.SetBaseType(baseType == null ? default(RuntimeTypeHandle) : GetRuntimeTypeHandle(baseType));
if (baseType == null)
return;
// Update every dictionary in type hierarchy with copy from base type
while (baseType != null)
{
CopyDictionaryFromTypeToAppropriateSlotInDerivedType(baseType, state);
baseType = baseType.BaseType;
}
}
private void FinishRuntimeType(TypeDesc type)
{
TypeLoaderLogger.WriteLine("Finishing type " + type.ToString() + " ...");
var state = type.GetTypeBuilderState();
if (type is DefType typeAsDefType)
{
if (type.HasInstantiation)
{
// Type definitions don't need any further finishing once created by the EETypeCreator
if (type.IsTypeDefinition)
return;
state.HalfBakedRuntimeTypeHandle.SetGenericDefinition(GetRuntimeTypeHandle(typeAsDefType.GetTypeDefinition()));
Instantiation instantiation = typeAsDefType.Instantiation;
state.HalfBakedRuntimeTypeHandle.SetGenericArity((uint)instantiation.Length);
for (int argIndex = 0; argIndex < instantiation.Length; argIndex++)
{
state.HalfBakedRuntimeTypeHandle.SetGenericArgument(argIndex, GetRuntimeTypeHandle(instantiation[argIndex]));
if (state.GenericVarianceFlags != null)
{
Debug.Assert(state.GenericVarianceFlags.Length == instantiation.Length);
state.HalfBakedRuntimeTypeHandle.SetGenericVariance(argIndex, state.GenericVarianceFlags[argIndex]);
}
}
}
FinishBaseTypeAndDictionaries(type, state);
FinishInterfaces(state);
FinishClassConstructor(type, state);
}
else if (type is ParameterizedType)
{
if (type is ArrayType typeAsSzArrayType)
{
RuntimeTypeHandle elementTypeHandle = GetRuntimeTypeHandle(typeAsSzArrayType.ElementType);
state.HalfBakedRuntimeTypeHandle.SetRelatedParameterType(elementTypeHandle);
ushort componentSize = (ushort)IntPtr.Size;
unsafe
{
if (typeAsSzArrayType.ElementType.IsValueType)
componentSize = checked((ushort)elementTypeHandle.ToEETypePtr()->ValueTypeSize);
}
state.HalfBakedRuntimeTypeHandle.SetComponentSize(componentSize);
FinishInterfaces(state);
}
else if (type is PointerType)
{
state.HalfBakedRuntimeTypeHandle.SetRelatedParameterType(GetRuntimeTypeHandle(((PointerType)type).ParameterType));
// Nothing else to do for pointer types
}
else if (type is ByRefType)
{
state.HalfBakedRuntimeTypeHandle.SetRelatedParameterType(GetRuntimeTypeHandle(((ByRefType)type).ParameterType));
// We used a pointer type for the template because they're similar enough. Adjust this to be a ByRef.
unsafe
{
Debug.Assert(state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ParameterizedTypeShape == ParameterizedTypeShapeConstants.Pointer);
state.HalfBakedRuntimeTypeHandle.SetParameterizedTypeShape(ParameterizedTypeShapeConstants.ByRef);
Debug.Assert(state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ElementType == EETypeElementType.Pointer);
state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ElementType = EETypeElementType.ByRef;
}
}
}
else
{
Debug.Assert(false);
}
}
private IEnumerable<GenericTypeEntry> TypesToRegister()
{
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
DefType typeAsDefType = _typesThatNeedTypeHandles[i] as DefType;
if (typeAsDefType == null)
continue;
yield return new GenericTypeEntry
{
_genericTypeDefinitionHandle = GetRuntimeTypeHandle(typeAsDefType.GetTypeDefinition()),
_genericTypeArgumentHandles = GetRuntimeTypeHandles(typeAsDefType.Instantiation),
_instantiatedTypeHandle = typeAsDefType.GetTypeBuilderState().HalfBakedRuntimeTypeHandle
};
}
}
private IEnumerable<GenericMethodEntry> MethodsToRegister()
{
for (int i = 0; i < _methodsThatNeedDictionaries.Count; i++)
{
InstantiatedMethod method = _methodsThatNeedDictionaries[i];
yield return new GenericMethodEntry
{
_declaringTypeHandle = GetRuntimeTypeHandle(method.OwningType),
_genericMethodArgumentHandles = GetRuntimeTypeHandles(method.Instantiation),
_methodNameAndSignature = method.NameAndSignature,
_methodDictionary = method.RuntimeMethodDictionary
};
}
}
private void RegisterGenericTypesAndMethods()
{
int typesToRegisterCount = 0;
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
if (_typesThatNeedTypeHandles[i] is DefType)
typesToRegisterCount++;
}
DynamicGenericsRegistrationData registrationData = new DynamicGenericsRegistrationData
{
TypesToRegisterCount = typesToRegisterCount,
TypesToRegister = (typesToRegisterCount != 0) ? TypesToRegister() : null,
MethodsToRegisterCount = _methodsThatNeedDictionaries.Count,
MethodsToRegister = (_methodsThatNeedDictionaries.Count != 0) ? MethodsToRegister() : null,
};
TypeLoaderEnvironment.Instance.RegisterDynamicGenericTypesAndMethods(registrationData);
}
private void FinishTypeAndMethodBuilding()
{
// Once we start allocating EETypes and dictionaries, the only accepted failure is OOM.
// TODO: Error handling - on retry, restart where we failed last time? The current implementation is leaking on OOM.
#if DEBUG
_finalTypeBuilding = true;
#endif
// At this point we know all types that need EETypes. Allocate all EETypes so that we can start building
// their contents.
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
AllocateRuntimeType(_typesThatNeedTypeHandles[i]);
}
for (int i = 0; i < _methodsThatNeedDictionaries.Count; i++)
{
AllocateRuntimeMethodDictionary(_methodsThatNeedDictionaries[i]);
}
// Do not add more type phases here. Instead, read the required information from the TypeDesc or TypeBuilderState.
// Fill in content of all EETypes
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
FinishRuntimeType(_typesThatNeedTypeHandles[i]);
}
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
FinishTypeDictionary(_typesThatNeedTypeHandles[i]);
}
for (int i = 0; i < _methodsThatNeedDictionaries.Count; i++)
{
FinishMethodDictionary(_methodsThatNeedDictionaries[i]);
}
int newArrayTypesCount = 0;
int newPointerTypesCount = 0;
int newByRefTypesCount = 0;
int[] mdArrayNewTypesCount = null;
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
ParameterizedType typeAsParameterizedType = _typesThatNeedTypeHandles[i] as ParameterizedType;
if (typeAsParameterizedType == null)
continue;
if (typeAsParameterizedType.IsSzArray)
newArrayTypesCount++;
else if (typeAsParameterizedType.IsPointer)
newPointerTypesCount++;
else if (typeAsParameterizedType.IsByRef)
newByRefTypesCount++;
else if (typeAsParameterizedType.IsMdArray)
{
mdArrayNewTypesCount ??= new int[MDArray.MaxRank + 1];
mdArrayNewTypesCount[((ArrayType)typeAsParameterizedType).Rank]++;
}
}
// Reserve space in array/pointer cache's so that the actual adding can be fault-free.
var szArrayCache = TypeSystemContext.GetArrayTypesCache(false, -1);
szArrayCache.Reserve(szArrayCache.Count + newArrayTypesCount);
//
if (mdArrayNewTypesCount != null)
{
for (int i = 0; i < mdArrayNewTypesCount.Length; i++)
{
if (mdArrayNewTypesCount[i] == 0)
continue;
var mdArrayCache = TypeSystemContext.GetArrayTypesCache(true, i);
mdArrayCache.Reserve(mdArrayCache.Count + mdArrayNewTypesCount[i]);
}
}
TypeSystemContext.PointerTypesCache.Reserve(TypeSystemContext.PointerTypesCache.Count + newPointerTypesCount);
TypeSystemContext.ByRefTypesCache.Reserve(TypeSystemContext.ByRefTypesCache.Count + newByRefTypesCount);
// Finally, register all generic types and methods atomically with the runtime
RegisterGenericTypesAndMethods();
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
_typesThatNeedTypeHandles[i].SetRuntimeTypeHandleUnsafe(_typesThatNeedTypeHandles[i].GetTypeBuilderState().HalfBakedRuntimeTypeHandle);
TypeLoaderLogger.WriteLine("Successfully Registered type " + _typesThatNeedTypeHandles[i].ToString() + ".");
}
// Save all constructed array and pointer types to the types cache
for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++)
{
ParameterizedType typeAsParameterizedType = _typesThatNeedTypeHandles[i] as ParameterizedType;
if (typeAsParameterizedType == null)