Esempio n. 1
0
		internal TextSection(PEWriter peWriter, CliHeader cliHeader, ModuleBuilder moduleBuilder, int strongNameSignatureLength)
		{
			this.peWriter = peWriter;
			this.cliHeader = cliHeader;
			this.moduleBuilder = moduleBuilder;
			this.strongNameSignatureLength = (uint)strongNameSignatureLength;
		}
Esempio n. 2
0
		internal TextSection(PEWriter peWriter, CliHeader cliHeader, ModuleBuilder moduleBuilder, bool strongName)
		{
			this.peWriter = peWriter;
			this.cliHeader = cliHeader;
			this.moduleBuilder = moduleBuilder;
			this.strongName = strongName;
		}
		internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder,
			PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine,
			ResourceSection resources, int entryPointToken, Stream stream)
		{
			if (stream == null)
			{
				string fileName = moduleBuilder.FullyQualifiedName;
				bool mono = System.Type.GetType("Mono.Runtime") != null;
				if (mono)
				{
					try
					{
						// Mono mmaps the file, so unlink the previous version since it may be in use
						File.Delete(fileName);
					}
					catch { }
				}
				using (FileStream fs = new FileStream(fileName, FileMode.Create))
				{
					WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs);
				}
				// if we're running on Mono, mark the module as executable by using a Mono private API extension
				if (mono)
				{
					File.SetAttributes(fileName, (FileAttributes)(unchecked((int)0x80000000)));
				}
			}
			else
			{
				WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream);
			}
		}
		internal ParameterBuilder(ModuleBuilder moduleBuilder, int sequence, ParameterAttributes attribs, string name)
		{
			this.moduleBuilder = moduleBuilder;
			this.flags = (short)attribs;
			this.sequence = (short)sequence;
			this.nameIndex = name == null ? 0 : moduleBuilder.Strings.Add(name);
			this.name = name;
		}
Esempio n. 5
0
 /// <summary>
 /// 构建一个可保存的动态程序集 ModuleScope 模块
 /// </summary>
 /// <param name="assemblySaveDir">程序集保存的目录</param>
 public ModuleScope(String assemblySaveDir)
 {
     if (assemblySaveDir != null && !Directory.Exists(assemblySaveDir))
     {
         throw new DirectoryNotFoundException(assemblySaveDir);
     }
     _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(NameOfAssembly), AssemblyBuilderAccess.RunAndSave, assemblySaveDir);
     ModuleBuilder = _assemblyBuilder.DefineDynamicModule(NameOfAssembly, AssemblyFileName);
     SavePhysicalAssembly = true;
 }
		internal TextSection(PEWriter peWriter, CliHeader cliHeader, ModuleBuilder moduleBuilder, int strongNameSignatureLength)
		{
			this.peWriter = peWriter;
			this.cliHeader = cliHeader;
			this.moduleBuilder = moduleBuilder;
			this.strongNameSignatureLength = (uint)strongNameSignatureLength;
			if (moduleBuilder.unmanagedExports.Count != 0)
			{
				this.exportTables = new ExportTables(this);
			}
		}
Esempio n. 7
0
	protected static void SetUp ()
	{
		AssemblyName assemblyName = new AssemblyName ();
		assemblyName.Name = ASSEMBLY_NAME;

		assembly =
			Thread.GetDomain ().DefineDynamicAssembly (
				assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());

		module = assembly.DefineDynamicModule ("module1");
	}
Esempio n. 8
0
		internal static void Create(ModuleBuilder modb, ClassLoaderWrapper loader)
		{
			TypeBuilder tb = modb.DefineType(DotNetTypeWrapper.GenericDelegateInterfaceTypeName, TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public);
			tb.DefineGenericParameters("T")[0].SetBaseTypeConstraint(Types.MulticastDelegate);
			genericDelegateInterfaceType = tb.CreateType();

			genericAttributeAnnotationType = CreateAnnotationType(modb, DotNetTypeWrapper.GenericAttributeAnnotationTypeName);
			genericAttributeAnnotationMultipleType = CreateAnnotationType(modb, DotNetTypeWrapper.GenericAttributeAnnotationMultipleTypeName);
			genericAttributeAnnotationReturnValueType = CreateAnnotationType(modb, DotNetTypeWrapper.GenericAttributeAnnotationReturnValueTypeName);
			CreateEnumEnum(modb, loader);
		}
Esempio n. 9
0
		private static void CreateEnumEnum(ModuleBuilder modb, ClassLoaderWrapper loader)
		{
			TypeWrapper enumTypeWrapper = loader.LoadClassByDottedName("java.lang.Enum");
			enumTypeWrapper.Finish();
			TypeBuilder tb = modb.DefineType(DotNetTypeWrapper.GenericEnumEnumTypeName, TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public, enumTypeWrapper.TypeAsBaseType);
			GenericTypeParameterBuilder gtpb = tb.DefineGenericParameters("T")[0];
			gtpb.SetBaseTypeConstraint(Types.Enum);
			CodeEmitter ilgen = CodeEmitter.Create(tb.DefineConstructor(MethodAttributes.Private, CallingConventions.Standard, new Type[] { Types.String, Types.Int32 }));
			ilgen.Emit(OpCodes.Ldarg_0);
			ilgen.Emit(OpCodes.Ldarg_1);
			ilgen.Emit(OpCodes.Ldarg_2);
			enumTypeWrapper.GetMethodWrapper("<init>", "(Ljava.lang.String;I)V", false).EmitCall(ilgen);
			ilgen.Emit(OpCodes.Ret);
			genericEnumEnumType = tb.CreateType();
		}
Esempio n. 10
0
		internal static ISymbolWriterImpl CreateSymbolWriterFor(ModuleBuilder moduleBuilder)
		{
			if (runningOnMono)
			{
#if MONO
				return new MdbWriter(moduleBuilder);
#else
				throw new NotSupportedException("IKVM.Reflection must be compiled with MONO defined to support writing Mono debugging symbols.");
#endif
			}
			else
			{
				return new PdbWriter(moduleBuilder);
			}
		}
Esempio n. 11
0
        public RouteResolver(
            ModuleCatalog catalog,
            ModuleBuilder moduleBuilder,
            RouteResolverTrie routeTrie)
        {
            if (catalog == null)
                throw new ArgumentNullException("catalog");
            if (moduleBuilder == null)
                throw new ArgumentNullException("moduleBuilder");
            if (routeTrie == null)
                throw new ArgumentNullException("routeTrie");

            _catalog = catalog;
            _moduleBuilder = moduleBuilder;
            _routeTrie = routeTrie;
        }
Esempio n. 12
0
		internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder,
			PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine,
			ResourceSection resources, int entryPointToken, Stream stream)
		{
			if (stream == null)
			{
				using (FileStream fs = new FileStream(moduleBuilder.FullyQualifiedName, FileMode.Create))
				{
					WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs);
				}
			}
			else
			{
				WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream);
			}
		}
		internal static ISymbolWriterImpl CreateSymbolWriterFor(ModuleBuilder moduleBuilder)
		{
#if NO_SYMBOL_WRITER
			throw new NotSupportedException("IKVM.Reflection compiled with NO_SYMBOL_WRITER does not support writing debugging symbols.");
#else
			if (Universe.MonoRuntime)
			{
#if MONO
				return new MdbWriter(moduleBuilder);
#else
				throw new NotSupportedException("IKVM.Reflection must be compiled with MONO defined to support writing Mono debugging symbols.");
#endif
			}
			else
			{
				return new PdbWriter(moduleBuilder);
			}
#endif
		}
Esempio n. 14
0
    public CodeGen(Stmt stmt, string moduleName)
    {
        if (string.IsNullOrEmpty(moduleName)) throw new ArgumentException("must have a module name", "moduleName");

        _stmt = stmt;
        _moduleName = moduleName;
        if (Path.GetFileName(moduleName) != moduleName) throw new Exception("can only output into current directory!");

        var filename = Path.GetFileNameWithoutExtension(moduleName);
        var asmName = new AssemblyName(filename);
        _asmb = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save);
        _modb = _asmb.DefineDynamicModule(moduleName);
        _typeBuilder = _modb.DefineType("Foo");

        _methb = _typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void),
            Type.EmptyTypes);

        _il = _methb.GetILGenerator();
        SymbolTable = new Dictionary<string, LocalBuilder>();
    }
Esempio n. 15
0
    static HugsWrapper()
    {
        AssemblyName assemblyName = new AssemblyName();
           assemblyName.Name = "HugsAssembly";

           AppDomain currentDomain = AppDomain.CurrentDomain;

           currentDomain.AssemblyResolve += new ResolveEventHandler(Resolver);

           assemblyBuilder =
         currentDomain.DefineDynamicAssembly(assemblyName,
                     AssemblyBuilderAccess.Run,//AssemblyBuilderAccess.RunAndSave,
                     (String)null);
           moduleBuilder =
         assemblyBuilder.DefineDynamicModule("HugsModule");
           //     assemblyBuilder.DefineDynamicModule("HugsModule", "test.dll");

           hugs = new Server();
           uniq = 0;
    }
Esempio n. 16
0
		internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder,
			PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine,
			ResourceSection resources, int entryPointToken, Stream stream)
		{
			if (stream == null)
			{
				using (FileStream fs = new FileStream(moduleBuilder.FullyQualifiedName, FileMode.Create))
				{
					WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs);
				}
				// if we're running on Mono, mark the module as executable by using a Mono private API extension
				if (System.Type.GetType("Mono.Runtime") != null)
				{
					File.SetAttributes(moduleBuilder.FullyQualifiedName, (FileAttributes)(unchecked((int)0x80000000)));
				}
			}
			else
			{
				WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream);
			}
		}
Esempio n. 17
0
File: com.cs Progetto: Diullei/Storm
        private void CreateDllRegType()
        {
            if (s_mb == null)
            {
                // Create dynamic assembly
                AssemblyName an = new AssemblyName();
                an.Name = "DllRegServerAssembly" + Guid.NewGuid().ToString("N");
                AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);

                // Add module to assembly
                s_mb = ab.DefineDynamicModule("DllRegServerModule");
            }

            // Add class to module
            TypeBuilder tb = s_mb.DefineType("DllRegServerClass" + Guid.NewGuid().ToString("N"));

            MethodBuilder meb;

            // Add PInvoke methods to class
            meb = tb.DefinePInvokeMethod("DllRegisterServer", m_sDllFile,
              MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
              CallingConventions.Standard, typeof(int), null, CallingConvention.StdCall, CharSet.Auto);

            // Apply preservesig metadata attribute so we can handle return HRESULT ourselves
            meb.SetImplementationFlags(MethodImplAttributes.PreserveSig | meb.GetMethodImplementationFlags());

            meb = tb.DefinePInvokeMethod("DllUnregisterServer", m_sDllFile,
              MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
              CallingConventions.Standard, typeof(int), null, CallingConvention.StdCall, CharSet.Auto);

            // Apply preservesig metadata attribute so we can handle return HRESULT ourselves
            meb.SetImplementationFlags(MethodImplAttributes.PreserveSig | meb.GetMethodImplementationFlags());

            // Create the type
            m_tDllReg = tb.CreateType();
        }
		private void AddJavaModuleAttribute(ModuleBuilder mb)
		{
			Type typeofJavaModuleAttribute = JVM.LoadType(typeof(JavaModuleAttribute));
			PropertyInfo[] propInfos = new PropertyInfo[] {
				typeofJavaModuleAttribute.GetProperty("Jars")
			};
			object[] propValues = new object[] {
				jarList.ToArray()
			};
			if (nameMappings.Count > 0)
			{
				string[] list = new string[nameMappings.Count * 2];
				int i = 0;
				foreach (KeyValuePair<string, string> kv in nameMappings)
				{
					list[i++] = kv.Key;
					list[i++] = kv.Value;
				}
				CustomAttributeBuilder cab = new CustomAttributeBuilder(typeofJavaModuleAttribute.GetConstructor(new Type[] { JVM.Import(typeof(string[])) }), new object[] { list }, propInfos, propValues);
				mb.SetCustomAttribute(cab);
			}
			else
			{
				CustomAttributeBuilder cab = new CustomAttributeBuilder(typeofJavaModuleAttribute.GetConstructor(Type.EmptyTypes), new object[0], propInfos, propValues);
				mb.SetCustomAttribute(cab);
			}
		}
