This repository was archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathDispatchProxyGenerator.cs
More file actions
936 lines (805 loc) · 41.6 KB
/
Copy pathDispatchProxyGenerator.cs
File metadata and controls
936 lines (805 loc) · 41.6 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.ExceptionServices;
using System.Threading;
namespace System.Reflection
{
// Helper class to handle the IL EMIT for the generation of proxies.
// Much of this code was taken directly from the Silverlight proxy generation.
// Differences between this and the Silverlight version are:
// 1. This version is based on DispatchProxy from NET Native and CoreCLR, not RealProxy in Silverlight ServiceModel.
// There are several notable differences between them.
// 2. Both DispatchProxy and RealProxy permit the caller to ask for a proxy specifying a pair of types:
// the interface type to implement, and a base type. But they behave slightly differently:
// - RealProxy generates a proxy type that derives from Object and *implements" all the base type's
// interfaces plus all the interface type's interfaces.
// - DispatchProxy generates a proxy type that *derives* from the base type and implements all
// the interface type's interfaces. This is true for both the CLR version in NET Native and this
// version for CoreCLR.
// 3. DispatchProxy and RealProxy use different type hierarchies for the generated proxies:
// - RealProxy type hierarchy is:
// proxyType : proxyBaseType : object
// Presumably the 'proxyBaseType' in the middle is to allow it to implement the base type's interfaces
// explicitly, preventing collision for same name methods on the base and interface types.
// - DispatchProxy hierarchy is:
// proxyType : baseType (where baseType : DispatchProxy)
// The generated DispatchProxy proxy type does not need to generate implementation methods
// for the base type's interfaces, because the base type already must have implemented them.
// 4. RealProxy required a proxy instance to hold a backpointer to the RealProxy instance to mirror
// the .NET Remoting design that required the proxy and RealProxy to be separate instances.
// But the DispatchProxy design encourages the proxy type to *be* an DispatchProxy. Therefore,
// the proxy's 'this' becomes the equivalent of RealProxy's backpointer to RealProxy, so we were
// able to remove an extraneous field and ctor arg from the DispatchProxy proxies.
//
internal static class DispatchProxyGenerator
{
// Generated proxies have a private Action field that all generated methods
// invoke. It is the first field in the class and the first ctor parameter.
private const int InvokeActionFieldAndCtorParameterIndex = 0;
// Proxies are requested for a pair of types: base type and interface type.
// The generated proxy will subclass the given base type and implement the interface type.
// We maintain a cache keyed by 'base type' containing a dictionary keyed by interface type,
// containing the generated proxy type for that pair. There are likely to be few (maybe only 1)
// base type in use for many interface types.
// Note: this differs from Silverlight's RealProxy implementation which keys strictly off the
// interface type. But this does not allow the same interface type to be used with more than a
// single base type. The implementation here permits multiple interface types to be used with
// multiple base types, and the generated proxy types will be unique.
// This cache of generated types grows unbounded, one element per unique T/ProxyT pair.
// This approach is used to prevent regenerating identical proxy types for identical T/Proxy pairs,
// which would ultimately be a more expensive leak.
// Proxy instances are not cached. Their lifetime is entirely owned by the caller of DispatchProxy.Create.
private static readonly Dictionary<Type, Dictionary<Type, Type>> s_baseTypeAndInterfaceToGeneratedProxyType = new Dictionary<Type, Dictionary<Type, Type>>();
private static readonly ProxyAssembly s_proxyAssembly = new ProxyAssembly();
private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(DispatchProxy).GetTypeInfo().GetDeclaredMethod("Invoke")!;
// Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType'
internal static object CreateProxyInstance(Type baseType, Type interfaceType)
{
Debug.Assert(baseType != null);
Debug.Assert(interfaceType != null);
Type proxiedType = GetProxyType(baseType!, interfaceType!);
return Activator.CreateInstance(proxiedType, (Action<object[]>)DispatchProxyGenerator.Invoke)!;
}
private static Type GetProxyType(Type baseType, Type interfaceType)
{
lock (s_baseTypeAndInterfaceToGeneratedProxyType)
{
if (!s_baseTypeAndInterfaceToGeneratedProxyType.TryGetValue(baseType, out Dictionary<Type, Type>? interfaceToProxy))
{
interfaceToProxy = new Dictionary<Type, Type>();
s_baseTypeAndInterfaceToGeneratedProxyType[baseType] = interfaceToProxy;
}
if (!interfaceToProxy.TryGetValue(interfaceType, out Type? generatedProxy))
{
generatedProxy = GenerateProxyType(baseType, interfaceType);
interfaceToProxy[interfaceType] = generatedProxy;
}
return generatedProxy;
}
}
// Unconditionally generates a new proxy type derived from 'baseType' and implements 'interfaceType'
private static Type GenerateProxyType(Type baseType, Type interfaceType)
{
// Parameter validation is deferred until the point we need to create the proxy.
// This prevents unnecessary overhead revalidating cached proxy types.
TypeInfo baseTypeInfo = baseType.GetTypeInfo();
// The interface type must be an interface, not a class
if (!interfaceType.GetTypeInfo().IsInterface)
{
// "T" is the generic parameter seen via the public contract
throw new ArgumentException(SR.Format(SR.InterfaceType_Must_Be_Interface, interfaceType.FullName), "T");
}
// The base type cannot be sealed because the proxy needs to subclass it.
if (baseTypeInfo.IsSealed)
{
// "TProxy" is the generic parameter seen via the public contract
throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Sealed, baseTypeInfo.FullName), "TProxy");
}
// The base type cannot be abstract
if (baseTypeInfo.IsAbstract)
{
throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Abstract, baseType.FullName), "TProxy");
}
// The base type must have a public default ctor
if (!baseTypeInfo.DeclaredConstructors.Any(c => c.IsPublic && c.GetParameters().Length == 0))
{
throw new ArgumentException(SR.Format(SR.BaseType_Must_Have_Default_Ctor, baseType.FullName), "TProxy");
}
// Create a type that derives from 'baseType' provided by caller
ProxyBuilder pb = s_proxyAssembly.CreateProxy("generatedProxy", baseType);
foreach (Type t in interfaceType.GetTypeInfo().ImplementedInterfaces)
pb.AddInterfaceImpl(t);
pb.AddInterfaceImpl(interfaceType);
Type generatedProxyType = pb.CreateType();
return generatedProxyType;
}
// All generated proxy methods call this static helper method to dispatch.
// Its job is to unpack the arguments and the 'this' instance and to dispatch directly
// to the (abstract) DispatchProxy.Invoke() method.
private static void Invoke(object?[] args)
{
PackedArgs packed = new PackedArgs(args);
MethodBase method = s_proxyAssembly.ResolveMethodToken(packed.DeclaringType, packed.MethodToken);
if (method.IsGenericMethodDefinition)
method = ((MethodInfo)method).MakeGenericMethod(packed.GenericTypes!);
// Call (protected method) DispatchProxy.Invoke()
try
{
Debug.Assert(s_dispatchProxyInvokeMethod != null);
object? returnValue = s_dispatchProxyInvokeMethod!.Invoke(packed.DispatchProxy,
new object?[] { method, packed.Args });
packed.ReturnValue = returnValue;
}
catch (TargetInvocationException tie)
{
Debug.Assert(tie.InnerException != null);
ExceptionDispatchInfo.Capture(tie.InnerException).Throw();
}
}
private class PackedArgs
{
internal const int DispatchProxyPosition = 0;
internal const int DeclaringTypePosition = 1;
internal const int MethodTokenPosition = 2;
internal const int ArgsPosition = 3;
internal const int GenericTypesPosition = 4;
internal const int ReturnValuePosition = 5;
internal static readonly Type[] PackedTypes = new Type[] { typeof(object), typeof(Type), typeof(int), typeof(object[]), typeof(Type[]), typeof(object) };
private readonly object?[] _args;
internal PackedArgs() : this(new object[PackedTypes.Length]) { }
internal PackedArgs(object?[] args) { _args = args; }
internal DispatchProxy? DispatchProxy { get { return (DispatchProxy?)_args[DispatchProxyPosition]; } }
internal Type? DeclaringType { get { return (Type?)_args[DeclaringTypePosition]; } }
internal int MethodToken { get { return (int)_args[MethodTokenPosition]!; } }
internal object[]? Args { get { return (object[]?)_args[ArgsPosition]; } }
internal Type[]? GenericTypes { get { return (Type[]?)_args[GenericTypesPosition]; } }
internal object? ReturnValue { /*get { return args[ReturnValuePosition]; }*/ set { _args[ReturnValuePosition] = value; } }
}
private class ProxyAssembly
{
private readonly AssemblyBuilder _ab;
private readonly ModuleBuilder _mb;
private int _typeId = 0;
// Maintain a MethodBase-->int, int-->MethodBase mapping to permit generated code
// to pass methods by token
private readonly Dictionary<MethodBase, int> _methodToToken = new Dictionary<MethodBase, int>();
private readonly List<MethodBase> _methodsByToken = new List<MethodBase>();
private readonly HashSet<string?> _ignoresAccessAssemblyNames = new HashSet<string?>();
private ConstructorInfo? _ignoresAccessChecksToAttributeConstructor;
public ProxyAssembly()
{
_ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ProxyBuilder"), AssemblyBuilderAccess.Run);
_mb = _ab.DefineDynamicModule("testmod");
}
// Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute.
// This attribute is both defined and referenced in the dynamic assembly to
// allow access to internal types in other assemblies.
internal ConstructorInfo IgnoresAccessChecksAttributeConstructor
{
get
{
if (_ignoresAccessChecksToAttributeConstructor == null)
{
_ignoresAccessChecksToAttributeConstructor = IgnoreAccessChecksToAttributeBuilder.AddToModule(_mb);
}
return _ignoresAccessChecksToAttributeConstructor;
}
}
public ProxyBuilder CreateProxy(string name, Type proxyBaseType)
{
int nextId = Interlocked.Increment(ref _typeId);
TypeBuilder tb = _mb.DefineType(name + "_" + nextId, TypeAttributes.Public, proxyBaseType);
return new ProxyBuilder(this, tb, proxyBaseType);
}
// Generates an instance of the IgnoresAccessChecksToAttribute to
// identify the given assembly as one which contains internal types
// the dynamic assembly will need to reference.
internal void GenerateInstanceOfIgnoresAccessChecksToAttribute(string assemblyName)
{
// Add this assembly level attribute:
// [assembly: System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute(assemblyName)]
ConstructorInfo attributeConstructor = IgnoresAccessChecksAttributeConstructor;
CustomAttributeBuilder customAttributeBuilder =
new CustomAttributeBuilder(attributeConstructor, new object[] { assemblyName });
_ab.SetCustomAttribute(customAttributeBuilder);
}
// Ensures the type we will reference from the dynamic assembly
// is visible. Non-public types need to emit an attribute that
// allows access from the dynamic assembly.
internal void EnsureTypeIsVisible(Type type)
{
TypeInfo typeInfo = type.GetTypeInfo();
if (!typeInfo.IsVisible)
{
string assemblyName = typeInfo.Assembly.GetName().Name!;
if (!_ignoresAccessAssemblyNames.Contains(assemblyName))
{
GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyName);
_ignoresAccessAssemblyNames.Add(assemblyName);
}
}
}
internal void GetTokenForMethod(MethodBase method, out Type type, out int token)
{
Debug.Assert(method.DeclaringType != null);
type = method.DeclaringType!;
token = 0;
if (!_methodToToken.TryGetValue(method, out token))
{
_methodsByToken.Add(method);
token = _methodsByToken.Count - 1;
_methodToToken[method] = token;
}
}
internal MethodBase ResolveMethodToken(Type? type, int token)
{
Debug.Assert(token >= 0 && token < _methodsByToken.Count);
return _methodsByToken[token];
}
}
private class ProxyBuilder
{
private static readonly MethodInfo s_delegateInvoke = typeof(Action<object[]>).GetTypeInfo().GetDeclaredMethod("Invoke")!;
private readonly ProxyAssembly _assembly;
private readonly TypeBuilder _tb;
private readonly Type _proxyBaseType;
private readonly List<FieldBuilder> _fields;
internal ProxyBuilder(ProxyAssembly assembly, TypeBuilder tb, Type proxyBaseType)
{
_assembly = assembly;
_tb = tb;
_proxyBaseType = proxyBaseType;
_fields = new List<FieldBuilder>();
_fields.Add(tb.DefineField("invoke", typeof(Action<object[]>), FieldAttributes.Private));
}
private void Complete()
{
Type[] args = new Type[_fields.Count];
for (int i = 0; i < args.Length; i++)
{
args[i] = _fields[i].FieldType;
}
ConstructorBuilder cb = _tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, args);
ILGenerator il = cb.GetILGenerator();
// chained ctor call
ConstructorInfo? baseCtor = _proxyBaseType.GetTypeInfo().DeclaredConstructors.SingleOrDefault(c => c.IsPublic && c.GetParameters().Length == 0);
Debug.Assert(baseCtor != null);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseCtor!);
// store all the fields
for (int i = 0; i < args.Length; i++)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg, i + 1);
il.Emit(OpCodes.Stfld, _fields[i]);
}
il.Emit(OpCodes.Ret);
}
internal Type CreateType()
{
this.Complete();
return _tb.CreateTypeInfo()!.AsType();
}
internal void AddInterfaceImpl(Type iface)
{
// If necessary, generate an attribute to permit visibility
// to internal types.
_assembly.EnsureTypeIsVisible(iface);
_tb.AddInterfaceImplementation(iface);
// AccessorMethods -> Metadata mappings.
var propertyMap = new Dictionary<MethodInfo, PropertyAccessorInfo>(MethodInfoEqualityComparer.Instance);
foreach (PropertyInfo pi in iface.GetRuntimeProperties())
{
var ai = new PropertyAccessorInfo(pi.GetMethod, pi.SetMethod);
if (pi.GetMethod != null)
propertyMap[pi.GetMethod] = ai;
if (pi.SetMethod != null)
propertyMap[pi.SetMethod] = ai;
}
var eventMap = new Dictionary<MethodInfo, EventAccessorInfo>(MethodInfoEqualityComparer.Instance);
foreach (EventInfo ei in iface.GetRuntimeEvents())
{
var ai = new EventAccessorInfo(ei.AddMethod, ei.RemoveMethod, ei.RaiseMethod);
if (ei.AddMethod != null)
eventMap[ei.AddMethod] = ai;
if (ei.RemoveMethod != null)
eventMap[ei.RemoveMethod] = ai;
if (ei.RaiseMethod != null)
eventMap[ei.RaiseMethod] = ai;
}
foreach (MethodInfo mi in iface.GetRuntimeMethods())
{
// Skip regular/non-virtual instance methods, static methods, and methods that cannot be overriden
// ("methods that cannot be overriden" includes default implementation of other interface methods).
if (!mi.IsVirtual || mi.IsFinal)
continue;
MethodBuilder mdb = AddMethodImpl(mi);
if (propertyMap.TryGetValue(mi, out PropertyAccessorInfo? associatedProperty))
{
if (MethodInfoEqualityComparer.Instance.Equals(associatedProperty.InterfaceGetMethod, mi))
associatedProperty.GetMethodBuilder = mdb;
else
associatedProperty.SetMethodBuilder = mdb;
}
if (eventMap.TryGetValue(mi, out EventAccessorInfo? associatedEvent))
{
if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceAddMethod, mi))
associatedEvent.AddMethodBuilder = mdb;
else if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceRemoveMethod, mi))
associatedEvent.RemoveMethodBuilder = mdb;
else
associatedEvent.RaiseMethodBuilder = mdb;
}
}
foreach (PropertyInfo pi in iface.GetRuntimeProperties())
{
PropertyAccessorInfo ai = propertyMap[pi.GetMethod ?? pi.SetMethod!];
// If we didn't make an overriden accessor above, this was a static property, non-virtual property,
// or a default implementation of a property of a different interface. In any case, we don't need
// to redeclare it.
if (ai.GetMethodBuilder == null && ai.SetMethodBuilder == null)
continue;
PropertyBuilder pb = _tb.DefineProperty(pi.Name, pi.Attributes, pi.PropertyType, pi.GetIndexParameters().Select(p => p.ParameterType).ToArray());
if (ai.GetMethodBuilder != null)
pb.SetGetMethod(ai.GetMethodBuilder);
if (ai.SetMethodBuilder != null)
pb.SetSetMethod(ai.SetMethodBuilder);
}
foreach (EventInfo ei in iface.GetRuntimeEvents())
{
EventAccessorInfo ai = eventMap[ei.AddMethod ?? ei.RemoveMethod!];
// If we didn't make an overriden accessor above, this was a static event, non-virtual event,
// or a default implementation of an event of a different interface. In any case, we don't
// need to redeclare it.
if (ai.AddMethodBuilder == null && ai.RemoveMethodBuilder == null && ai.RaiseMethodBuilder == null)
continue;
Debug.Assert(ei.EventHandlerType != null);
EventBuilder eb = _tb.DefineEvent(ei.Name, ei.Attributes, ei.EventHandlerType!);
if (ai.AddMethodBuilder != null)
eb.SetAddOnMethod(ai.AddMethodBuilder);
if (ai.RemoveMethodBuilder != null)
eb.SetRemoveOnMethod(ai.RemoveMethodBuilder);
if (ai.RaiseMethodBuilder != null)
eb.SetRaiseMethod(ai.RaiseMethodBuilder);
}
}
private MethodBuilder AddMethodImpl(MethodInfo mi)
{
ParameterInfo[] parameters = mi.GetParameters();
Type[] paramTypes = ParamTypes(parameters, false);
MethodBuilder mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes);
if (mi.ContainsGenericParameters)
{
Type[] ts = mi.GetGenericArguments();
string[] ss = new string[ts.Length];
for (int i = 0; i < ts.Length; i++)
{
ss[i] = ts[i].Name;
}
GenericTypeParameterBuilder[] genericParameters = mdb.DefineGenericParameters(ss);
for (int i = 0; i < genericParameters.Length; i++)
{
genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes);
}
}
ILGenerator il = mdb.GetILGenerator();
ParametersArray args = new ParametersArray(il, paramTypes);
// object[] args = new object[paramCount];
il.Emit(OpCodes.Nop);
GenericArray<object> argsArr = new GenericArray<object>(il, ParamTypes(parameters, true).Length);
for (int i = 0; i < parameters.Length; i++)
{
// args[i] = argi;
bool isOutRef = parameters[i].IsOut && parameters[i].ParameterType.IsByRef && !parameters[i].IsIn;
if (!isOutRef)
{
argsArr.BeginSet(i);
args.Get(i);
argsArr.EndSet(parameters[i].ParameterType);
}
}
// object[] packed = new object[PackedArgs.PackedTypes.Length];
GenericArray<object> packedArr = new GenericArray<object>(il, PackedArgs.PackedTypes.Length);
// packed[PackedArgs.DispatchProxyPosition] = this;
packedArr.BeginSet(PackedArgs.DispatchProxyPosition);
il.Emit(OpCodes.Ldarg_0);
packedArr.EndSet(typeof(DispatchProxy));
// packed[PackedArgs.DeclaringTypePosition] = typeof(iface);
MethodInfo Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) })!;
_assembly.GetTokenForMethod(mi, out Type declaringType, out int methodToken);
packedArr.BeginSet(PackedArgs.DeclaringTypePosition);
il.Emit(OpCodes.Ldtoken, declaringType);
il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
packedArr.EndSet(typeof(object));
// packed[PackedArgs.MethodTokenPosition] = iface method token;
packedArr.BeginSet(PackedArgs.MethodTokenPosition);
il.Emit(OpCodes.Ldc_I4, methodToken);
packedArr.EndSet(typeof(int));
// packed[PackedArgs.ArgsPosition] = args;
packedArr.BeginSet(PackedArgs.ArgsPosition);
argsArr.Load();
packedArr.EndSet(typeof(object[]));
// packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments();
if (mi.ContainsGenericParameters)
{
packedArr.BeginSet(PackedArgs.GenericTypesPosition);
Type[] genericTypes = mi.GetGenericArguments();
GenericArray<Type> typeArr = new GenericArray<Type>(il, genericTypes.Length);
for (int i = 0; i < genericTypes.Length; ++i)
{
typeArr.BeginSet(i);
il.Emit(OpCodes.Ldtoken, genericTypes[i]);
il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
typeArr.EndSet(typeof(Type));
}
typeArr.Load();
packedArr.EndSet(typeof(Type[]));
}
// Call static DispatchProxyHelper.Invoke(object[])
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); // delegate
packedArr.Load();
il.Emit(OpCodes.Call, s_delegateInvoke);
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType.IsByRef)
{
args.BeginSet(i);
argsArr.Get(i);
args.EndSet(i, typeof(object));
}
}
if (mi.ReturnType != typeof(void))
{
packedArr.Get(PackedArgs.ReturnValuePosition);
Convert(il, typeof(object), mi.ReturnType, false);
}
il.Emit(OpCodes.Ret);
_tb.DefineMethodOverride(mdb, mi);
return mdb;
}
private static Type[] ParamTypes(ParameterInfo[] parms, bool noByRef)
{
Type[] types = new Type[parms.Length];
for (int i = 0; i < parms.Length; i++)
{
types[i] = parms[i].ParameterType;
if (noByRef && types[i].IsByRef)
types[i] = types[i].GetElementType()!;
}
return types;
}
// TypeCode does not exist in ProjectK or ProjectN.
// This lookup method was copied from PortableLibraryThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs
// but returns the integer value equivalent to its TypeCode enum.
private static int GetTypeCode(Type? type)
{
if (type == null)
return 0; // TypeCode.Empty;
if (type == typeof(bool))
return 3; // TypeCode.Boolean;
if (type == typeof(char))
return 4; // TypeCode.Char;
if (type == typeof(sbyte))
return 5; // TypeCode.SByte;
if (type == typeof(byte))
return 6; // TypeCode.Byte;
if (type == typeof(short))
return 7; // TypeCode.Int16;
if (type == typeof(ushort))
return 8; // TypeCode.UInt16;
if (type == typeof(int))
return 9; // TypeCode.Int32;
if (type == typeof(uint))
return 10; // TypeCode.UInt32;
if (type == typeof(long))
return 11; // TypeCode.Int64;
if (type == typeof(ulong))
return 12; // TypeCode.UInt64;
if (type == typeof(float))
return 13; // TypeCode.Single;
if (type == typeof(double))
return 14; // TypeCode.Double;
if (type == typeof(decimal))
return 15; // TypeCode.Decimal;
if (type == typeof(DateTime))
return 16; // TypeCode.DateTime;
if (type == typeof(string))
return 18; // TypeCode.String;
if (type.GetTypeInfo().IsEnum)
return GetTypeCode(Enum.GetUnderlyingType(type));
return 1; // TypeCode.Object;
}
private static readonly OpCode[] s_convOpCodes = new OpCode[] {
OpCodes.Nop, //Empty = 0,
OpCodes.Nop, //Object = 1,
OpCodes.Nop, //DBNull = 2,
OpCodes.Conv_I1, //Boolean = 3,
OpCodes.Conv_I2, //Char = 4,
OpCodes.Conv_I1, //SByte = 5,
OpCodes.Conv_U1, //Byte = 6,
OpCodes.Conv_I2, //Int16 = 7,
OpCodes.Conv_U2, //UInt16 = 8,
OpCodes.Conv_I4, //Int32 = 9,
OpCodes.Conv_U4, //UInt32 = 10,
OpCodes.Conv_I8, //Int64 = 11,
OpCodes.Conv_U8, //UInt64 = 12,
OpCodes.Conv_R4, //Single = 13,
OpCodes.Conv_R8, //Double = 14,
OpCodes.Nop, //Decimal = 15,
OpCodes.Nop, //DateTime = 16,
OpCodes.Nop, //17
OpCodes.Nop, //String = 18,
};
private static readonly OpCode[] s_ldindOpCodes = new OpCode[] {
OpCodes.Nop, //Empty = 0,
OpCodes.Nop, //Object = 1,
OpCodes.Nop, //DBNull = 2,
OpCodes.Ldind_I1, //Boolean = 3,
OpCodes.Ldind_I2, //Char = 4,
OpCodes.Ldind_I1, //SByte = 5,
OpCodes.Ldind_U1, //Byte = 6,
OpCodes.Ldind_I2, //Int16 = 7,
OpCodes.Ldind_U2, //UInt16 = 8,
OpCodes.Ldind_I4, //Int32 = 9,
OpCodes.Ldind_U4, //UInt32 = 10,
OpCodes.Ldind_I8, //Int64 = 11,
OpCodes.Ldind_I8, //UInt64 = 12,
OpCodes.Ldind_R4, //Single = 13,
OpCodes.Ldind_R8, //Double = 14,
OpCodes.Nop, //Decimal = 15,
OpCodes.Nop, //DateTime = 16,
OpCodes.Nop, //17
OpCodes.Ldind_Ref, //String = 18,
};
private static readonly OpCode[] s_stindOpCodes = new OpCode[] {
OpCodes.Nop, //Empty = 0,
OpCodes.Nop, //Object = 1,
OpCodes.Nop, //DBNull = 2,
OpCodes.Stind_I1, //Boolean = 3,
OpCodes.Stind_I2, //Char = 4,
OpCodes.Stind_I1, //SByte = 5,
OpCodes.Stind_I1, //Byte = 6,
OpCodes.Stind_I2, //Int16 = 7,
OpCodes.Stind_I2, //UInt16 = 8,
OpCodes.Stind_I4, //Int32 = 9,
OpCodes.Stind_I4, //UInt32 = 10,
OpCodes.Stind_I8, //Int64 = 11,
OpCodes.Stind_I8, //UInt64 = 12,
OpCodes.Stind_R4, //Single = 13,
OpCodes.Stind_R8, //Double = 14,
OpCodes.Nop, //Decimal = 15,
OpCodes.Nop, //DateTime = 16,
OpCodes.Nop, //17
OpCodes.Stind_Ref, //String = 18,
};
private static void Convert(ILGenerator il, Type source, Type target, bool isAddress)
{
Debug.Assert(!target.IsByRef);
if (target == source)
return;
TypeInfo sourceTypeInfo = source.GetTypeInfo();
TypeInfo targetTypeInfo = target.GetTypeInfo();
if (source.IsByRef)
{
Debug.Assert(!isAddress);
Type argType = source.GetElementType()!;
Ldind(il, argType);
Convert(il, argType, target, isAddress);
return;
}
if (targetTypeInfo.IsValueType)
{
if (sourceTypeInfo.IsValueType)
{
OpCode opCode = s_convOpCodes[GetTypeCode(target)];
Debug.Assert(!opCode.Equals(OpCodes.Nop));
il.Emit(opCode);
}
else
{
Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo));
il.Emit(OpCodes.Unbox, target);
if (!isAddress)
Ldind(il, target);
}
}
else if (targetTypeInfo.IsAssignableFrom(sourceTypeInfo))
{
if (sourceTypeInfo.IsValueType || source.IsGenericParameter)
{
if (isAddress)
Ldind(il, source);
il.Emit(OpCodes.Box, source);
}
}
else
{
Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo) || targetTypeInfo.IsInterface || sourceTypeInfo.IsInterface);
if (target.IsGenericParameter)
{
il.Emit(OpCodes.Unbox_Any, target);
}
else
{
il.Emit(OpCodes.Castclass, target);
}
}
}
private static void Ldind(ILGenerator il, Type type)
{
OpCode opCode = s_ldindOpCodes[GetTypeCode(type)];
if (!opCode.Equals(OpCodes.Nop))
{
il.Emit(opCode);
}
else
{
il.Emit(OpCodes.Ldobj, type);
}
}
private static void Stind(ILGenerator il, Type type)
{
OpCode opCode = s_stindOpCodes[GetTypeCode(type)];
if (!opCode.Equals(OpCodes.Nop))
{
il.Emit(opCode);
}
else
{
il.Emit(OpCodes.Stobj, type);
}
}
private class ParametersArray
{
private readonly ILGenerator _il;
private readonly Type[] _paramTypes;
internal ParametersArray(ILGenerator il, Type[] paramTypes)
{
_il = il;
_paramTypes = paramTypes;
}
internal void Get(int i)
{
_il.Emit(OpCodes.Ldarg, i + 1);
}
internal void BeginSet(int i)
{
_il.Emit(OpCodes.Ldarg, i + 1);
}
internal void EndSet(int i, Type stackType)
{
Debug.Assert(_paramTypes[i].IsByRef);
Type argType = _paramTypes[i].GetElementType()!;
Convert(_il, stackType, argType, false);
Stind(_il, argType);
}
}
private class GenericArray<T>
{
private readonly ILGenerator _il;
private readonly LocalBuilder _lb;
internal GenericArray(ILGenerator il, int len)
{
_il = il;
_lb = il.DeclareLocal(typeof(T[]));
il.Emit(OpCodes.Ldc_I4, len);
il.Emit(OpCodes.Newarr, typeof(T));
il.Emit(OpCodes.Stloc, _lb);
}
internal void Load()
{
_il.Emit(OpCodes.Ldloc, _lb);
}
internal void Get(int i)
{
_il.Emit(OpCodes.Ldloc, _lb);
_il.Emit(OpCodes.Ldc_I4, i);
_il.Emit(OpCodes.Ldelem_Ref);
}
internal void BeginSet(int i)
{
_il.Emit(OpCodes.Ldloc, _lb);
_il.Emit(OpCodes.Ldc_I4, i);
}
internal void EndSet(Type stackType)
{
Convert(_il, stackType, typeof(T), false);
_il.Emit(OpCodes.Stelem_Ref);
}
}
private sealed class PropertyAccessorInfo
{
public MethodInfo? InterfaceGetMethod { get; }
public MethodInfo? InterfaceSetMethod { get; }
public MethodBuilder? GetMethodBuilder { get; set; }
public MethodBuilder? SetMethodBuilder { get; set; }
public PropertyAccessorInfo(MethodInfo? interfaceGetMethod, MethodInfo? interfaceSetMethod)
{
InterfaceGetMethod = interfaceGetMethod;
InterfaceSetMethod = interfaceSetMethod;
}
}
private sealed class EventAccessorInfo
{
public MethodInfo? InterfaceAddMethod { get; }
public MethodInfo? InterfaceRemoveMethod { get; }
public MethodInfo? InterfaceRaiseMethod { get; }
public MethodBuilder? AddMethodBuilder { get; set; }
public MethodBuilder? RemoveMethodBuilder { get; set; }
public MethodBuilder? RaiseMethodBuilder { get; set; }
public EventAccessorInfo(MethodInfo? interfaceAddMethod, MethodInfo? interfaceRemoveMethod, MethodInfo? interfaceRaiseMethod)
{
InterfaceAddMethod = interfaceAddMethod;
InterfaceRemoveMethod = interfaceRemoveMethod;
InterfaceRaiseMethod = interfaceRaiseMethod;
}
}
private sealed class MethodInfoEqualityComparer : EqualityComparer<MethodInfo>
{
public static readonly MethodInfoEqualityComparer Instance = new MethodInfoEqualityComparer();
private MethodInfoEqualityComparer() { }
public sealed override bool Equals(MethodInfo? left, MethodInfo? right)
{
if (ReferenceEquals(left, right))
return true;
if (left == null)
return right == null;
else if (right == null)
return false;
// This assembly should work in netstandard1.3,
// so we cannot use MemberInfo.MetadataToken here.
// Therefore, it compares honestly referring ECMA-335 I.8.6.1.6 Signature Matching.
if (!Equals(left.DeclaringType, right.DeclaringType))
return false;
if (!Equals(left.ReturnType, right.ReturnType))
return false;
if (left.CallingConvention != right.CallingConvention)
return false;
if (left.IsStatic != right.IsStatic)
return false;
if (left.Name != right.Name)
return false;
Type[] leftGenericParameters = left.GetGenericArguments();
Type[] rightGenericParameters = right.GetGenericArguments();
if (leftGenericParameters.Length != rightGenericParameters.Length)
return false;
for (int i = 0; i < leftGenericParameters.Length; i++)
{
if (!Equals(leftGenericParameters[i], rightGenericParameters[i]))
return false;
}
ParameterInfo[] leftParameters = left.GetParameters();
ParameterInfo[] rightParameters = right.GetParameters();
if (leftParameters.Length != rightParameters.Length)
return false;
for (int i = 0; i < leftParameters.Length; i++)
{
if (!Equals(leftParameters[i].ParameterType, rightParameters[i].ParameterType))
return false;
}
return true;
}
public sealed override int GetHashCode(MethodInfo obj)
{
if (obj == null)
return 0;
Debug.Assert(obj.DeclaringType != null);
int hashCode = obj.DeclaringType!.GetHashCode();
hashCode ^= obj.Name.GetHashCode();
foreach (ParameterInfo parameter in obj.GetParameters())
{
hashCode ^= parameter.ParameterType.GetHashCode();
}
return hashCode;
}
}
}
}
}