using System; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Threading; namespace AspClassic.Scripting.Utils; internal static class ReflectionUtils { public const char GenericArityDelimiter = '`'; private static AssemblyBuilder _assembly; private static ModuleBuilder _modBuilder; private static int _typeCount; private static readonly Type[] _DelegateCtorSignature = new Type[2] { typeof(object), typeof(IntPtr) }; private static TypeBuilder DefineDelegateType(string name) { if (_assembly == null) { Interlocked.CompareExchange(ref _assembly, AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicDelegates"), AssemblyBuilderAccess.Run), null); lock (_assembly) { if (_modBuilder == null) { _modBuilder = _assembly.DefineDynamicModule("DynamicDelegates"); } } } return _modBuilder.DefineType(name + Interlocked.Increment(ref _typeCount), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AutoClass, typeof(MulticastDelegate)); } public static Type GetObjectCallSiteDelegateType(int paramCnt) { switch (paramCnt) { case 0: return typeof(Func); case 1: return typeof(Func); case 2: return typeof(Func); case 3: return typeof(Func); case 4: return typeof(Func); case 5: return typeof(Func); case 6: return typeof(Func); case 7: return typeof(Func); case 8: return typeof(Func); case 9: return typeof(Func); case 10: return typeof(Func); case 11: return typeof(Func); case 12: return typeof(Func); case 13: return typeof(Func); case 14: return typeof(Func); default: { Type[] array = new Type[paramCnt + 2]; array[0] = typeof(CallSite); array[1] = typeof(object); for (int i = 0; i < paramCnt; i++) { array[i + 2] = typeof(object); } TypeBuilder typeBuilder = DefineDelegateType("Delegate"); typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard, _DelegateCtorSignature).SetImplementationFlags(MethodImplAttributes.CodeTypeMask); typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask, typeof(object), array).SetImplementationFlags(MethodImplAttributes.CodeTypeMask); return typeBuilder.CreateType(); } } } }