Esempio n. 19
0
		public ModuleBuilder DefineDynamicModule(string name, string fileName, bool emitSymbolInfo)
		{
			ModuleBuilder module = new ModuleBuilder(this, name, fileName, emitSymbolInfo);
			modules.Add(module);
			return module;
		}
Esempio n. 20
0
 protected void DefineTypesCore(ModuleBuilder moduleBuilder)
 {
 }
Esempio n. 21
0
        private static bool DoStubCall(int callerIndex, bool staticMethod, bool onValueType, GenericShape typeGenericShape, GenericShape methodGenericShape)
        {
            string        callerNameSeed = Config.InstantiatingStubPrefix + "Caller" + callerIndex; // Use a consistent seed value here so that the various various of unboxing/instantiating stubs are generated with the same arg shape
            string        callerName     = callerNameSeed + (staticMethod ? "Static" : "Instance") + (onValueType ? "Class" : "ValueType") + typeGenericShape.ToString() + methodGenericShape.ToString();
            Random        rand           = new Random(GetSeed(callerNameSeed));
            List <TypeEx> pms;

            do
            {
                pms = RandomParameters(s_allTypes, rand);
            } while (pms.Count > 16);

            Type delegateType = GetDelegateType(pms, typeof(int));

            Callee callee = new Callee(callerName + "Callee", pms);// CreateCallee(Config.PInvokeePrefix + calleeIndex, s_allTypes);

            callee.Emit();

            Delegate calleeDelegate = callee.Method.CreateDelegate(delegateType);

            int newStubCount = Interlocked.Increment(ref s_stubTypesCreated);

            if ((s_stubTypesModule == null) || (newStubCount % 1000) == 0)
            {
                AssemblyBuilder stubsAssembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ABIStress_Stubs" + newStubCount), AssemblyBuilderAccess.RunAndCollect);
                s_stubTypesModule = stubsAssembly.DefineDynamicModule("ABIStress_Stubs" + newStubCount);
            }

            // This code is based on DelegateHelpers.cs in System.Linq.Expressions.Compiler
            TypeBuilder tb =
                s_stubTypesModule.DefineType(
                    $"{callerName}_GenericTarget",
                    TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AutoClass,
                    onValueType ? typeof(object) : typeof(ValueType));

            GenericTypeParameterBuilder[] typeParamsType = null;
            if (typeGenericShape != GenericShape.NotGeneric)
            {
                typeParamsType = tb.DefineGenericParameters(new string[] { "T" });
            }

            FieldInfo fieldDeclaration = tb.DefineField("MagicValue", typeof(int), FieldAttributes.Public);

            Type      typeofInstantiatedType;
            FieldInfo fieldInfoMagicValueField;

            if (typeGenericShape == GenericShape.NotGeneric)
            {
                typeofInstantiatedType   = tb;
                fieldInfoMagicValueField = fieldDeclaration;
            }
            else
            {
                typeofInstantiatedType   = tb.MakeGenericType(typeParamsType[0]);
                fieldInfoMagicValueField = TypeBuilder.GetField(typeofInstantiatedType, fieldDeclaration);
            }

            ConstructorBuilder cb = tb.DefineConstructor(
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName,
                CallingConventions.Standard,
                new Type[] { typeof(int) });

            cb.SetImplementationFlags(MethodImplAttributes.Managed);

            ILGenerator g = cb.GetILGenerator();

            g.Emit(OpCodes.Ldarg, 0);
            g.Emit(OpCodes.Call, typeof(object).GetConstructor(Array.Empty <Type>()));
            g.Emit(OpCodes.Ldarg, 0);
            g.Emit(OpCodes.Ldarg_1);
            g.Emit(OpCodes.Stfld, fieldInfoMagicValueField);
            g.Emit(OpCodes.Ret);

            MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig;

            if (staticMethod)
            {
                methodAttributes |= MethodAttributes.Static;
            }

            MethodBuilder mbInstance = tb.DefineMethod(
                "Method",
                methodAttributes,
                callee.Method.ReturnType,
                callee.Parameters.Select(t => t.Type).ToArray());

            GenericTypeParameterBuilder[] typeParamsMethod = null;
            if (methodGenericShape != GenericShape.NotGeneric)
            {
                typeParamsMethod = mbInstance.DefineGenericParameters(new string[] { "T" });
            }

            mbInstance.SetImplementationFlags(MethodImplAttributes.Managed);

            int magicNumberEmbeddedInObject = rand.Next();

            GCHandle gchCallee       = GCHandle.Alloc(callee.Method.CreateDelegate(delegateType));
            IntPtr   gchCalleeIntPtr = GCHandle.ToIntPtr(gchCallee);

            g = mbInstance.GetILGenerator();

            if (!staticMethod)
            {
                // Verify random number made it intact, and this parameter was handled correctly

                g.Emit(OpCodes.Ldarg_0);
                g.Emit(OpCodes.Ldfld, fieldInfoMagicValueField);
                g.Emit(OpCodes.Ldc_I4, magicNumberEmbeddedInObject);
                g.Emit(OpCodes.Call, s_compareNumbers);
            }

            // Verify generic args are as expected
            EmitTypeHandleCheck(g, typeGenericShape, typeParamsType, "type");
            EmitTypeHandleCheck(g, methodGenericShape, typeParamsMethod, "method");

            // Make the call to callee
            LocalBuilder gcHandleLocal = g.DeclareLocal(typeof(GCHandle));

            // Load GCHandle of callee delegate
            g.Emit(OpCodes.Ldc_I8, (long)gchCalleeIntPtr);
            g.Emit(OpCodes.Conv_I);
            g.Emit(OpCodes.Call, s_gcHandleFromIntPtr);
            g.Emit(OpCodes.Stloc, gcHandleLocal);
            // Resolve to target
            g.Emit(OpCodes.Ldloca, gcHandleLocal);
            g.Emit(OpCodes.Call, s_gcHandle_getTarget);
            // Cast to delegate type
            g.Emit(OpCodes.Castclass, delegateType);
            // Load all args
            int argOffset = 1;

            if (staticMethod)
            {
                argOffset = 0;
            }
            for (int i = 0; i < pms.Count; i++)
            {
                g.Emit(OpCodes.Ldarg, argOffset + i);
            }

            // Call delegate invoke method
            g.Emit(OpCodes.Callvirt, delegateType.GetMethod("Invoke"));
            // ret
            g.Emit(OpCodes.Ret);
            Type calleeTypeOpen = tb.CreateType();
            Type calleeType;

            switch (typeGenericShape)
            {
            case GenericShape.NotGeneric:
                calleeType = calleeTypeOpen;
                break;

            case GenericShape.GenericOverReferenceType:
                calleeType = calleeTypeOpen.MakeGenericType(typeof(object));
                break;

            case GenericShape.GenericOverValueType:
                calleeType = calleeTypeOpen.MakeGenericType(typeof(int));
                break;

            default:
                throw new Exception("Unknown case");
            }

            MethodInfo targetMethodOpen = calleeType.GetMethod("Method");
            MethodInfo targetMethod;

            switch (methodGenericShape)
            {
            case GenericShape.NotGeneric:
                targetMethod = targetMethodOpen;
                break;

            case GenericShape.GenericOverReferenceType:
                targetMethod = targetMethodOpen.MakeGenericMethod(typeof(object));
                break;

            case GenericShape.GenericOverValueType:
                targetMethod = targetMethodOpen.MakeGenericMethod(typeof(int));
                break;

            default:
                throw new Exception("Unknown case");
            }

            Delegate targetMethodToCallDel;

            if (staticMethod)
            {
                targetMethodToCallDel = targetMethod.CreateDelegate(delegateType);
            }
            else
            {
                targetMethodToCallDel = targetMethod.CreateDelegate(delegateType, Activator.CreateInstance(calleeType, magicNumberEmbeddedInObject));
            }

            GCHandle gchTargetMethod = GCHandle.Alloc(targetMethodToCallDel);

            // CALLER Dynamic method
            DynamicMethod caller = new DynamicMethod(
                callerName, typeof(int), pms.Select(t => t.Type).ToArray(), typeof(Program).Module);

            g = caller.GetILGenerator();

            // Create the args to pass to the callee from the caller.
            List <Value> args = GenCallerToCalleeArgs(pms, callee.Parameters, rand);

            if (Config.Verbose)
            {
                EmitDumpValues("Caller's incoming args", g, pms.Select((p, i) => new ArgValue(p, i)));
            }

            if (Config.Verbose)
            {
                EmitDumpValues($"Caller's args to {callerName} call", g, args);
            }

            gcHandleLocal = g.DeclareLocal(typeof(GCHandle));
            g.Emit(OpCodes.Ldc_I8, (long)GCHandle.ToIntPtr(gchTargetMethod));
            g.Emit(OpCodes.Conv_I);
            g.Emit(OpCodes.Call, s_gcHandleFromIntPtr);
            g.Emit(OpCodes.Stloc, gcHandleLocal);
            // Resolve to target
            g.Emit(OpCodes.Ldloca, gcHandleLocal);
            g.Emit(OpCodes.Call, s_gcHandle_getTarget);
            // Cast to delegate type
            g.Emit(OpCodes.Castclass, delegateType);

            foreach (Value v in args)
            {
                v.Emit(g);
            }

            // Call delegate invoke method
            g.Emit(OpCodes.Callvirt, delegateType.GetMethod("Invoke"));
            // ret
            g.Emit(OpCodes.Ret);

            (object callerResult, object calleeResult) = InvokeCallerCallee(caller, pms, callee.Method, args, rand);

            gchCallee.Free();
            gchTargetMethod.Free();
            if (callerResult.Equals(calleeResult))
            {
                return(true);
            }

            Console.WriteLine("Mismatch in stub call: expected {0}, got {1}", calleeResult, callerResult);
            Console.WriteLine(callerName);
            WriteSignature(caller);
            WriteSignature(callee.Method);
            return(false);
        }
