/
TypeBuilder.cs
1973 lines (1580 loc) · 82.1 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using CultureInfo = System.Globalization.CultureInfo;
namespace System.Reflection.Emit
{
public sealed partial class TypeBuilder : TypeInfo
{
public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Declarations
private sealed class CustAttr
{
private readonly ConstructorInfo? m_con;
private readonly byte[]? m_binaryAttribute;
private readonly CustomAttributeBuilder? m_customBuilder;
public CustAttr(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
m_con = con;
m_binaryAttribute = binaryAttribute;
}
public CustAttr(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
m_customBuilder = customBuilder;
}
public void Bake(ModuleBuilder module, int token)
{
if (m_customBuilder == null)
{
Debug.Assert(m_con != null);
DefineCustomAttribute(module, token, module.GetConstructorToken(m_con),
m_binaryAttribute);
}
else
{
m_customBuilder.CreateCustomAttribute(module, token);
}
}
}
#endregion
#region Public Static Methods
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern",
Justification = "MakeGenericType is only called on a TypeBuilder which is not subject to trimming")]
public static MethodInfo GetMethod(Type type, MethodInfo method)
{
if (type is not TypeBuilder && type is not TypeBuilderInstantiation)
throw new ArgumentException(SR.Argument_MustBeTypeBuilder, nameof(type));
// The following checks establishes invariants that more simply put require type to be generic and
// method to be a generic method definition declared on the generic type definition of type.
// To create generic method G<Foo>.M<Bar> these invariants require that G<Foo>.M<S> be created by calling
// this function followed by MakeGenericMethod on the resulting MethodInfo to finally get G<Foo>.M<Bar>.
// We could also allow G<T>.M<Bar> to be created before G<Foo>.M<Bar> (BindGenParm followed by this method)
// if we wanted to but that just complicates things so these checks are designed to prevent that scenario.
if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
throw new ArgumentException(SR.Argument_NeedGenericMethodDefinition, nameof(method));
if (method.DeclaringType == null || !method.DeclaringType.IsGenericTypeDefinition)
throw new ArgumentException(SR.Argument_MethodNeedGenericDeclaringType, nameof(method));
if (type.GetGenericTypeDefinition() != method.DeclaringType)
throw new ArgumentException(SR.Argument_InvalidMethodDeclaringType, nameof(type));
// The following converts from Type or TypeBuilder of G<T> to TypeBuilderInstantiation G<T>. These types
// both logically represent the same thing. The runtime displays a similar convention by having
// G<M>.M() be encoded by a typeSpec whose parent is the typeDef for G<M> and whose instantiation is also G<M>.
if (type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
if (type is not TypeBuilderInstantiation typeBuilderInstantiation)
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
return MethodOnTypeBuilderInstantiation.GetMethod(method, typeBuilderInstantiation);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern",
Justification = "MakeGenericType is only called on a TypeBuilder which is not subject to trimming")]
public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor)
{
if (type is not TypeBuilder && type is not TypeBuilderInstantiation)
throw new ArgumentException(SR.Argument_MustBeTypeBuilder, nameof(type));
if (!constructor.DeclaringType!.IsGenericTypeDefinition)
throw new ArgumentException(SR.Argument_ConstructorNeedGenericDeclaringType, nameof(constructor));
if (type.GetGenericTypeDefinition() != constructor.DeclaringType)
throw new ArgumentException(SR.Argument_InvalidConstructorDeclaringType, nameof(type));
// TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
if (type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
if (type is not TypeBuilderInstantiation typeBuilderInstantiation)
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, typeBuilderInstantiation);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern",
Justification = "MakeGenericType is only called on a TypeBuilder which is not subject to trimming")]
public static FieldInfo GetField(Type type, FieldInfo field)
{
if (type is not TypeBuilder and not TypeBuilderInstantiation)
throw new ArgumentException(SR.Argument_MustBeTypeBuilder, nameof(type));
if (!field.DeclaringType!.IsGenericTypeDefinition)
throw new ArgumentException(SR.Argument_FieldNeedGenericDeclaringType, nameof(field));
if (type.GetGenericTypeDefinition() != field.DeclaringType)
throw new ArgumentException(SR.Argument_InvalidFieldDeclaringType, nameof(type));
// TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
if (type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
if (type is not TypeBuilderInstantiation typeBuilderInstantiation)
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
return FieldOnTypeBuilderInstantiation.GetField(field, typeBuilderInstantiation);
}
#endregion
#region Private Static FCalls
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetParentType")]
private static partial void SetParentType(QCallModule module, int tdTypeDef, int tkParent);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_AddInterfaceImpl")]
private static partial void AddInterfaceImpl(QCallModule module, int tdTypeDef, int tkInterface);
#endregion
#region Internal Static FCalls
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineMethod", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int DefineMethod(QCallModule module, int tkParent, string name, byte[] signature, int sigLength,
MethodAttributes attributes);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineMethodSpec")]
internal static partial int DefineMethodSpec(QCallModule module, int tkParent, byte[] signature, int sigLength);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineField", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int DefineField(QCallModule module, int tkParent, string name, byte[] signature, int sigLength,
FieldAttributes attributes);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetMethodIL")]
private static partial void SetMethodIL(QCallModule module, int tk, [MarshalAs(UnmanagedType.Bool)] bool isInitLocals,
byte[]? body, int bodyLength,
byte[] LocalSig, int sigLength,
int maxStackSize,
ExceptionHandler[]? exceptions, int numExceptions,
int[]? tokenFixups, int numTokenFixups);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineCustomAttribute")]
private static partial void DefineCustomAttribute(QCallModule module, int tkAssociate, int tkConstructor,
byte[]? attr, int attrLength);
internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor,
byte[]? attr)
{
byte[]? localAttr = null;
if (attr != null)
{
localAttr = new byte[attr.Length];
Buffer.BlockCopy(attr, 0, localAttr, 0, attr.Length);
}
DefineCustomAttribute(new QCallModule(ref module), tkAssociate, tkConstructor,
localAttr, (localAttr != null) ? localAttr.Length : 0);
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineProperty", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int DefineProperty(QCallModule module, int tkParent, string name, PropertyAttributes attributes,
byte[] signature, int sigLength);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineEvent", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int DefineEvent(QCallModule module, int tkParent, string name, EventAttributes attributes, int tkEventType);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineMethodSemantics")]
internal static partial void DefineMethodSemantics(QCallModule module, int tkAssociation,
MethodSemanticsAttributes semantics, int tkMethod);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineMethodImpl")]
internal static partial void DefineMethodImpl(QCallModule module, int tkType, int tkBody, int tkDecl);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetMethodImpl")]
internal static partial void SetMethodImpl(QCallModule module, int tkMethod, MethodImplAttributes MethodImplAttributes);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetParamInfo", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int SetParamInfo(QCallModule module, int tkMethod, int iSequence,
ParameterAttributes iParamAttributes, string? strParamName);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_GetTokenFromSig")]
internal static partial int GetTokenFromSig(QCallModule module, byte[] signature, int sigLength);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetFieldLayoutOffset")]
internal static partial void SetFieldLayoutOffset(QCallModule module, int fdToken, int iOffset);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetClassLayout")]
internal static partial void SetClassLayout(QCallModule module, int tk, PackingSize iPackingSize, int iTypeSize);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetConstantValue")]
private static unsafe partial void SetConstantValue(QCallModule module, int tk, int corType, void* pValue);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_SetPInvokeData", StringMarshalling = StringMarshalling.Utf16)]
private static partial void SetPInvokeData(QCallModule module, string DllName, string name, int token, int linkFlags);
#endregion
#region Internal\Private Static Members
internal static bool IsTypeEqual(Type? t1, Type? t2)
{
// Maybe we are lucky that they are equal in the first place
if (t1 == t2)
return true;
TypeBuilder? tb1 = null;
TypeBuilder? tb2 = null;
Type? runtimeType1;
Type? runtimeType2;
// set up the runtimeType and TypeBuilder type corresponding to t1 and t2
if (t1 is TypeBuilder)
{
tb1 = (TypeBuilder)t1;
// This will be null if it is not baked.
runtimeType1 = tb1.m_bakedRuntimeType;
}
else
{
runtimeType1 = t1;
}
if (t2 is TypeBuilder)
{
tb2 = (TypeBuilder)t2;
// This will be null if it is not baked.
runtimeType2 = tb2.m_bakedRuntimeType;
}
else
{
runtimeType2 = t2;
}
// If the type builder view is equal then it is equal
if (tb1 != null && tb2 != null && ReferenceEquals(tb1, tb2))
return true;
// if the runtimetype view is eqaul than it is equal
if (runtimeType1 != null && runtimeType2 != null && runtimeType1 == runtimeType2)
return true;
return false;
}
internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, object? value)
{
// This is a helper function that is used by ParameterBuilder, PropertyBuilder,
// and FieldBuilder to validate a default value and save it in the meta-data.
if (value != null)
{
Type type = value.GetType();
// We should allow setting a constant value on a ByRef parameter
if (destType.IsByRef)
destType = destType.GetElementType()!;
// Convert nullable types to their underlying type.
// This is necessary for nullable enum types to pass the IsEnum check that's coming next.
destType = Nullable.GetUnderlyingType(destType) ?? destType;
if (destType.IsEnum)
{
// | | UnderlyingSystemType | Enum.GetUnderlyingType() | IsEnum
// |-----------------------------------|---------------------------|---------------------------|---------
// | runtime Enum Type | self | underlying type of enum | TRUE
// | EnumBuilder | underlying type of enum | underlying type of enum* | TRUE
// | TypeBuilder of enum types** | underlying type of enum | Exception | TRUE
// | TypeBuilder of enum types (baked) | runtime enum type | Exception | TRUE
// *: the behavior of Enum.GetUnderlyingType(EnumBuilder) might change in the future
// so let's not depend on it.
// **: created with System.Enum as the parent type.
// The above behaviors might not be the most consistent but we have to live with them.
Type? underlyingType;
if (destType is EnumBuilder enumBldr)
{
underlyingType = enumBldr.GetEnumUnderlyingType();
// The constant value supplied should match either the baked enum type or its underlying type
// we don't need to compare it with the EnumBuilder itself because you can never have an object of that type
if (type != enumBldr.m_typeBuilder.m_bakedRuntimeType && type != underlyingType)
throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
else if (destType is TypeBuilder typeBldr)
{
underlyingType = typeBldr.m_enumUnderlyingType;
// The constant value supplied should match either the baked enum type or its underlying type
// typeBldr.m_enumUnderlyingType is null if the user hasn't created a "value__" field on the enum
if (underlyingType == null || (type != typeBldr.UnderlyingSystemType && type != underlyingType))
throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
else // must be a runtime Enum Type
{
Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");
underlyingType = Enum.GetUnderlyingType(destType);
// The constant value supplied should match either the enum itself or its underlying type
if (type != destType && type != underlyingType)
throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
type = underlyingType;
}
else
{
// Note that it is non CLS compliant if destType != type. But RefEmit never guarantees CLS-Compliance.
if (!destType.IsAssignableFrom(type))
throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
CorElementType corType = RuntimeTypeHandle.GetCorElementType((RuntimeType)type);
switch (corType)
{
case CorElementType.ELEMENT_TYPE_I1:
case CorElementType.ELEMENT_TYPE_U1:
case CorElementType.ELEMENT_TYPE_BOOLEAN:
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_CHAR:
case CorElementType.ELEMENT_TYPE_I4:
case CorElementType.ELEMENT_TYPE_U4:
case CorElementType.ELEMENT_TYPE_R4:
case CorElementType.ELEMENT_TYPE_I8:
case CorElementType.ELEMENT_TYPE_U8:
case CorElementType.ELEMENT_TYPE_R8:
fixed (byte* pData = &value.GetRawData())
SetConstantValue(new QCallModule(ref module), tk, (int)corType, pData);
break;
default:
if (type == typeof(string))
{
fixed (char* pString = (string)value)
SetConstantValue(new QCallModule(ref module), tk, (int)CorElementType.ELEMENT_TYPE_STRING, pString);
}
else if (type == typeof(DateTime))
{
// date is a I8 representation
long ticks = ((DateTime)value).Ticks;
SetConstantValue(new QCallModule(ref module), tk, (int)CorElementType.ELEMENT_TYPE_I8, &ticks);
}
else
{
throw new ArgumentException(SR.Format(SR.Argument_ConstantNotSupported, type));
}
break;
}
}
else
{
// A null default value in metadata is permissible even for non-nullable value types.
// (See ECMA-335 II.15.4.1.4 "The .param directive" and II.22.9 "Constant" for details.)
// This is how the Roslyn compilers generally encode `default(TValueType)` default values.
SetConstantValue(new QCallModule(ref module), tk, (int)CorElementType.ELEMENT_TYPE_CLASS, null);
}
}
#endregion
#region Private Data Members
private List<CustAttr>? m_ca;
private int m_tdType;
private readonly ModuleBuilder m_module;
private readonly string? m_strName;
private readonly string? m_strNameSpace;
private string? m_strFullQualName;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
private Type? m_typeParent;
private List<Type>? m_typeInterfaces;
private readonly TypeAttributes m_iAttr;
private GenericParameterAttributes m_genParamAttributes;
internal List<MethodBuilder>? m_listMethods;
internal int m_lastTokenizedMethod;
private int m_constructorCount;
private readonly int m_iTypeSize;
private readonly PackingSize m_iPackingSize;
private readonly TypeBuilder? m_DeclaringType;
// We cannot store this on EnumBuilder because users can define enum types manually using TypeBuilder.
private Type? m_enumUnderlyingType;
internal bool m_isHiddenGlobalType;
private bool m_hasBeenCreated;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
private RuntimeType m_bakedRuntimeType = null!;
private readonly int m_genParamPos;
private GenericTypeParameterBuilder[]? m_inst;
private readonly bool m_bIsGenParam;
private readonly MethodBuilder? m_declMeth;
private readonly TypeBuilder? m_genTypeDef;
#endregion
#region Constructor
// ctor for the global (module) type
internal TypeBuilder(ModuleBuilder module)
{
m_tdType = ((int)MetadataTokenType.TypeDef);
m_isHiddenGlobalType = true;
m_module = module;
m_listMethods = new List<MethodBuilder>();
// No token has been created so let's initialize it to -1
// The first time we call MethodBuilder.GetToken this will incremented.
m_lastTokenizedMethod = -1;
}
// ctor for generic method parameter
internal TypeBuilder(string szName, int genParamPos, MethodBuilder declMeth)
{
m_strName = szName;
m_genParamPos = genParamPos;
m_bIsGenParam = true;
m_typeInterfaces = new List<Type>();
Debug.Assert(declMeth != null);
m_declMeth = declMeth;
m_DeclaringType = m_declMeth.GetTypeBuilder();
m_module = declMeth.GetModuleBuilder();
}
// ctor for generic type parameter
private TypeBuilder(string szName, int genParamPos, TypeBuilder declType)
{
m_strName = szName;
m_genParamPos = genParamPos;
m_bIsGenParam = true;
m_typeInterfaces = new List<Type>();
Debug.Assert(declType != null);
m_DeclaringType = declType;
m_module = declType.GetModuleBuilder();
}
internal TypeBuilder(
string fullname, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces, ModuleBuilder module,
PackingSize iPackingSize, int iTypeSize, TypeBuilder? enclosingType)
{
ArgumentException.ThrowIfNullOrEmpty(fullname);
if (fullname[0] == '\0')
throw new ArgumentException(SR.Argument_IllegalName, nameof(fullname));
if (fullname.Length > 1023)
throw new ArgumentException(SR.Argument_TypeNameTooLong, nameof(fullname));
int i;
m_module = module;
m_DeclaringType = enclosingType;
AssemblyBuilder containingAssem = m_module.ContainingAssemblyBuilder;
// cannot have two types within the same assembly of the same name
containingAssem.CheckTypeNameConflict(fullname, enclosingType);
if (enclosingType != null)
{
// Nested Type should have nested attribute set.
// If we are renumbering TypeAttributes' bit, we need to change the logic here.
if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) || ((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
throw new ArgumentException(SR.Argument_BadNestedTypeFlags, nameof(attr));
}
int[]? interfaceTokens = null;
if (interfaces != null)
{
for (i = 0; i < interfaces.Length; i++)
{
// cannot contain null in the interface list
ArgumentNullException.ThrowIfNull(interfaces[i], nameof(interfaces));
}
interfaceTokens = new int[interfaces.Length + 1];
for (i = 0; i < interfaces.Length; i++)
{
interfaceTokens[i] = m_module.GetTypeTokenInternal(interfaces[i]);
}
}
int iLast = fullname.LastIndexOf('.');
if (iLast <= 0)
{
// no name space
m_strNameSpace = string.Empty;
m_strName = fullname;
}
else
{
// split the name space
m_strNameSpace = fullname.Substring(0, iLast);
m_strName = fullname.Substring(iLast + 1);
}
VerifyTypeAttributes(attr);
m_iAttr = attr;
SetParent(parent);
m_listMethods = new List<MethodBuilder>();
m_lastTokenizedMethod = -1;
SetInterfaces(interfaces);
int tkParent = 0;
if (m_typeParent != null)
tkParent = m_module.GetTypeTokenInternal(m_typeParent);
int tkEnclosingType = 0;
if (enclosingType != null)
{
tkEnclosingType = enclosingType.m_tdType;
}
m_tdType = DefineType(new QCallModule(ref module),
fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens!);
m_iPackingSize = iPackingSize;
m_iTypeSize = iTypeSize;
if ((m_iPackingSize != 0) || (m_iTypeSize != 0))
SetClassLayout(new QCallModule(ref module), m_tdType, m_iPackingSize, m_iTypeSize);
m_module.AddType(FullName!, this);
}
#endregion
#region Private Members
private FieldBuilder DefineDataHelper(string name, byte[]? data, int size, FieldAttributes attributes)
{
string strValueClassName;
TypeBuilder? valueClassType;
FieldBuilder fdBuilder;
TypeAttributes typeAttributes;
ArgumentException.ThrowIfNullOrEmpty(name);
if (size <= 0 || size >= 0x003f0000)
throw new ArgumentException(SR.Argument_BadSizeForData);
ThrowIfCreated();
// form the value class name
strValueClassName = $"$ArrayType${size}";
// Is this already defined in this module?
Type? temp = m_module.FindTypeBuilderWithName(strValueClassName, false);
valueClassType = temp as TypeBuilder;
if (valueClassType == null)
{
typeAttributes = TypeAttributes.Public | TypeAttributes.ExplicitLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass;
// Define the backing value class
valueClassType = m_module.DefineType(strValueClassName, typeAttributes, typeof(System.ValueType), PackingSize.Size1, size);
valueClassType.CreateType();
}
fdBuilder = DefineField(name, valueClassType, attributes | FieldAttributes.Static);
// now we need to set the RVA
fdBuilder.SetData(data, size);
return fdBuilder;
}
private void VerifyTypeAttributes(TypeAttributes attr)
{
// Verify attr consistency for Nesting or otherwise.
if (DeclaringType == null)
{
// Not a nested class.
if (((attr & TypeAttributes.VisibilityMask) != TypeAttributes.NotPublic) && ((attr & TypeAttributes.VisibilityMask) != TypeAttributes.Public))
{
throw new ArgumentException(SR.Argument_BadTypeAttrNestedVisibilityOnNonNestedType);
}
}
else
{
// Nested class.
if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic) || ((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public))
{
throw new ArgumentException(SR.Argument_BadTypeAttrNonNestedVisibilityNestedType);
}
}
// Verify that the layout mask is valid.
if (((attr & TypeAttributes.LayoutMask) != TypeAttributes.AutoLayout) && ((attr & TypeAttributes.LayoutMask) != TypeAttributes.SequentialLayout) && ((attr & TypeAttributes.LayoutMask) != TypeAttributes.ExplicitLayout))
{
throw new ArgumentException(SR.Argument_BadTypeAttrInvalidLayout);
}
// Check if the user attempted to set any reserved bits.
if ((attr & TypeAttributes.ReservedMask) != 0)
{
throw new ArgumentException(SR.Argument_BadTypeAttrReservedBitsSet);
}
}
public bool IsCreated()
{
return m_hasBeenCreated;
}
#endregion
#region FCalls
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineType", StringMarshalling = StringMarshalling.Utf16)]
private static partial int DefineType(QCallModule module,
string fullname, int tkParent, TypeAttributes attributes, int tkEnclosingType, int[] interfaceTokens);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_DefineGenericParam", StringMarshalling = StringMarshalling.Utf16)]
private static partial int DefineGenericParam(QCallModule module,
string name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeBuilder_TermCreateClass")]
private static partial void TermCreateClass(QCallModule module, int tk, ObjectHandleOnStack type);
#endregion
#region Internal Methods
internal void ThrowIfCreated()
{
if (IsCreated())
throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated);
}
internal object SyncRoot => m_module.SyncRoot;
internal ModuleBuilder GetModuleBuilder()
{
return m_module;
}
internal RuntimeType BakedRuntimeType => m_bakedRuntimeType;
internal void SetGenParamAttributes(GenericParameterAttributes genericParameterAttributes)
{
m_genParamAttributes = genericParameterAttributes;
}
internal void SetGenParamCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
CustAttr ca = new CustAttr(con, binaryAttribute);
lock (SyncRoot)
{
SetGenParamCustomAttributeNoLock(ca);
}
}
internal void SetGenParamCustomAttribute(CustomAttributeBuilder customBuilder)
{
CustAttr ca = new CustAttr(customBuilder);
lock (SyncRoot)
{
SetGenParamCustomAttributeNoLock(ca);
}
}
private void SetGenParamCustomAttributeNoLock(CustAttr ca)
{
m_ca ??= new List<TypeBuilder.CustAttr>();
m_ca.Add(ca);
}
#endregion
#region Object Overrides
public override string ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!;
}
#endregion
#region MemberInfo Overrides
public override Type? DeclaringType => m_DeclaringType;
public override Type? ReflectedType => m_DeclaringType;
public override string Name =>
// one of the constructors allows this to be null but it is only used internally without accessing Name
m_strName!;
public override Module Module => GetModuleBuilder();
public override bool IsByRefLike => false;
public override int MetadataToken => m_tdType;
#endregion
#region Type Overrides
public override Guid GUID
{
get
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GUID;
}
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
public override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target,
object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
public override Assembly Assembly => m_module.Assembly;
public override RuntimeTypeHandle TypeHandle => throw new NotSupportedException(SR.NotSupported_DynamicModule);
public override string? FullName => m_strFullQualName ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
public override string? Namespace => m_strNameSpace;
public override string? AssemblyQualifiedName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
public override Type? BaseType => m_typeParent;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder,
CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetConstructors(bindingAttr);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder,
CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
if (types == null)
{
return m_bakedRuntimeType.GetMethod(name, bindingAttr);
}
else
{
return m_bakedRuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
}
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetMethods(bindingAttr);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetField(name, bindingAttr);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetFields(bindingAttr);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
public override Type? GetInterface(string name, bool ignoreCase)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetInterface(name, ignoreCase);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
public override Type[] GetInterfaces()
{
if (m_bakedRuntimeType != null)
{
return m_bakedRuntimeType.GetInterfaces();
}
if (m_typeInterfaces == null)
{
return Type.EmptyTypes;
}
return m_typeInterfaces.ToArray();
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)]
public override EventInfo? GetEvent(string name, BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetEvent(name, bindingAttr);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)]
public override EventInfo[] GetEvents()
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetEvents();
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder,
Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetProperties(bindingAttr);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)]
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetNestedTypes(bindingAttr);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)]
public override Type? GetNestedType(string name, BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetNestedType(name, bindingAttr);
}
[DynamicallyAccessedMembers(GetAllMembers)]
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetMember(name, type, bindingAttr);
}
public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetInterfaceMap(interfaceType);
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)]
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetEvents(bindingAttr);
}
[DynamicallyAccessedMembers(GetAllMembers)]
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetMembers(bindingAttr);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "The GetInterfaces technically requires all interfaces to be preserved" +
"But in this case it acts only on TypeBuilder which is never trimmed (as it's runtime created).")]
public override bool IsAssignableFrom([NotNullWhen(true)] Type? c)
{
if (IsTypeEqual(c, this))
return true;
Type? fromRuntimeType;
TypeBuilder? fromTypeBuilder = c as TypeBuilder;
if (fromTypeBuilder != null)
fromRuntimeType = fromTypeBuilder.m_bakedRuntimeType;
else
fromRuntimeType = c;
if (fromRuntimeType != null && fromRuntimeType is RuntimeType)
{
// fromType is baked. So if this type is not baked, it cannot be assignable to!
if (m_bakedRuntimeType == null)
return false;
// since toType is also baked, delegate to the base
return m_bakedRuntimeType.IsAssignableFrom(fromRuntimeType);
}
// So if c is not a runtimeType nor TypeBuilder. We don't know how to deal with it.
// return false then.
if (fromTypeBuilder == null)
return false;
// If fromTypeBuilder is a subclass of this class, then c can be cast to this type.
if (fromTypeBuilder.IsSubclassOf(this))
return true;
if (!IsInterface)
return false;
// now is This type a base type on one of the interface impl?
Type[] interfaces = fromTypeBuilder.GetInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
// unfortunately, IsSubclassOf does not cover the case when they are the same type.
if (IsTypeEqual(interfaces[i], this))
return true;
if (interfaces[i].IsSubclassOf(this))
return true;
}
return false;
}
protected override TypeAttributes GetAttributeFlagsImpl()
{
return m_iAttr;
}
public override bool IsTypeDefinition => true;
public override bool IsSZArray => false;
protected override bool IsArrayImpl()
{
return false;
}
protected override bool IsByRefImpl()
{