Esempio n. 22
0
        public void ConfigureServices(IServiceCollection services)
        {
            var moduleRepo              = new ModuleRepository();
            var elementMapper           = new ElementTypeTemplateMapper();
            var controlMapper           = new ControlTypeTemplateMapper();
            var validationMapper        = new ValidationAttributeJsConverterMapper();
            var moduleBuilder           = new ModuleBuilder(moduleRepo, elementMapper, controlMapper, validationMapper);
            var inMemoryFlowPersistance = new InMemoryFlowPersistance();

            services.AddSingleton <IElementTypeTemplateMapper>(elementMapper);
            services.AddSingleton <IControlTypeTemplateMapper>(controlMapper);
            services.AddSingleton <IValidationAttributeJsConverterMapper>(validationMapper);
            services.AddSingleton <IModuleRepository>(moduleRepo);
            services.AddSingleton <IFlowPersistance>(inMemoryFlowPersistance);

            validationMapper.AddValidator("MaxLengthAttribute", CustomAttribuesJsConverters.MaxLengthJsConverter);
            controlMapper.AddTemplate("defaultButton", ControlType.Button, true);

            UserRegistrationFlow.RegisterFlow(moduleBuilder);
            UserLoginFlow.RegisterFlow(moduleBuilder);
            UserEditFlow.RegisterFlow(moduleBuilder);

            A1Flow.RegisterFlow(moduleBuilder);
            A2A3A4Flow.RegisterFlow(moduleBuilder);
            A7Flow.RegisterFlow(moduleBuilder);

            TestFlow.RegisterFlow(moduleBuilder);
            SimpleFlow.RegisterFlow(moduleBuilder);

            MainReportFlow.RegisterFlow(moduleBuilder);

            services.AddControllers(c =>
            {
                c.EnableEndpointRouting = false;
            }).ConfigureApplicationPartManager(apm =>
            {
                apm.FeatureProviders.Add(new FlowControllerFeatureProvider(moduleRepo));
            }).AddNewtonsoftJson(j =>
            {
                j.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
                j.SerializerSettings.Converters.Add(new StringEnumConverter
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                });
                j.SerializerSettings.Converters.Add(new BaseCollectionConverter());
                j.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                j.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

            var symmetricKey = Encoding.ASCII.GetBytes(Configuration.GetSection("Jwt").GetValue <string>("SymmetricKey"));

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(symmetricKey),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
            services.AddAuthorization(a =>
            {
                a.AddPolicy("IsAccountEnabled", policy => policy.RequireClaim("account_enabled", "True", "true"));
            });

            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Core Dui Example API", Version = "v1"
                });
                s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    Description = "Please insert JWT with Bearer into field",
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });
                s.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            services.AddDbContext <DbLabCalcContext>(o =>
            {
                o.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.Configure <LdapConfig>(Configuration.GetSection("Ldap"));
            services.Configure <JwtConfig>(Configuration.GetSection("Jwt"));
            services.Configure <SmtpConfig>(Configuration.GetSection("Smtp"));
            services.Configure <AppConfig>(Configuration.GetSection("App"));

            services.AddScoped <IEmailClient, GmailEmailClient>();
            services.AddScoped <IAuthenticationService <LdapUser>, LdapAuthenticationService>();
            services.AddScoped <IAuthenticationService <DbUserClient>, DbAuthenticationService>();
            services.AddScoped <IEmailTemplates, EmailTemplates>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }
Esempio n. 23
0
 /// <summary>
 /// Builds LLVM IR instructions that get a handle to the metadata
 /// for a particular type.
 /// </summary>
 /// <param name="type">The type whose metadata is to be inspected.</param>
 /// <param name="module">
 /// The LLVM module to generate the metadata in.
 /// </param>
 /// <returns>A metadata pointer.</returns>
 public abstract LLVMValueRef GetMetadata(
     IType type,
     ModuleBuilder module);
Esempio n. 24
0
 /// <summary>
 /// Builds LLVM IR instructions that perform a virtual method lookup:
 /// loads the address of the implementation of a virtual method given
 /// a type metadata pointer for the 'this' type.
 /// </summary>
 /// <param name="callee">
 /// A virtual method to find an implementation for.
 /// </param>
 /// <param name="metadata">
 /// A handle to the type metadata of the 'this' type.
 /// </param>
 /// <param name="module">
 /// The LLVM module to generate the instructions in.
 /// </param>
 /// <param name="builder">
 /// An instruction builder to use for emitting instructions.
 /// </param>
 /// <param name="name">
 /// A suggested name for the value that refers to the method
 /// implementation address.
 /// </param>
 /// <returns>A pointer to a method implementation.</returns>
 public abstract LLVMValueRef EmitMethodAddress(
     IMethod callee,
     LLVMValueRef metadata,
     ModuleBuilder module,
     IRBuilder builder,
     string name);
Esempio n. 25
0
 public ProxyAssembly()
 {
     _ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ProxyBuilder"), AssemblyBuilderAccess.Run);
     _mb = _ab.DefineDynamicModule("testmod");
 }
Esempio n. 26
0
        /// <summary>
        /// Creates an <see cref="EnumBuilder"/> instance within <paramref name="modBuilder"/>
        /// </summary>
        /// <param name="modBuilder"></param>
        /// <param name="enumName"></param>
        /// <returns></returns>
        public static EnumBuilder GetEnum(ModuleBuilder modBuilder, string enumName)
        {
            EnumBuilder builder = modBuilder.DefineEnum(enumName, TypeAttributes.Public, typeof(Int32));

            return(builder);
        }
Esempio n. 27
0
        /// <summary>
        /// Creates a <see cref="ModuleBuilder"/> instance within <paramref name="asmBuilder"/>
        /// </summary>
        /// <param name="asmBuilder"></param>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        public static ModuleBuilder GetModule(AssemblyBuilder asmBuilder, String moduleName)
        {
            ModuleBuilder builder = asmBuilder.DefineDynamicModule(moduleName, true);//"EmitMethods", "EmitMethods.dll");

            return(builder);
        }
Esempio n. 28
0
    /// <summary>
    /// 动态生成接口的实现类
    /// </summary>
    /// <param name="interfaceType"></param>
    /// <param name="constructor"></param>
    /// <returns></returns>
    private Type BuildTargetType(Type targetType, params object[] constructor)
    {
        if (!targetType.IsInterface)
        {
            throw new Exception($"{targetType.FullName} is not a interface");
        }

        string assemblyName = targetType.Name + "_ProxyAssembly";
        string moduleName   = targetType.Name + "_ProxyModule";
        string typeName     = targetType.Name + "_Proxy";

        AssemblyName    assyName    = new AssemblyName(assemblyName);
        AssemblyBuilder assyBuilder = AssemblyBuilder.DefineDynamicAssembly(assyName, AssemblyBuilderAccess.Run);
        ModuleBuilder   modBuilder  = assyBuilder.DefineDynamicModule(moduleName);

        //新类型的属性
        TypeAttributes newTypeAttribute = TypeAttributes.Class | TypeAttributes.Public;
        //父类型
        Type parentType = null;

        //要实现的接口
        Type[] interfaceTypes = new Type[] { targetType };

        var allInterfaces = targetType.GetInterfaces();

        //优先实例化泛型
        foreach (var iInterface in allInterfaces)
        {
            if (iInterface.IsGenericType)
            {
                var isRepository = typeof(IRepository <,>).IsAssignableFrom(iInterface.GetGenericTypeDefinition());
                if (isRepository)
                {
                    var genericType = iInterface.GetGenericArguments();
                    parentType = typeof(BaseRepository <,>).MakeGenericType(genericType);
                    break;
                }
            }
            else
            {
                var isRepository = typeof(IRepository).IsAssignableFrom(iInterface);
                if (isRepository)
                {
                    parentType = typeof(BaseRepository);
                }
            }
        }

        if (parentType == null)
        {
            throw new Exception($"{targetType.FullName} please assignable from {typeof(IRepository<,>).FullName} or {typeof(IRepository).FullName}");
        }

        //得到类型生成器
        TypeBuilder typeBuilder = modBuilder.DefineType(typeName, newTypeAttribute, parentType, interfaceTypes);

        var cotrParameterTypes = new Type[] { typeof(IDbContext) };
        //创建构造函数
        ConstructorBuilder constructorBuilder =
            typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, cotrParameterTypes);

        var baseCtor = parentType.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, cotrParameterTypes, null);

        //il创建构造函数,对httpService和IServiceProvider两个字段进行赋值,同时初始化存放参数的集合
        ILGenerator ilgCtor = constructorBuilder.GetILGenerator();

        ilgCtor.Emit(OpCodes.Ldarg_0); //加载当前类
        ilgCtor.Emit(OpCodes.Ldarg_1);
        //ilgCtor.Emit(OpCodes.Ldarg_2);
        ilgCtor.Emit(OpCodes.Call, baseCtor);

        ilgCtor.Emit(OpCodes.Nop);
        ilgCtor.Emit(OpCodes.Nop);
        ilgCtor.Emit(OpCodes.Ret); //返回

        var resultType = typeBuilder.CreateTypeInfo().AsType();

        return(resultType);
    }
Esempio n. 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EmitFieldGetAccessor"/> class.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="assemblyBuilder">The assembly builder.</param>
        /// <param name="moduleBuilder">The module builder.</param>
        public EmitFieldSetAccessor(Type targetObjectType, string fieldName, AssemblyBuilder assemblyBuilder, ModuleBuilder moduleBuilder)
        {
            _targetType = targetObjectType;
            _fieldName  = fieldName;

            FieldInfo fieldInfo = _targetType.GetField(fieldName, VISIBILITY);

            // Make sure the field exists
            if (fieldInfo == null)
            {
                throw new NotSupportedException(
                          string.Format("Field \"{0}\" does not exist for type "
                                        + "{1}.", fieldName, targetObjectType));
            }
            else
            {
                _fieldType = fieldInfo.FieldType;
                this.EmitIL(assemblyBuilder, moduleBuilder);
            }
        }
Esempio n. 30
0
        protected virtual Type EmitStartInfo(ModuleBuilder moduleBuilder)
        {
            var si = EmitStartInfoCore(moduleBuilder);

            return(si.CreateType());
        }
Esempio n. 31
0
        private Type EmitHostServiceWrapper(ModuleBuilder m, IEnumerable <BuilderMethodInfo> methods)
        {
            var si = m.DefineType(HOST_SERVICE_WRAPPER, TypeAttributes.Public | TypeAttributes.Sealed);

            si.AddInterfaceImplementation(_GeneratedServiceContract);
            si.SetCustomAttribute(
                new CustomAttributeBuilder(
                    typeof(ServiceBehaviorAttribute).GetConstructor(new Type[0]),
                    new object[0],
                    new[]
            {
                typeof(ServiceBehaviorAttribute).GetProperty("InstanceContextMode"),
                typeof(ServiceBehaviorAttribute).GetProperty("ConcurrencyMode")
            },
                    new object[]
            {
                InstanceContextMode.Single,
                ConcurrencyMode.Multiple
            }));

            var hi   = si.DefineField("_HostInstance", _UserServiceContract, FieldAttributes.Private);
            var func = si.DefineField("_ProcessResolver", typeof(Func <,>).MakeGenericType(typeof(int), _SubprocessType), FieldAttributes.Private);

            {
                var ctor = si.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.Standard, new[] { hi.FieldType, func.FieldType });
                ctor.DefineParameter(1, ParameterAttributes.None, "hostInstance");
                ctor.DefineParameter(2, ParameterAttributes.None, "processResolver");
                var gen = ctor.GetILGenerator();
                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Ldarg_1);
                gen.Emit(OpCodes.Stfld, hi);
                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Ldarg_2);
                gen.Emit(OpCodes.Stfld, func);
                gen.Emit(OpCodes.Ret);
            }

            foreach (var im in methods)
            {
                var nm = si.DefineMethod(im.Name, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig);
                nm.SetReturnType(im.ReturnType);
                nm.SetParameters(im.Parameters.Where(_ => _.ImplIndex >= 0).Select(_ => _.ParameterType).ToArray());

                foreach (var p in im.Parameters)
                {
                    if (p.ImplIndex >= 0)
                    {
                        nm.DefineParameter(p.ImplIndex + 1, ParameterAttributes.None, p.Name);
                    }
                }

                var gen            = nm.GetILGenerator();
                var lb             = im.Parameters.Any(_ => _.IsInfo) ? gen.DeclareLocal(_SubprocessType) : null;
                var implParamCount = im.Parameters.Count(_ => _.ImplIndex >= 0);

                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Ldfld, func);
                gen.EmitLdArg(implParamCount);
                gen.Emit(OpCodes.Callvirt, func.FieldType.GetMethod("Invoke", new[] { typeof(int) }));
                if (lb == null)
                {
                    gen.Emit(OpCodes.Pop);
                }
                else
                {
                    gen.Emit(OpCodes.Stloc_0);
                }
                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Ldfld, hi);

                foreach (var p in im.Parameters)
                {
                    if (p.HostIndex < 0)
                    {
                        continue;
                    }
                    if (p.IsId)
                    {
                        gen.EmitLdArg(implParamCount);
                    }
                    else if (p.IsInfo)
                    {
                        gen.Emit(OpCodes.Ldloc_0);
                    }
                    else
                    {
                        gen.EmitLdArg(p.ImplIndex + 1);
                    }
                }

                gen.Emit(OpCodes.Callvirt, im.Method);
                gen.Emit(OpCodes.Ret);
            }
            return(si.CreateType());
        }
Esempio n. 32
0
        public DelegateBuilder(ModuleBuilder /*!*/ moduleBuilder)
        {
            Debug.Assert(moduleBuilder != null);

            this.moduleBuilder = moduleBuilder;
        }
Esempio n. 33
0
 /// <summary>
 /// Emits LLVM IR instructions that test if the type corresponding
 /// to a type metadata handle is a subtype of another type.
 /// </summary>
 /// <param name="subtypeMetadata">
 /// A type metadata handle of a potential subtype.
 /// </param>
 /// <param name="supertype">
 /// A potential supertype.
 /// </param>
 /// <param name="module">
 /// The LLVM module to generate the instructions in.
 /// </param>
 /// <param name="builder">
 /// An instruction builder to use for emitting instructions.
 /// </param>
 /// <param name="name">
 /// A suggested name for the resulting Boolean value.
 /// </param>
 /// <returns>
 /// A Boolean value that is <c>true</c> if the type corresponding
 /// to <paramref name="subtypeMetadata"/> is a subtype of <paramref name="supertype"/>;
 /// otherwise, <c>false</c>.
 /// </returns>
 public abstract LLVMValueRef EmitIsSubtype(
     LLVMValueRef subtypeMetadata,
     IType supertype,
     ModuleBuilder module,
     IRBuilder builder,
     string name);
Esempio n. 34
0
		internal override int ImportTo(ModuleBuilder other)
		{
			if (typeBuilder.IsGenericTypeDefinition)
			{
				return other.ImportMember(TypeBuilder.GetMethod(typeBuilder, this));
			}
			else if (other == typeBuilder.ModuleBuilder)
			{
				return pseudoToken;
			}
			else
			{
				return other.ImportMethodOrField(typeBuilder, name, this.MethodSignature);
			}
		}
		private static int WriteMarshallingDescriptor(ModuleBuilder module, CustomAttributeBuilder attribute)
		{
			UnmanagedType unmanagedType;
			object val = attribute.GetConstructorArgument(0);
			if (val is short)
			{
				unmanagedType = (UnmanagedType)(short)val;
			}
			else if (val is int)
			{
				unmanagedType = (UnmanagedType)(int)val;
			}
			else
			{
				unmanagedType = (UnmanagedType)val;
			}

			ByteBuffer bb = new ByteBuffer(5);
			bb.WriteCompressedUInt((int)unmanagedType);

			if (unmanagedType == UnmanagedType.LPArray)
			{
				UnmanagedType arraySubType = attribute.GetFieldValue<UnmanagedType>("ArraySubType") ?? NATIVE_TYPE_MAX;
				bb.WriteCompressedUInt((int)arraySubType);
				int? sizeParamIndex = attribute.GetFieldValue<short>("SizeParamIndex");
				int? sizeConst = attribute.GetFieldValue<int>("SizeConst");
				if (sizeParamIndex != null)
				{
					bb.WriteCompressedUInt(sizeParamIndex.Value);
					if (sizeConst != null)
					{
						bb.WriteCompressedUInt(sizeConst.Value);
						bb.WriteCompressedUInt(1); // flag that says that SizeParamIndex was specified
					}
				}
				else if (sizeConst != null)
				{
					bb.WriteCompressedUInt(0); // SizeParamIndex
					bb.WriteCompressedUInt(sizeConst.Value);
					bb.WriteCompressedUInt(0); // flag that says that SizeParamIndex was not specified
				}
			}
			else if (unmanagedType == UnmanagedType.SafeArray)
			{
				VarEnum? safeArraySubType = attribute.GetFieldValue<VarEnum>("SafeArraySubType");
				if (safeArraySubType != null)
				{
					bb.WriteCompressedUInt((int)safeArraySubType);
					Type safeArrayUserDefinedSubType = (Type)attribute.GetFieldValue("SafeArrayUserDefinedSubType");
					if (safeArrayUserDefinedSubType != null)
					{
						WriteType(module, bb, safeArrayUserDefinedSubType);
					}
				}
			}
			else if (unmanagedType == UnmanagedType.ByValArray)
			{
				bb.WriteCompressedUInt(attribute.GetFieldValue<int>("SizeConst") ?? 1);
				UnmanagedType? arraySubType = attribute.GetFieldValue<UnmanagedType>("ArraySubType");
				if (arraySubType != null)
				{
					bb.WriteCompressedUInt((int)arraySubType);
				}
			}
			else if (unmanagedType == UnmanagedType.ByValTStr)
			{
				bb.WriteCompressedUInt(attribute.GetFieldValue<int>("SizeConst").Value);
			}
			else if (unmanagedType == UnmanagedType.Interface
				|| unmanagedType == UnmanagedType.IDispatch
				|| unmanagedType == UnmanagedType.IUnknown)
			{
				int? iidParameterIndex = attribute.GetFieldValue<int>("IidParameterIndex");
				if (iidParameterIndex != null)
				{
					bb.WriteCompressedUInt(iidParameterIndex.Value);
				}
			}
			else if (unmanagedType == UnmanagedType.CustomMarshaler)
			{
				bb.WriteCompressedUInt(0);
				bb.WriteCompressedUInt(0);
				string marshalType = (string)attribute.GetFieldValue("MarshalType");
				if (marshalType != null)
				{
					WriteString(bb, marshalType);
				}
				else
				{
					WriteType(module, bb, (Type)attribute.GetFieldValue("MarshalTypeRef"));
				}
				WriteString(bb, (string)attribute.GetFieldValue("MarshalCookie") ?? "");
			}

			return module.Blobs.Add(bb);
		}
Esempio n. 36
0
		internal void WriteMethodRefSig(ModuleBuilder module, ByteBuffer bb, Type[] optionalParameterTypes)
		{
			WriteSigImpl(module, bb, parameterTypes.Length + optionalParameterTypes.Length);
			if (optionalParameterTypes.Length > 0)
			{
				bb.Write(SENTINEL);
				foreach (Type type in optionalParameterTypes)
				{
					WriteType(module, bb, type);
				}
			}
		}
Esempio n. 37
0
 /// <summary>
 /// Gets the type of a type metadata handle.
 /// </summary>
 /// <param name="module">A module.</param>
 /// <returns>The type of a type metadata handle.</returns>
 public abstract LLVMTypeRef GetMetadataType(ModuleBuilder module);
        private static int WriteMarshallingDescriptor(ModuleBuilder module, CustomAttributeBuilder attribute)
        {
            UnmanagedType unmanagedType;
            object        val = attribute.GetConstructorArgument(0);

            if (val is short)
            {
                unmanagedType = (UnmanagedType)(short)val;
            }
            else if (val is int)
            {
                unmanagedType = (UnmanagedType)(int)val;
            }
            else
            {
                unmanagedType = (UnmanagedType)val;
            }

            ByteBuffer bb = new ByteBuffer(5);

            bb.WriteCompressedUInt((int)unmanagedType);

            if (unmanagedType == UnmanagedType.LPArray)
            {
                UnmanagedType arraySubType = attribute.GetFieldValue <UnmanagedType>("ArraySubType") ?? NATIVE_TYPE_MAX;
                bb.WriteCompressedUInt((int)arraySubType);
                int?sizeParamIndex = attribute.GetFieldValue <short>("SizeParamIndex");
                int?sizeConst      = attribute.GetFieldValue <int>("SizeConst");
                if (sizeParamIndex != null)
                {
                    bb.WriteCompressedUInt(sizeParamIndex.Value);
                    if (sizeConst != null)
                    {
                        bb.WriteCompressedUInt(sizeConst.Value);
                        bb.WriteCompressedUInt(1); // flag that says that SizeParamIndex was specified
                    }
                }
                else if (sizeConst != null)
                {
                    bb.WriteCompressedUInt(0); // SizeParamIndex
                    bb.WriteCompressedUInt(sizeConst.Value);
                    bb.WriteCompressedUInt(0); // flag that says that SizeParamIndex was not specified
                }
            }
            else if (unmanagedType == UnmanagedType.SafeArray)
            {
                VarEnum?safeArraySubType = attribute.GetFieldValue <VarEnum>("SafeArraySubType");
                if (safeArraySubType != null)
                {
                    bb.WriteCompressedUInt((int)safeArraySubType);
                    Type safeArrayUserDefinedSubType = (Type)attribute.GetFieldValue("SafeArrayUserDefinedSubType");
                    if (safeArrayUserDefinedSubType != null)
                    {
                        WriteType(module, bb, safeArrayUserDefinedSubType);
                    }
                }
            }
            else if (unmanagedType == UnmanagedType.ByValArray)
            {
                bb.WriteCompressedUInt(attribute.GetFieldValue <int>("SizeConst") ?? 1);
                UnmanagedType?arraySubType = attribute.GetFieldValue <UnmanagedType>("ArraySubType");
                if (arraySubType != null)
                {
                    bb.WriteCompressedUInt((int)arraySubType);
                }
            }
            else if (unmanagedType == UnmanagedType.ByValTStr)
            {
                bb.WriteCompressedUInt(attribute.GetFieldValue <int>("SizeConst").Value);
            }
            else if (unmanagedType == UnmanagedType.Interface ||
                     unmanagedType == UnmanagedType.IDispatch ||
                     unmanagedType == UnmanagedType.IUnknown)
            {
                int?iidParameterIndex = attribute.GetFieldValue <int>("IidParameterIndex");
                if (iidParameterIndex != null)
                {
                    bb.WriteCompressedUInt(iidParameterIndex.Value);
                }
            }
            else if (unmanagedType == UnmanagedType_CustomMarshaler)
            {
                bb.WriteCompressedUInt(0);
                bb.WriteCompressedUInt(0);
                string marshalType = (string)attribute.GetFieldValue("MarshalType");
                if (marshalType != null)
                {
                    WriteString(bb, marshalType);
                }
                else
                {
                    WriteType(module, bb, (Type)attribute.GetFieldValue("MarshalTypeRef"));
                }
                WriteString(bb, (string)attribute.GetFieldValue("MarshalCookie") ?? "");
            }

            return(module.Blobs.Add(bb));
        }
Esempio n. 39
0
 public static TypeBuilder DefineStaticType(this ModuleBuilder builder)
 {
     return(builder.DefineType(Guid.NewGuid().ToString("N"),
                               TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.AutoClass |
                               TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit));
 }
		internal abstract void WriteSig(ModuleBuilder module, ByteBuffer bb);
Esempio n. 41
0
		internal override int ImportTo(ModuleBuilder module)
		{
			return module.ImportMember(methodBuilder);
		}
Esempio n. 42
0
        public unsafe static IntPtr getAdrressWithMSIL(byte[] syscall)
        {
            //begin memcopy en msil
            AppDomain       appD       = AppDomain.CurrentDomain;
            AssemblyName    assName    = new AssemblyName("MethodSmasher");
            AssemblyBuilder assBuilder = appD.DefineDynamicAssembly(assName, AssemblyBuilderAccess.Run);
            AllowPartiallyTrustedCallersAttribute attr = new AllowPartiallyTrustedCallersAttribute();
            ConstructorInfo csInfo = attr.GetType().GetConstructors()[0];

            object[] obArray = new object[0];
            CustomAttributeBuilder cAttrB = new CustomAttributeBuilder(csInfo, obArray);

            assBuilder.SetCustomAttribute(cAttrB);
            ModuleBuilder             mBuilder = assBuilder.DefineDynamicModule("MethodSmasher");
            UnverifiableCodeAttribute codAttr  = new UnverifiableCodeAttribute();

            csInfo = codAttr.GetType().GetConstructors()[0];
            CustomAttributeBuilder modCAttrB = new CustomAttributeBuilder(csInfo, obArray);

            mBuilder.SetCustomAttribute(modCAttrB);
            TypeBuilder tBuilder = mBuilder.DefineType("MethodSmasher", TypeAttributes.Public);

            Type[]        allParams     = { typeof(IntPtr), typeof(IntPtr), typeof(Int32) };
            MethodBuilder methodBuilder = tBuilder.DefineMethod("OverwriteMethod", MethodAttributes.Public | MethodAttributes.Static, null, allParams);
            ILGenerator   generator     = methodBuilder.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldarg_1);
            generator.Emit(OpCodes.Ldarg_2);
            generator.Emit(OpCodes.Volatile);
            generator.Emit(OpCodes.Cpblk);
            generator.Emit(OpCodes.Ret);

            var smasherType     = tBuilder.CreateType();
            var overWriteMethod = smasherType.GetMethod("OverwriteMethod");

            //end memcopy en msil

            //begin xor dummy method
            appD       = AppDomain.CurrentDomain;
            assName    = new AssemblyName("SmashMe");
            assBuilder = appD.DefineDynamicAssembly(assName, AssemblyBuilderAccess.Run);
            attr       = new AllowPartiallyTrustedCallersAttribute();
            csInfo     = attr.GetType().GetConstructors()[0];
            obArray    = new object[0];
            cAttrB     = new CustomAttributeBuilder(csInfo, obArray);
            assBuilder.SetCustomAttribute(cAttrB);
            mBuilder  = assBuilder.DefineDynamicModule("SmashMe");
            codAttr   = new UnverifiableCodeAttribute();
            csInfo    = codAttr.GetType().GetConstructors()[0];
            modCAttrB = new CustomAttributeBuilder(csInfo, obArray);
            mBuilder.SetCustomAttribute(modCAttrB);
            tBuilder = mBuilder.DefineType("SmashMe", TypeAttributes.Public);
            Int32 xorK = 0x41424344;

            Type[] allParams2 = { typeof(Int32) };
            methodBuilder = tBuilder.DefineMethod("OverwriteMe", MethodAttributes.Public | MethodAttributes.Static, typeof(Int32), allParams2);
            generator     = methodBuilder.GetILGenerator();
            generator.DeclareLocal(typeof(Int32));
            generator.Emit(OpCodes.Ldarg_0);

            for (var x = 0; x < 13000; x++)
            {
                generator.Emit(OpCodes.Ldc_I4, xorK);
                generator.Emit(OpCodes.Xor);
                generator.Emit(OpCodes.Stloc_0);
                generator.Emit(OpCodes.Ldloc_0);
            }

            generator.Emit(OpCodes.Ldc_I4, xorK);
            generator.Emit(OpCodes.Xor);
            generator.Emit(OpCodes.Ret);

            var smashmeType       = tBuilder.CreateType();
            var overwriteMeMethod = smashmeType.GetMethod("OverwriteMe");

            //end xor dummy method

            //jit the xor method
            for (var x = 0; x < 40; x++)
            {
                try
                {
                    var i = overwriteMeMethod.Invoke(null, new object[] { 0x11112222 });
                }
                catch (Exception e)
                {
                    if (e.InnerException != null)
                    {
                        string err = e.InnerException.Message;
                    }
                }
            }

            byte[] trap;


            if (IntPtr.Size == 4)
            {
                //32bits shcode
                trap = new byte[] { 0x90 };
            }
            else
            {
                //64bits shcode
                trap = new byte[] { 0x90 };
            }

            byte[] finalShellcode = new byte[trap.Length + syscall.Length];
            Buffer.BlockCopy(trap, 0, finalShellcode, 0, trap.Length);
            Buffer.BlockCopy(syscall, 0, finalShellcode, trap.Length, syscall.Length);

            IntPtr shellcodeAddress = Marshal.AllocHGlobal(finalShellcode.Length);

            Marshal.Copy(finalShellcode, 0, shellcodeAddress, finalShellcode.Length);

            IntPtr targetMethodAddress = getMethodAddress(overwriteMeMethod);

            object[] owParams = new object[] { targetMethodAddress, shellcodeAddress, finalShellcode.Length };
            try
            {
                overWriteMethod.Invoke(null, owParams);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    string err = e.InnerException.Message;
                }
            }

            return(targetMethodAddress);
        }
Esempio n. 43
0
    public static void Main()
    {
        // Define a dynamic assembly to contain the sample type. The
        // assembly will not be run, but only saved to disk, so
        // AssemblyBuilderAccess.Save is specified.
        //
        //<Snippet2>
        AppDomain       myDomain   = AppDomain.CurrentDomain;
        AssemblyName    myAsmName  = new AssemblyName("GenericEmitExample1");
        AssemblyBuilder myAssembly =
            myDomain.DefineDynamicAssembly(myAsmName,
                                           AssemblyBuilderAccess.RunAndSave);
        //</Snippet2>

        // An assembly is made up of executable modules. For a single-
        // module assembly, the module name and file name are the same
        // as the assembly name.
        //
        //<Snippet3>
        ModuleBuilder myModule =
            myAssembly.DefineDynamicModule(myAsmName.Name,
                                           myAsmName.Name + ".dll");
        //</Snippet3>

        // Get type objects for the base class trivial interfaces to
        // be used as constraints.
        //
        Type baseType   = typeof(ExampleBase);
        Type interfaceA = typeof(IExampleA);
        Type interfaceB = typeof(IExampleB);

        // Define the sample type.
        //
        //<Snippet4>
        TypeBuilder myType =
            myModule.DefineType("Sample", TypeAttributes.Public);

        //</Snippet4>

        Console.WriteLine("Type 'Sample' is generic: {0}",
                          myType.IsGenericType);

        // Define type parameters for the type. Until you do this,
        // the type is not generic, as the preceding and following
        // WriteLine statements show. The type parameter names are
        // specified as an array of strings. To make the code
        // easier to read, each GenericTypeParameterBuilder is placed
        // in a variable with the same name as the type parameter.
        //
        //<Snippet5>
        string[] typeParamNames = { "TFirst", "TSecond" };
        GenericTypeParameterBuilder[] typeParams =
            myType.DefineGenericParameters(typeParamNames);

        GenericTypeParameterBuilder TFirst  = typeParams[0];
        GenericTypeParameterBuilder TSecond = typeParams[1];

        //</Snippet5>

        Console.WriteLine("Type 'Sample' is generic: {0}",
                          myType.IsGenericType);

        // Apply constraints to the type parameters.
        //
        // A type that is substituted for the first parameter, TFirst,
        // must be a reference type and must have a parameterless
        // constructor.
        //<Snippet6>
        TFirst.SetGenericParameterAttributes(
            GenericParameterAttributes.DefaultConstructorConstraint |
            GenericParameterAttributes.ReferenceTypeConstraint);
        //</Snippet6>

        // A type that is substituted for the second type
        // parameter must implement IExampleA and IExampleB, and
        // inherit from the trivial test class ExampleBase. The
        // interface constraints are specified as an array
        // containing the interface types.
        //<Snippet7>
        TSecond.SetBaseTypeConstraint(baseType);
        Type[] interfaceTypes = { interfaceA, interfaceB };
        TSecond.SetInterfaceConstraints(interfaceTypes);
        //</Snippet7>

        // The following code adds a private field named ExampleField,
        // of type TFirst.
        //<Snippet21>
        FieldBuilder exField =
            myType.DefineField("ExampleField", TFirst,
                               FieldAttributes.Private);
        //</Snippet21>

        // Define a static method that takes an array of TFirst and
        // returns a List<TFirst> containing all the elements of
        // the array. To define this method it is necessary to create
        // the type List<TFirst> by calling MakeGenericType on the
        // generic type definition, List<T>. (The T is omitted with
        // the typeof operator when you get the generic type
        // definition.) The parameter type is created by using the
        // MakeArrayType method.
        //
        //<Snippet22>
        Type listOf       = typeof(List <>);
        Type listOfTFirst = listOf.MakeGenericType(TFirst);

        Type[] mParamTypes = { TFirst.MakeArrayType() };

        MethodBuilder exMethod =
            myType.DefineMethod("ExampleMethod",
                                MethodAttributes.Public | MethodAttributes.Static,
                                listOfTFirst,
                                mParamTypes);
        //</Snippet22>

        // Emit the method body.
        // The method body consists of just three opcodes, to load
        // the input array onto the execution stack, to call the
        // List<TFirst> constructor that takes IEnumerable<TFirst>,
        // which does all the work of putting the input elements into
        // the list, and to return, leaving the list on the stack. The
        // hard work is getting the constructor.
        //
        // The GetConstructor method is not supported on a
        // GenericTypeParameterBuilder, so it is not possible to get
        // the constructor of List<TFirst> directly. There are two
        // steps, first getting the constructor of List<T> and then
        // calling a method that converts it to the corresponding
        // constructor of List<TFirst>.
        //
        // The constructor needed here is the one that takes an
        // IEnumerable<T>. Note, however, that this is not the
        // generic type definition of IEnumerable<T>; instead, the
        // T from List<T> must be substituted for the T of
        // IEnumerable<T>. (This seems confusing only because both
        // types have type parameters named T. That is why this example
        // uses the somewhat silly names TFirst and TSecond.) To get
        // the type of the constructor argument, take the generic
        // type definition IEnumerable<T> (expressed as
        // IEnumerable<> when you use the typeof operator) and
        // call MakeGenericType with the first generic type parameter
        // of List<T>. The constructor argument list must be passed
        // as an array, with just one argument in this case.
        //
        // Now it is possible to get the constructor of List<T>,
        // using GetConstructor on the generic type definition. To get
        // the constructor of List<TFirst>, pass List<TFirst> and
        // the constructor from List<T> to the static
        // TypeBuilder.GetConstructor method.
        //
        //<Snippet23>
        ILGenerator ilgen = exMethod.GetILGenerator();

        Type ienumOf     = typeof(IEnumerable <>);
        Type TfromListOf = listOf.GetGenericArguments()[0];
        Type ienumOfT    = ienumOf.MakeGenericType(TfromListOf);

        Type[] ctorArgs = { ienumOfT };

        ConstructorInfo ctorPrep = listOf.GetConstructor(ctorArgs);
        ConstructorInfo ctor     =
            TypeBuilder.GetConstructor(listOfTFirst, ctorPrep);

        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Newobj, ctor);
        ilgen.Emit(OpCodes.Ret);
        //</Snippet23>

        // Create the type and save the assembly.
        //<Snippet8>
        Type finished = myType.CreateType();

        myAssembly.Save(myAsmName.Name + ".dll");
        //</Snippet8>

        // Invoke the method.
        // ExampleMethod is not generic, but the type it belongs to is
        // generic, so in order to get a MethodInfo that can be invoked
        // it is necessary to create a constructed type. The Example
        // class satisfies the constraints on TFirst, because it is a
        // reference type and has a default constructor. In order to
        // have a class that satisfies the constraints on TSecond,
        // this code example defines the ExampleDerived type. These
        // two types are passed to MakeGenericMethod to create the
        // constructed type.
        //
        //<Snippet9>
        Type[]     typeArgs    = { typeof(Example), typeof(ExampleDerived) };
        Type       constructed = finished.MakeGenericType(typeArgs);
        MethodInfo mi          = constructed.GetMethod("ExampleMethod");

        //</Snippet9>

        // Create an array of Example objects, as input to the generic
        // method. This array must be passed as the only element of an
        // array of arguments. The first argument of Invoke is
        // null, because ExampleMethod is static. Display the count
        // on the resulting List<Example>.
        //
        //<Snippet10>
        Example[] input     = { new Example(), new Example() };
        object[]  arguments = { input };

        List <Example> listX =
            (List <Example>)mi.Invoke(null, arguments);

        Console.WriteLine(
            "\nThere are {0} elements in the List<Example>.",
            listX.Count);
        //</Snippet10>

        DisplayGenericParameters(finished);
    }
Esempio n. 44
0
 public override void Compile(ModuleBuilder builder)
 {
 }
Esempio n. 45
0
 static TypeBuilder smethod_29(ModuleBuilder moduleBuilder_0, string string_0, TypeAttributes typeAttributes_0, Type type_0)
 {
     return(moduleBuilder_0.DefineType(string_0, typeAttributes_0, type_0));
 }
Esempio n. 46
0
        /// <summary>
        /// 调用所设定的函数
        /// </summary>
        /// <param name="ObjArray_Parameter"> 实参 </param>
        /// <param name="TypeArray_ParameterType"> 实参类型 </param>
        /// <param name="ModePassArray_Parameter"> 实参传送方式 </param>
        /// <param name="Type_Return"> 返回类型 </param>
        /// <returns> 返回所调用函数的 object</returns>
        public object Invoke(object[] ObjArray_Parameter, Type[] TypeArray_ParameterType, ModePass[] ModePassArray_Parameter, Type Type_Return)
        {
            // 下面 3 个 if 是进行安全检查 , 若不能通过 , 则抛出异常
            if (hModule == IntPtr.Zero)
            {
                throw (new Exception(" 函数库模块的句柄为空 , 请确保已进行 LoadDll 操作 !"));
            }
            if (farProc == IntPtr.Zero)
            {
                throw (new Exception(" 函数指针为空 , 请确保已进行 LoadFun 操作 !"));
            }
            if (ObjArray_Parameter.Length != ModePassArray_Parameter.Length)
            {
                throw (new Exception(" 参数个数及其传递方式的个数不匹配 ."));
            }
            // 下面是创建 MyAssemblyName 对象并设置其 Name 属性
            AssemblyName MyAssemblyName = new AssemblyName();

            MyAssemblyName.Name = "InvokeFun";
            // 生成单模块配件
            AssemblyBuilder MyAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(MyAssemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder   MyModuleBuilder   = MyAssemblyBuilder.DefineDynamicModule("InvokeDll");
            // 定义要调用的方法 , 方法名为“ MyFun ”,返回类型是“ Type_Return ”参数类型是“ TypeArray_ParameterType ”
            MethodBuilder MyMethodBuilder = MyModuleBuilder.DefineGlobalMethod("MyFun", MethodAttributes.Public | MethodAttributes.Static, Type_Return, TypeArray_ParameterType);
            // 获取一个 ILGenerator ,用于发送所需的 IL
            ILGenerator IL = MyMethodBuilder.GetILGenerator();
            int         i;

            for (i = 0; i < ObjArray_Parameter.Length; i++)
            {// 用循环将参数依次压入堆栈
                switch (ModePassArray_Parameter[i])
                {
                case ModePass.ByValue:
                    IL.Emit(OpCodes.Ldarg, i);
                    break;

                case ModePass.ByRef:
                    IL.Emit(OpCodes.Ldarga, i);
                    break;

                default:
                    throw (new Exception(" 第 " + (i + 1).ToString() + " 个参数没有给定正确的传递方式 ."));
                }
            }
            if (IntPtr.Size == 4)
            {// 判断处理器类型
                IL.Emit(OpCodes.Ldc_I4, farProc.ToInt32());
            }
            else if (IntPtr.Size == 8)
            {
                IL.Emit(OpCodes.Ldc_I8, farProc.ToInt64());
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
            IL.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, Type_Return, TypeArray_ParameterType);
            IL.Emit(OpCodes.Ret); // 返回值
            MyModuleBuilder.CreateGlobalFunctions();
            // 取得方法信息
            MethodInfo MyMethodInfo = MyModuleBuilder.GetMethod("MyFun");

            return(MyMethodInfo.Invoke(null, ObjArray_Parameter));// 调用方法,并返回其值
        }
Esempio n. 47
0
		private int AddFile(ModuleBuilder manifestModule, string fileName, int flags)
		{
			SHA1Managed hash = new SHA1Managed();
			string fullPath = fileName;
			if (dir != null)
			{
				fullPath = Path.Combine(dir, fileName);
			}
			using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read))
			{
				using (CryptoStream cs = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write))
				{
					byte[] buf = new byte[8192];
					ModuleWriter.HashChunk(fs, cs, buf, (int)fs.Length);
				}
			}
			return manifestModule.__AddModule(flags, Path.GetFileName(fileName), hash.Hash);
		}
    public static void Main()
    {
        // Define a dynamic assembly to contain the sample type. The
        // assembly will not be run, but only saved to disk, so
        // AssemblyBuilderAccess.Save is specified.
        //
        AppDomain       myDomain   = AppDomain.CurrentDomain;
        AssemblyName    myAsmName  = new AssemblyName("MakeXxxTypeExample");
        AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(
            myAsmName,
            AssemblyBuilderAccess.Save);

        // An assembly is made up of executable modules. For a single-
        // module assembly, the module name and file name are the same
        // as the assembly name.
        //
        ModuleBuilder myModule = myAssembly.DefineDynamicModule(
            myAsmName.Name,
            myAsmName.Name + ".dll");

        // Define the sample type.
        TypeBuilder myType = myModule.DefineType(
            "Sample",
            TypeAttributes.Public | TypeAttributes.Abstract);

        // Define a method that takes a ref argument of type Sample,
        // a pointer to type Sample, and an array of Sample objects. The
        // method returns a two-dimensional array of Sample objects.
        //
        // To create this method, you need Type objects that represent the
        // parameter types and the return type. Use the MakeByRefType,
        // MakePointerType, and MakeArrayType methods to create the Type
        // objects.
        //
        Type byRefMyType       = myType.MakeByRefType();
        Type pointerMyType     = myType.MakePointerType();
        Type arrayMyType       = myType.MakeArrayType();
        Type twoDimArrayMyType = myType.MakeArrayType(2);

        // Create the array of parameter types.
        Type[] parameterTypes = { byRefMyType, pointerMyType, arrayMyType };

        // Define the abstract Test method. After you have compiled
        // and run this code example code, you can use ildasm.exe
        // to open MakeXxxTypeExample.dll, examine the Sample type,
        // and verify the parameter types and return type of the
        // TestMethod method.
        //
        MethodBuilder myMethodBuilder = myType.DefineMethod(
            "TestMethod",
            MethodAttributes.Abstract | MethodAttributes.Virtual
            | MethodAttributes.Public,
            twoDimArrayMyType,
            parameterTypes);

        // Create the type and save the assembly. For a single-file
        // assembly, there is only one module to store the manifest
        // information in.
        //
        myType.CreateType();
        myAssembly.Save(myAsmName.Name + ".dll");
    }
    public static void Main()
    {
        // Create an assembly.
        AssemblyName myAssemblyName = new AssemblyName();

        myAssemblyName.Name = "SampleAssembly";

        AssemblyBuilder myAssembly =
            Thread.GetDomain().DefineDynamicAssembly(myAssemblyName,
                                                     AssemblyBuilderAccess.RunAndSave);

        // Create a module. For a single-file assembly the module
        // name is usually the same as the assembly name.
        ModuleBuilder myModule =
            myAssembly.DefineDynamicModule(myAssemblyName.Name,
                                           myAssemblyName.Name + ".dll", true);

        // Define a public class 'Example'.
        TypeBuilder myTypeBuilder =
            myModule.DefineType("Example", TypeAttributes.Public);

        // Create the 'Function1' public method, which takes an integer
        // and returns a string.
        MethodBuilder myMethod = myTypeBuilder.DefineMethod("Function1",
                                                            MethodAttributes.Public | MethodAttributes.Static,
                                                            typeof(String), new Type[] { typeof(int) });

        // Generate IL for 'Function1'. The function body demonstrates
        // assigning an argument to a local variable, assigning a
        // constant string to a local variable, and putting the contents
        // of local variables on the stack.
        ILGenerator myMethodIL = myMethod.GetILGenerator();

        // Create local variables named myString and myInt.
        LocalBuilder myLB1 = myMethodIL.DeclareLocal(typeof(string));

        myLB1.SetLocalSymInfo("myString");
        Console.WriteLine("local 'myString' type is: {0}", myLB1.LocalType);

        LocalBuilder myLB2 = myMethodIL.DeclareLocal(typeof(int));

        myLB2.SetLocalSymInfo("myInt", 1, 2);
        Console.WriteLine("local 'myInt' type is: {0}", myLB2.LocalType);

        // Store the function argument in myInt.
        myMethodIL.Emit(OpCodes.Ldarg_0);
        myMethodIL.Emit(OpCodes.Stloc_1);

        // Store a literal value in myString, and return the value.
        myMethodIL.Emit(OpCodes.Ldstr, "string value");
        myMethodIL.Emit(OpCodes.Stloc_0);
        myMethodIL.Emit(OpCodes.Ldloc_0);
        myMethodIL.Emit(OpCodes.Ret);

        // Create "Example" class.
        Type myType1 = myTypeBuilder.CreateType();

        Console.WriteLine("'Example' is created.");

        myAssembly.Save(myAssemblyName.Name + ".dll");
        Console.WriteLine("'{0}' is created.", myAssemblyName.Name + ".dll");

        // Invoke 'Function1' method of 'Example', passing the value 42.
        Object myObject2 = myType1.InvokeMember("Function1",
                                                BindingFlags.InvokeMethod, null, null, new Object[] { 42 });

        Console.WriteLine("Example.Function1 returned: {0}", myObject2);
    }
Esempio n. 50
0
    public static Type DynamicDotProductGen()
    {
        Type ivType = null;

        Type[] ctorParams = new Type[] { typeof(int),
                                         typeof(int),
                                         typeof(int) };

        AppDomain    myDomain  = Thread.GetDomain();
        AssemblyName myAsmName = new AssemblyName();

        myAsmName.Name = "IntVectorAsm";

        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
            myAsmName,
            AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder IntVectorModule = myAsmBuilder.DefineDynamicModule("IntVectorModule",
                                                                         "Vector.dll");

        TypeBuilder ivTypeBld = IntVectorModule.DefineType("IntVector",
                                                           TypeAttributes.Public);

        FieldBuilder xField = ivTypeBld.DefineField("x", typeof(int),
                                                    FieldAttributes.Private);
        FieldBuilder yField = ivTypeBld.DefineField("y", typeof(int),
                                                    FieldAttributes.Private);
        FieldBuilder zField = ivTypeBld.DefineField("z", typeof(int),
                                                    FieldAttributes.Private);

        Type            objType = Type.GetType("System.Object");
        ConstructorInfo objCtor = objType.GetConstructor(new Type[0]);

        ConstructorBuilder ivCtor = ivTypeBld.DefineConstructor(
            MethodAttributes.Public,
            CallingConventions.Standard,
            ctorParams);
        ILGenerator ctorIL = ivCtor.GetILGenerator();

        ctorIL.Emit(OpCodes.Ldarg_0);
        ctorIL.Emit(OpCodes.Call, objCtor);
        ctorIL.Emit(OpCodes.Ldarg_0);
        ctorIL.Emit(OpCodes.Ldarg_1);
        ctorIL.Emit(OpCodes.Stfld, xField);
        ctorIL.Emit(OpCodes.Ldarg_0);
        ctorIL.Emit(OpCodes.Ldarg_2);
        ctorIL.Emit(OpCodes.Stfld, yField);
        ctorIL.Emit(OpCodes.Ldarg_0);
        ctorIL.Emit(OpCodes.Ldarg_3);
        ctorIL.Emit(OpCodes.Stfld, zField);
        ctorIL.Emit(OpCodes.Ret);

        // This method will find the dot product of the stored vector
        // with another.

        Type[] dpParams = new Type[] { ivTypeBld };

        // Here, you create a MethodBuilder containing the
        // name, the attributes (public, static, private, and so on),
        // the return type (int, in this case), and a array of Type
        // indicating the type of each parameter. Since the sole parameter
        // is a IntVector, the very class you're creating, you will
        // pass in the TypeBuilder (which is derived from Type) instead of
        // a Type object for IntVector, avoiding an exception.

        // -- This method would be declared in C# as:
        //    public int DotProduct(IntVector aVector)

        MethodBuilder dotProductMthd = ivTypeBld.DefineMethod(
            "DotProduct",
            MethodAttributes.Public,
            typeof(int),
            dpParams);

        // A ILGenerator can now be spawned, attached to the MethodBuilder.

        ILGenerator mthdIL = dotProductMthd.GetILGenerator();

        // Here's the body of our function, in MSIL form. We're going to find the
        // "dot product" of the current vector instance with the passed vector
        // instance. For reference purposes, the equation is:
        // (x1 * x2) + (y1 * y2) + (z1 * z2) = the dot product

        // First, you'll load the reference to the current instance "this"
        // stored in argument 0 (ldarg.0) onto the stack. Ldfld, the subsequent
        // instruction, will pop the reference off the stack and look up the
        // field "x", specified by the FieldInfo token "xField".

        mthdIL.Emit(OpCodes.Ldarg_0);
        mthdIL.Emit(OpCodes.Ldfld, xField);

        // That completed, the value stored at field "x" is now atop the stack.
        // Now, you'll do the same for the object reference we passed as a
        // parameter, stored in argument 1 (ldarg.1). After Ldfld executed,
        // you'll have the value stored in field "x" for the passed instance
        // atop the stack.

        mthdIL.Emit(OpCodes.Ldarg_1);
        mthdIL.Emit(OpCodes.Ldfld, xField);

        // There will now be two values atop the stack - the "x" value for the
        // current vector instance, and the "x" value for the passed instance.
        // You'll now multiply them, and push the result onto the evaluation stack.

        mthdIL.Emit(OpCodes.Mul_Ovf_Un);

        // Now, repeat this for the "y" fields of both vectors.

        mthdIL.Emit(OpCodes.Ldarg_0);
        mthdIL.Emit(OpCodes.Ldfld, yField);
        mthdIL.Emit(OpCodes.Ldarg_1);
        mthdIL.Emit(OpCodes.Ldfld, yField);
        mthdIL.Emit(OpCodes.Mul_Ovf_Un);

        // At this time, the results of both multiplications should be atop
        // the stack. You'll now add them and push the result onto the stack.

        mthdIL.Emit(OpCodes.Add_Ovf_Un);

        // Multiply both "z" field and push the result onto the stack.
        mthdIL.Emit(OpCodes.Ldarg_0);
        mthdIL.Emit(OpCodes.Ldfld, zField);
        mthdIL.Emit(OpCodes.Ldarg_1);
        mthdIL.Emit(OpCodes.Ldfld, zField);
        mthdIL.Emit(OpCodes.Mul_Ovf_Un);

        // Finally, add the result of multiplying the "z" fields with the
        // result of the earlier addition, and push the result - the dot product -
        // onto the stack.
        mthdIL.Emit(OpCodes.Add_Ovf_Un);

        // The "ret" opcode will pop the last value from the stack and return it
        // to the calling method. You're all done!

        mthdIL.Emit(OpCodes.Ret);

        ivType = ivTypeBld.CreateType();

        return(ivType);
    }
		internal static void SetMarshalAsAttribute(ModuleBuilder module, int token, CustomAttributeBuilder attribute)
		{
			attribute = attribute.DecodeBlob(module.Assembly);
			FieldMarshalTable.Record rec = new FieldMarshalTable.Record();
			rec.Parent = token;
			rec.NativeType = WriteMarshallingDescriptor(module, attribute);
			module.FieldMarshal.AddRecord(rec);
		}
Esempio n. 52
0
        private Assembly ProcessStructureAssembly(string structureName)
        {
            string location       = _cacheLocation + structureName + ".dll";
            string upperVersion   = structureName.ToUpper();
            string lowerVersion   = structureName.ToLower();
            string profileVersion = "_" + upperVersion;

            if (_structureDictionary.ContainsKey(structureName))
            {
                return(_structureDictionary[structureName]);
            }
            FileInfo fiCheck = new FileInfo(location);

            if (fiCheck.Exists)
            {
                var dll = Assembly.LoadFile(location);
                if (dll != null)
                {
                    _structureDictionary.Add(structureName, dll);
                    return(dll);
                }
                return(null);
            }
            AppDomain       myDomain        = AppDomain.CurrentDomain;
            AssemblyName    assemblyName    = new AssemblyName(structureName + "Assembly");
            AssemblyBuilder assemblyBuilder = myDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
            ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule(structureName + "Module", structureName + ".dll");
            TypeBuilder     typeBuilder     = moduleBuilder.DefineType("liveforensics." + upperVersion, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.ExplicitLayout | TypeAttributes.BeforeFieldInit | TypeAttributes.AnsiClass, typeof(ValueType), PackingSize.Size1);
            List <Tuple <int, string, string, int> > entryList = new List <Tuple <int, string, string, int> >();
            FileInfo fi = new FileInfo(_profileRoot + @"v1.0\nt\GUID\" + _requestedImage);

            if (fi.Exists)
            {
                try
                {
                    byte[] json = null;
                    using (FileStream original = fi.OpenRead())
                    {
                        using (GZipStream gzStream = new GZipStream(original, CompressionMode.Decompress))
                        {
                            MemoryStream final = new MemoryStream();
                            gzStream.CopyTo(final);
                            long len = final.Length;
                            json = final.ToArray();
                        }
                    }
                    string theJson    = Encoding.UTF8.GetString(json);
                    var    parsedJson = JObject.Parse(theJson);
                    foreach (dynamic item in parsedJson["$STRUCTS"][profileVersion][1])
                    {
                        string name = item.Name;
                        var    val  = item.Value;
                        int    w    = (int)val[0];
                        var    v    = val[1];
                        string a    = v[0].ToString();
                        int    size = (int)GetEntrySize(a);
                        if (a == "Array")
                        {
                            int    arraySize = 0;
                            string arrayType = "";
                            foreach (KeyValuePair <string, JToken> k in (JObject)v[1])
                            {
                                if (k.Key == "target")
                                {
                                    arrayType = k.Value.ToString();
                                }
                                if (k.Key == "count")
                                {
                                    arraySize = (int)k.Value;
                                }
                            }
                            size = (int)GetEntrySize(arrayType) * arraySize;
                        }
                        else if (a == "BitField")
                        {
                            foreach (KeyValuePair <string, JToken> k in (JObject)v[1])
                            {
                                if (k.Key == "target")
                                {
                                    size = (int)GetEntrySize(k.Value.ToString());
                                }
                            }
                        }
                        entryList.Add(new Tuple <int, string, string, int>(w, name, a, size));
                    }
                    entryList.Sort();
                    FieldBuilder field = null;
                    foreach (var entry in entryList)
                    {
                        if (GetEntryType(entry.Item3) != null)
                        {
                            field = typeBuilder.DefineField(entry.Item2, GetEntryType(entry.Item3), FieldAttributes.Public);
                            field.SetOffset(entry.Item1);
                        }
                        else if (entry.Item4 == 1)
                        {
                            field = typeBuilder.DefineField(entry.Item2, typeof(byte), FieldAttributes.Public);
                            field.SetOffset(entry.Item1);
                        }
                        else if (entry.Item4 == 2)
                        {
                            field = typeBuilder.DefineField(entry.Item2, typeof(UInt16), FieldAttributes.Public);
                            field.SetOffset(entry.Item1);
                        }
                        else if (entry.Item4 == 4)
                        {
                            field = typeBuilder.DefineField(entry.Item2, typeof(UInt32), FieldAttributes.Public);
                            field.SetOffset(entry.Item1);
                        }
                        else if (entry.Item4 == 8)
                        {
                            field = typeBuilder.DefineField(entry.Item2, typeof(UInt64), FieldAttributes.Public);
                            field.SetOffset(entry.Item1);
                        }
                        else
                        {
                            field = typeBuilder.DefineField(entry.Item2, typeof(byte[]), FieldAttributes.Public);
                            field.SetMarshal(UnmanagedMarshal.DefineByValArray(entry.Item4));
                            field.SetOffset(entry.Item1);
                        }
                    }
                    Type ptType = typeBuilder.CreateType();
                    assemblyBuilder.Save(structureName + ".dll");
                    FileInfo fiMove = new FileInfo(Environment.CurrentDirectory + "\\" + structureName + ".dll");
                    if (fiMove.Exists)
                    {
                        fiMove.MoveTo(location);
                    }
                    var dll = Assembly.LoadFile(location);
                    if (dll != null)
                    {
                        _structureDictionary.Add(structureName, dll);
                        return(dll);
                    }
                    return(null);
                }
                catch (Exception ex)
                {
                    throw new ArgumentException("Error: " + ex.Message);
                }
            }
            return(null);
        }
Esempio n. 53
0
		internal override void WriteSig(ModuleBuilder module, ByteBuffer bb)
		{
			WriteSigImpl(module, bb, parameterTypes.Length);
		}
 public override Type EmitType(ModuleBuilder modelBuilder, Type typeToMake, string nameToUseForType = null)
 => base.EmitType(modelBuilder, typeToMake, "OwneddStateEmitter_" + (string.IsNullOrWhiteSpace(
                                                                         nameToUseForType)
                                                                                ? typeToMake.Name
                                                                                : nameToUseForType));
Esempio n. 55
0
		private void WriteSigImpl(ModuleBuilder module, ByteBuffer bb, int parameterCount)
		{
			byte first;
			if ((callingConvention & CallingConventions.Any) == CallingConventions.VarArgs)
			{
				Debug.Assert(genericParamCount == 0);
				first = VARARG;
			}
			else if (genericParamCount > 0)
			{
				first = GENERIC;
			}
			else
			{
				first = DEFAULT;
			}
			if ((callingConvention & CallingConventions.HasThis) != 0)
			{
				first |= HASTHIS;
			}
			if ((callingConvention & CallingConventions.ExplicitThis) != 0)
			{
				first |= EXPLICITTHIS;
			}
			bb.Write(first);
			if (genericParamCount > 0)
			{
				bb.WriteCompressedInt(genericParamCount);
			}
			bb.WriteCompressedInt(parameterCount);
			// RetType
			if (modifiers != null && modifiers[0] != null)
			{
				WriteCustomModifiers(module, bb, ELEMENT_TYPE_CMOD_OPT, modifiers[0][0]);
				WriteCustomModifiers(module, bb, ELEMENT_TYPE_CMOD_REQD, modifiers[0][1]);
			}
			WriteType(module, bb, returnType);
			// Param
			for (int i = 0; i < parameterTypes.Length; i++)
			{
				if (modifiers != null && modifiers[i + 1] != null)
				{
					WriteCustomModifiers(module, bb, ELEMENT_TYPE_CMOD_OPT, modifiers[i + 1][0]);
					WriteCustomModifiers(module, bb, ELEMENT_TYPE_CMOD_REQD, modifiers[i + 1][1]);
				}
				WriteType(module, bb, parameterTypes[i]);
			}
		}
Esempio n. 56
0
        static TypeAccessor CreateNew(Type type, bool allowNonPublicAccessors)
        {
#if !NO_DYNAMIC
#if WINDOWS_PHONE_APP
            if (typeof(IDynamicMetaObjectProvider).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
#else
            if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
#endif
            {
                return(DynamicAccessor.Singleton);
            }
#endif

#if WINDOWS_PHONE_APP
            PropertyInfo[] props  = type.GetRuntimeProperties().ToArray();
            FieldInfo[]    fields = type.GetRuntimeFields().ToArray();
#else
            PropertyInfo[] props  = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            FieldInfo[]    fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
#endif
            Dictionary <string, int> map     = new Dictionary <string, int>(StringComparer.Ordinal);
            List <MemberInfo>        members = new List <MemberInfo>(props.Length + fields.Length);
            int i = 0;
            foreach (var prop in props)
            {
                if (!map.ContainsKey(prop.Name) && prop.GetIndexParameters().Length == 0)
                {
                    map.Add(prop.Name, i++);
                    members.Add(prop);
                }
            }
            foreach (var field in fields)
            {
                if (!map.ContainsKey(field.Name))
                {
                    map.Add(field.Name, i++); members.Add(field);
                }
            }

            ConstructorInfo ctor = null;
#if WINDOWS_PHONE_APP
            if (type.GetTypeInfo().IsClass&& !type.GetTypeInfo().IsAbstract)
            {
                ctor = type.GetTypeInfo().DeclaredConstructors.FirstOrDefault();
            }
#else
            if (type.IsClass && !type.IsAbstract)
            {
                ctor = type.GetConstructor(Type.EmptyTypes);
            }
#endif
#if !__IOS__ && !WINDOWS_PHONE_APP
            ILGenerator il;
            if (!IsFullyPublic(type, props, allowNonPublicAccessors))
            {
                DynamicMethod dynGetter = new DynamicMethod(type.FullName + "_get", typeof(object), new Type[] { typeof(int), typeof(object) }, type, true),
                              dynSetter = new DynamicMethod(type.FullName + "_set", null, new Type[] { typeof(int), typeof(object), typeof(object) }, type, true);
                WriteMapImpl(dynGetter.GetILGenerator(), type, members, null, allowNonPublicAccessors, true);
                WriteMapImpl(dynSetter.GetILGenerator(), type, members, null, allowNonPublicAccessors, false);
                DynamicMethod dynCtor = null;
                if (ctor != null)
                {
                    dynCtor = new DynamicMethod(type.FullName + "_ctor", typeof(object), Type.EmptyTypes, type, true);
                    il      = dynCtor.GetILGenerator();
                    il.Emit(OpCodes.Newobj, ctor);
                    il.Emit(OpCodes.Ret);
                }
                return(new DelegateAccessor(
                           map,
                           (Func <int, object, object>)dynGetter.CreateDelegate(typeof(Func <int, object, object>)),
                           (Action <int, object, object>)dynSetter.CreateDelegate(typeof(Action <int, object, object>)),
                           dynCtor == null ? null : (Func <object>)dynCtor.CreateDelegate(typeof(Func <object>)), type));
            }
            // note this region is synchronized; only one is being created at a time so we don't need to stress about the builders
            if (assembly == null)
            {
                AssemblyName name = new AssemblyName("FastMember_dynamic");
                assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
                module   = assembly.DefineDynamicModule(name.Name);
            }
            TypeBuilder tb = module.DefineType("FastMember_dynamic." + type.Name + "_" + Interlocked.Increment(ref counter),
                                               (typeof(TypeAccessor).Attributes | TypeAttributes.Sealed | TypeAttributes.Public) & ~(TypeAttributes.Abstract | TypeAttributes.NotPublic), typeof(RuntimeTypeAccessor));

            il = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] {
                typeof(Dictionary <string, int>)
            }).GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            FieldBuilder mapField = tb.DefineField("_map", typeof(Dictionary <string, int>), FieldAttributes.InitOnly | FieldAttributes.Private);
            il.Emit(OpCodes.Stfld, mapField);
            il.Emit(OpCodes.Ret);


            PropertyInfo  indexer = typeof(TypeAccessor).GetProperty("Item");
            MethodInfo    baseGetter = indexer.GetGetMethod(), baseSetter = indexer.GetSetMethod();
            MethodBuilder body = tb.DefineMethod(baseGetter.Name, baseGetter.Attributes & ~MethodAttributes.Abstract, typeof(object), new Type[] { typeof(object), typeof(string) });
            il = body.GetILGenerator();
            WriteMapImpl(il, type, members, mapField, allowNonPublicAccessors, true);
            tb.DefineMethodOverride(body, baseGetter);

            body = tb.DefineMethod(baseSetter.Name, baseSetter.Attributes & ~MethodAttributes.Abstract, null, new Type[] { typeof(object), typeof(string), typeof(object) });
            il   = body.GetILGenerator();
            WriteMapImpl(il, type, members, mapField, allowNonPublicAccessors, false);
            tb.DefineMethodOverride(body, baseSetter);

            MethodInfo baseMethod;
            if (ctor != null)
            {
                baseMethod = typeof(TypeAccessor).GetProperty("CreateNewSupported").GetGetMethod();
                body       = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes, baseMethod.ReturnType, Type.EmptyTypes);
                il         = body.GetILGenerator();
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Ret);
                tb.DefineMethodOverride(body, baseMethod);

                baseMethod = typeof(TypeAccessor).GetMethod("CreateNew");
                body       = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes, baseMethod.ReturnType, Type.EmptyTypes);
                il         = body.GetILGenerator();
                il.Emit(OpCodes.Newobj, ctor);
                il.Emit(OpCodes.Ret);
                tb.DefineMethodOverride(body, baseMethod);
            }

            baseMethod = typeof(RuntimeTypeAccessor).GetProperty("Type", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true);
            body       = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes & ~MethodAttributes.Abstract, baseMethod.ReturnType, Type.EmptyTypes);
            il         = body.GetILGenerator();
            il.Emit(OpCodes.Ldtoken, type);
            il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));
            il.Emit(OpCodes.Ret);
            tb.DefineMethodOverride(body, baseMethod);

            try
            {
                var accessor = (TypeAccessor)Activator.CreateInstance(tb.CreateType(), map);
                return(accessor);
            }
            catch (TargetInvocationException vex)
            {
                var _getter = new Func <int, object, object>((index, obj) =>
                {
                    return(obj.GetType().GetProperties()[index].GetValue(obj));
                });

                var _setter = new Action <int, object, object>((index, obj, value) =>
                {
                    try
                    {
                        obj.GetType().GetProperties()[index].SetValue(obj, value);
                    }
                    catch (ArgumentException icex)
                    {
                        throw new InvalidCastException(icex.Message, icex);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message, ex);
                    }
                });

                return(new DelegateAccessor(map, _getter, _setter, delegate { return ctor.Invoke(null); }, type));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
#else
            var _getter = new Func <int, object, object>((index, obj) =>
            {
#if WINDOWS_PHONE_APP
                return(obj.GetType().GetRuntimeProperties().ToArray()[index].GetValue(obj));
#else
                return(obj.GetType().GetProperties()[index].GetValue(obj));
#endif
            });

            var _setter = new Action <int, object, object>((index, obj, value) =>
            {
                try
                {
#if WINDOWS_PHONE_APP
                    obj.GetType().GetRuntimeProperties().ToArray()[index].SetValue(obj, value);
#else
                    obj.GetType().GetProperties()[index].SetValue(obj, value);
#endif
                }
                catch (ArgumentException icex)
                {
                    throw new InvalidCastException(icex.Message, icex);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }
            });

            return(new DelegateAccessor(map, _getter, _setter, delegate { return ctor.Invoke(null); }, type));

            //RuntimeTypeAccessor() (TypeAccessor) Activator.CreateInstance(type);
            //return (TypeAccessor)Activator.CreateInstance(type);
#endif
        }
Esempio n. 57
0
		private static Type CreateAnnotationType(ModuleBuilder modb, string name)
		{
			TypeBuilder tb = modb.DefineType(name, TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public);
			tb.DefineGenericParameters("T")[0].SetBaseTypeConstraint(Types.Attribute);
			return tb.CreateType();
		}
Esempio n. 58
0
        public static Type Generate(string functionAssemblyName, string typeName, Collection <CustomAttributeBuilder> typeAttributes, Collection <FunctionDescriptor> functions)
        {
            if (functions == null)
            {
                throw new ArgumentNullException("functions");
            }

            AssemblyName    assemblyName    = new AssemblyName(functionAssemblyName);
            AssemblyBuilder assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    assemblyName,
                    AssemblyBuilderAccess.Run);

            ModuleBuilder mb = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

            TypeBuilder tb = mb.DefineType(typeName, TypeAttributes.Public);

            if (typeAttributes != null)
            {
                foreach (CustomAttributeBuilder attributeBuilder in typeAttributes)
                {
                    tb.SetCustomAttribute(attributeBuilder);
                }
            }

            foreach (FunctionDescriptor function in functions)
            {
                if (function.Metadata.IsDirect)
                {
                    continue;
                }

                MethodBuilder methodBuilder = tb.DefineMethod(function.Name, MethodAttributes.Public | MethodAttributes.Static);
                Type[]        types         = function.Parameters.Select(p => p.Type).ToArray();
                methodBuilder.SetParameters(types);
                methodBuilder.SetReturnType(typeof(Task));

                if (function.CustomAttributes != null)
                {
                    foreach (CustomAttributeBuilder attributeBuilder in function.CustomAttributes)
                    {
                        methodBuilder.SetCustomAttribute(attributeBuilder);
                    }
                }

                for (int i = 0; i < function.Parameters.Count; i++)
                {
                    ParameterDescriptor parameter        = function.Parameters[i];
                    ParameterBuilder    parameterBuilder = methodBuilder.DefineParameter(i + 1, parameter.Attributes, parameter.Name);
                    if (parameter.CustomAttributes != null)
                    {
                        foreach (CustomAttributeBuilder attributeBuilder in parameter.CustomAttributes)
                        {
                            parameterBuilder.SetCustomAttribute(attributeBuilder);
                        }
                    }
                }

                _invokerMap[function.Name] = function.Invoker;

                MethodInfo invokeMethod = function.Invoker.GetType().GetMethod("Invoke");
                MethodInfo getInvoker   = typeof(FunctionGenerator).GetMethod("GetInvoker", BindingFlags.Static | BindingFlags.Public);

                ILGenerator il = methodBuilder.GetILGenerator();

                LocalBuilder argsLocal    = il.DeclareLocal(typeof(object[]));
                LocalBuilder invokerLocal = il.DeclareLocal(typeof(IFunctionInvoker));

                il.Emit(OpCodes.Nop);

                // declare an array for all parameter values
                il.Emit(OpCodes.Ldc_I4, function.Parameters.Count);
                il.Emit(OpCodes.Newarr, typeof(object));
                il.Emit(OpCodes.Stloc, argsLocal);

                // copy each parameter into the arg array
                for (int i = 0; i < function.Parameters.Count; i++)
                {
                    ParameterDescriptor parameter = function.Parameters[i];

                    il.Emit(OpCodes.Ldloc, argsLocal);
                    il.Emit(OpCodes.Ldc_I4, i);
                    il.Emit(OpCodes.Ldarg, i);

                    // For Out and Ref types, need to do an indirection.
                    if (parameter.Type.IsByRef)
                    {
                        il.Emit(OpCodes.Ldind_Ref);
                    }

                    // Box value types
                    if (parameter.Type.IsValueType)
                    {
                        il.Emit(OpCodes.Box, parameter.Type);
                    }

                    il.Emit(OpCodes.Stelem_Ref);
                }

                // get the invoker instance
                il.Emit(OpCodes.Ldstr, function.Name);
                il.Emit(OpCodes.Call, getInvoker);
                il.Emit(OpCodes.Stloc, invokerLocal);

                // now call the invoker, passing in the args
                il.Emit(OpCodes.Ldloc, invokerLocal);
                il.Emit(OpCodes.Ldloc, argsLocal);
                il.Emit(OpCodes.Callvirt, invokeMethod);

                if (function.Parameters.Any(p => p.Type.IsByRef))
                {
                    LocalBuilder taskLocal        = il.DeclareLocal(typeof(Task));
                    LocalBuilder taskAwaiterLocal = il.DeclareLocal(typeof(TaskAwaiter));

                    // We need to wait on the function's task if we have any out/ref
                    // parameters to ensure they have been populated before we copy them back

                    // Store the result into a local Task
                    // and load it onto the evaluation stack
                    il.Emit(OpCodes.Stloc, taskLocal);
                    il.Emit(OpCodes.Ldloc, taskLocal);

                    // Call "GetAwaiter" on the Task
                    il.Emit(OpCodes.Callvirt, typeof(Task).GetMethod("GetAwaiter", Type.EmptyTypes));

                    // Call "GetResult", which will synchonously wait for the Task to complete
                    il.Emit(OpCodes.Stloc, taskAwaiterLocal);
                    il.Emit(OpCodes.Ldloca, taskAwaiterLocal);
                    il.Emit(OpCodes.Call, typeof(TaskAwaiter).GetMethod("GetResult"));

                    // Copy back out and ref parameters
                    for (int i = 0; i < function.Parameters.Count; i++)
                    {
                        var param = function.Parameters[i];
                        if (!param.Type.IsByRef)
                        {
                            continue;
                        }

                        il.Emit(OpCodes.Ldarg, i);

                        il.Emit(OpCodes.Ldloc, argsLocal);
                        il.Emit(OpCodes.Ldc_I4, i);
                        il.Emit(OpCodes.Ldelem_Ref);
                        il.Emit(OpCodes.Castclass, param.Type.GetElementType());

                        il.Emit(OpCodes.Stind_Ref);
                    }

                    il.Emit(OpCodes.Ldloc, taskLocal);
                }

                il.Emit(OpCodes.Ret);
            }

            Type t = tb.CreateType();

            return(t);
        }
Esempio n. 59
0
		private static void CreateEnumEnum(ModuleBuilder modb, ClassLoaderWrapper loader)
		{
			TypeBuilder tb = modb.DefineType(DotNetTypeWrapper.GenericEnumEnumTypeName, TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public);
			GenericTypeParameterBuilder gtpb = tb.DefineGenericParameters("T")[0];
			gtpb.SetBaseTypeConstraint(Types.Enum);
			genericEnumEnumType = tb;
		}
Esempio n. 60
0
 public DynamicModule(ModuleBuilder builder)
 {
     Builder      = builder;
     CreatedTypes = new Dictionary <string, Type>();
 }