public DefineType ( string name ) : System.Reflection.Emit.TypeBuilder | ||
name | string | |
return | System.Reflection.Emit.TypeBuilder |
private TypeBuilder EmitOwnerMappingType(IPropertyMappingProvider map, ModuleBuilder defineDynamicModule, string ownerTypeName) { var owner = defineDynamicModule.DefineType( ownerTypeName, TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract, null, new[] { typeof(IRdfListOwner) }).CreateType(); var ownerMapType = typeof(ListOwnerMap<>).MakeGenericType(new[] { owner }); var mapBuilderHelper = defineDynamicModule.DefineType(ownerTypeName + "Map", TypeAttributes.Public, ownerMapType); var propertyBuilder = mapBuilderHelper.DefineProperty("ListPredicate", PropertyAttributes.None, typeof(Uri), null); var getMethod = mapBuilderHelper.DefineMethod( "get_ListPredicate", MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName, typeof(Uri), Type.EmptyTypes); propertyBuilder.SetGetMethod(getMethod); var ilGenerator = getMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Nop); ilGenerator.Emit(OpCodes.Ldstr, map.GetTerm(_ontologyProvider).ToString()); ilGenerator.Emit(OpCodes.Newobj, typeof(Uri).GetConstructor(new[] { typeof(string) })); ilGenerator.Emit(OpCodes.Ret); return mapBuilderHelper; }
internal void CreateMainType() { // Create a new type to hold our method. MainType = ModuleBuilder.DefineType("JavaScriptClass" + TypeCount.ToString(), System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class ); TypeCount++; }
public DotNetCompiler(LibraryContext context, string filename) { Context = context; var fi = new FileInfo(filename); Path = fi; BuilderAppDomain = AppDomain.CurrentDomain; AssemblyBuilder = BuilderAppDomain.DefineDynamicAssembly(new AssemblyName(fi.Name), AssemblyBuilderAccess.RunAndSave, fi.DirectoryName); MainModule = AssemblyBuilder.DefineDynamicModule(fi.Name, fi.Name); ScriptsType = MainModule.DefineType("Scripts", TypeAttributes.Class); RoomsType = MainModule.DefineType("Rooms", TypeAttributes.Class); }
private static void CreateWrappers(Type interfaceType, ModuleBuilder mb, out TypeBuilder rawInterface, out TypeBuilder CCP, out TypeBuilder RCP) { idCounter += 1; List<MethodDesc> methodDescs = new List<MethodDesc>(); foreach (MethodInfo mi in interfaceType.GetMethods()) { methodDescs.Add(new MethodDesc(mi)); } rawInterface = mb.DefineType(interfaceType.FullName + "-RAW" + idCounter, TypeAttributes.Interface); CCW = mb.DefineType(interfaceType.FullName + "-CCP" + idCounter, TypeAttributes.Class); RCW = mb.DefineType(interfaceType.FullName + "-RCP" + idCounter, TypeAttributes.Class); }
public Type DefineParallelizedType(ModuleBuilder moduleBuilder) { TypeBuilder typeBuilder = moduleBuilder.DefineType(ParallelizedTypeName); typeBuilder.SetParent(source); TypeAnalyzer typeAnalyzer = new TypeAnalyzer(source); ChannelImplementer channelImplementer = new ChannelImplementer(typeBuilder); ForkImplementer forkImplementer = new ForkImplementer(typeBuilder, channelImplementer); ChordImplementer chordImplementer = new ChordImplementer(typeBuilder, channelImplementer); JoinImplementer joinImplementer = new JoinImplementer(typeBuilder, channelImplementer); YieldImplementer yieldImplementer = new YieldImplementer(typeBuilder, channelImplementer); DisposeImplementer disposeImplementer = new DisposeImplementer(typeBuilder, source); ConstructorImplementer constructorImplementer = new ConstructorImplementer(typeBuilder, source, channelImplementer, chordImplementer, disposeImplementer); foreach (ForkGroup forkGroup in typeAnalyzer.GetForkGroups()) forkImplementer.Implement(forkGroup); foreach (ChordInfo chord in typeAnalyzer.GetChords()) chordImplementer.Implement(chord); foreach (JoinGroup joinGroup in typeAnalyzer.GetJoinGroups()) joinImplementer.Implement(joinGroup); foreach (YieldInfo yieldInfo in typeAnalyzer.GetYields()) yieldImplementer.Implement(yieldInfo); disposeImplementer.ImplementDisposalBehavior(); constructorImplementer.ImplementConstructor(); return typeBuilder.CreateType(); }
/// <summary> /// Initializes a new instance of the <see cref="SerializerEmitter"/> class. /// </summary> /// <param name="host">The host <see cref="ModuleBuilder"/>.</param> /// <param name="specification">The specification of the serializer.</param> /// <param name="baseClass">Type of the base class of the serializer.</param> /// <param name="isDebuggable">Set to <c>true</c> when <paramref name="host"/> is debuggable.</param> public SerializerEmitter( ModuleBuilder host, SerializerSpecification specification, Type baseClass, bool isDebuggable ) { Contract.Requires( host != null ); Contract.Requires( specification != null ); Contract.Requires( baseClass != null ); Tracer.Emit.TraceEvent( Tracer.EventType.DefineType, Tracer.EventId.DefineType, "Create {0}", specification.SerializerTypeFullName ); this._methodTable = new Dictionary<string, MethodBuilder>(); this._fieldTable = new Dictionary<string, FieldBuilder>(); this._specification = specification; this._host = host; this._typeBuilder = host.DefineType( specification.SerializerTypeFullName, TypeAttributes.Sealed | TypeAttributes.Public | TypeAttributes.UnicodeClass | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit, baseClass ); #if DEBUG Contract.Assert( this._typeBuilder.BaseType != null, "baseType != null" ); #endif // DEBUG this._isDebuggable = isDebuggable; #if DEBUG && !NETFX_35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 if ( isDebuggable && SerializerDebugging.DumpEnabled ) { SerializerDebugging.PrepareDump( host.Assembly as AssemblyBuilder ); } #endif // DEBUG && !NETFX_35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 }
void EmitType(ModuleBuilder Parent, CodeTypeDeclaration Decl) { TypeBuilder Type = Parent.DefineType(Decl.Name, TypeAttributes.Public); // Allow for late binding var LocalMethods = new Dictionary<string, MethodWriter>(); var LocalParameters = new Dictionary<string, Type[]>(); foreach(CodeMemberMethod Method in Decl.Members) { var Writer = new MethodWriter(Type, Method, Methods, Mirror); LocalParameters.Add(Method.Name, GetParameterTypes(Method.Parameters)); LocalMethods.Add(Method.Name, Writer); } foreach(var Writer in LocalMethods.Values) { Writer.ParameterTypes = LocalParameters; Writer.Methods = LocalMethods; Writer.Emit(); if(Writer.IsEntryPoint) EntryPoint = Writer.Method; } Type.CreateType(); }
/// <summary> /// Defines a new delegate type. /// </summary> public static System.Type DefineDelegateType( string fullTypeName, ModuleBuilder moduleBuilder, System.Type returnType, System.Type[] parameterTypes) { TypeBuilder delegateBuilder = moduleBuilder.DefineType( fullTypeName, TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate)); // Define a special constructor ConstructorBuilder constructorBuilder = delegateBuilder.DefineConstructor( MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new System.Type[] {typeof(object), typeof(IntPtr)}); constructorBuilder.SetImplementationFlags( MethodImplAttributes.Runtime | MethodImplAttributes.Managed); // Define the Invoke method for the delegate MethodBuilder methodBuilder; methodBuilder = delegateBuilder.DefineMethod( "Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, returnType, parameterTypes); methodBuilder.SetImplementationFlags( MethodImplAttributes.Runtime | MethodImplAttributes.Managed); return delegateBuilder.CreateType(); }
public CodeGenerator(Expression pExpression, String pModuleName, ref LogHandler rLogHandler) { _symbolTable = new Dictionary <String, Emit.LocalBuilder>(); _assemblyName = new Reflect.AssemblyName(Path.GetFileNameWithoutExtension(pModuleName)); _statement = pExpression; //Init Assembly _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, Emit.AssemblyBuilderAccess.Save); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(pModuleName); _typeBuilder = _moduleBuilder.DefineType("PascalCompilerType"); _methodBuilder = _typeBuilder.DefineMethod ( "Main", Reflect.MethodAttributes.Static, typeof(void), Type.EmptyTypes ); _ilGenerator = _methodBuilder.GetILGenerator(); //Actual Work GenerateStatement(_statement, null); _ilGenerator.Emit(Emit.OpCodes.Ret); //Finalizing Work _typeBuilder.CreateType(); _moduleBuilder.CreateGlobalFunctions(); _assemblyBuilder.SetEntryPoint(_methodBuilder); _assemblyBuilder.Save(pModuleName); }
public void Program() { var tempName = "EvilProg-" + Guid.NewGuid().ToString(); AssemblyName aName = new AssemblyName(tempName); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save); programModule = ab.DefineDynamicModule(aName.Name, tempName + ".exe", true); programType = programModule.DefineType("Program", TypeAttributes.Public); createReadInInt(); this.program(); var main = functionMap["main"]; programModule.SetUserEntryPoint(main); ab.SetEntryPoint(main); programType.CreateType(); string tempPath = tempName + ".exe"; ab.Save(tempPath); if (File.Exists(Options.ClrExec.Value)) File.Delete(Options.ClrExec.Value); File.Move(tempPath, Options.ClrExec.Value); File.Delete(tempPath); }
public ILDynamicTypeImpl(string name, Type baseType, Type[] interfaces) { _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.RunAndCollect); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(name + ".dll", true); _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, baseType, interfaces); _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder); }
public ILDynamicMethodDebugImpl(string name, Type delegateType, Type thisType) { _delegateType = delegateType; _expectedLength = 64; var mi = delegateType.GetMethod("Invoke"); var uniqueName = ILDynamicTypeDebugImpl.UniqueName(name); _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(uniqueName), AssemblyBuilderAccess.RunAndSave, DynamicILDirectoryPath.DynamicIL); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(uniqueName + ".dll", true); var sourceCodeFileName = Path.Combine(DynamicILDirectoryPath.DynamicIL, uniqueName + ".il"); _symbolDocumentWriter = _moduleBuilder.DefineDocument(sourceCodeFileName, SymDocumentType.Text, SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft); _sourceCodeWriter = new SourceCodeWriter(sourceCodeFileName, _symbolDocumentWriter); Type[] parameterTypes; if (thisType != null) { parameterTypes = new[] { thisType }.Concat(mi.GetParameters().Select(pi => pi.ParameterType)).ToArray(); } else { parameterTypes = mi.GetParameters().Select(pi => pi.ParameterType).ToArray(); } _sourceCodeWriter.StartMethod(name, mi.ReturnType, parameterTypes, MethodAttributes.Static); _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, typeof(object), Type.EmptyTypes); _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder); _dynamicMethod = _typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Static, mi.ReturnType, parameterTypes); for (int i = 0; i < parameterTypes.Length; i++) { _dynamicMethod.DefineParameter(i + 1, ParameterAttributes.In, string.Format("arg{0}", i)); } }
static Type CreateTypeFromInterface(ModuleBuilder builder, Type typeToProxy) { string typeName = typeToProxy.Namespace + ProxyNamespaceSuffix + "." + typeToProxy.Name; TypeBuilder typeBuilder = builder.DefineType(typeName, TypeAttributes.Serializable | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed, typeof(object), new[] {typeToProxy}); typeBuilder.DefineDefaultConstructor(MethodAttributes.Public); typeToProxy.GetAllProperties().Each(x => { FieldBuilder fieldBuilder = typeBuilder.DefineField("field_" + x.Name, x.PropertyType, FieldAttributes.Private); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(x.Name, x.Attributes | PropertyAttributes.HasDefault, x.PropertyType, null); MethodBuilder getMethod = GetGetMethodBuilder(x, typeBuilder, fieldBuilder); MethodBuilder setMethod = GetSetMethodBuilder(x, typeBuilder, fieldBuilder); propertyBuilder.SetGetMethod(getMethod); propertyBuilder.SetSetMethod(setMethod); }); return typeBuilder.CreateType(); }
public CodeGen(Stmt stmt, string moduleName) { if (IO.Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } Reflect.AssemblyName name = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(moduleName)); Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save); Emit.ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); Emit.TypeBuilder typeBuilder = modb.DefineType("Foo"); Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); // CodeGenerator this.il = methb.GetILGenerator(); this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>(); // Go Compile! this.GenStmt(stmt); il.Emit(Emit.OpCodes.Ret); typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb); asmb.Save(moduleName); this.symbolTable = null; this.il = null; }
static NativeCall() { // The static constructor is responsible for generating the // assembly and the methods that implement the IJW thunks. // // To do this, we actually use reflection on the INativeCall // interface (defined below) and generate the required thunk // code based on the method signatures. AssemblyName aname = new AssemblyName(); aname.Name = "e__NativeCall_Assembly"; AssemblyBuilderAccess aa = AssemblyBuilderAccess.Run; aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa); mBuilder = aBuilder.DefineDynamicModule("e__NativeCall_Module"); TypeAttributes ta = TypeAttributes.Public; TypeBuilder tBuilder = mBuilder.DefineType("e__NativeCall", ta); Type iType = typeof(INativeCall); tBuilder.AddInterfaceImplementation(iType); // Use reflection to loop over the INativeCall interface methods, // calling GenerateThunk to create a managed thunk for each one. foreach (MethodInfo method in iType.GetMethods()) { GenerateThunk(tBuilder, method); } Type theType = tBuilder.CreateType(); Impl = (INativeCall)Activator.CreateInstance(theType); }
protected void SetUp () { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = GetType().FullName; AssemblyBuilder assembly = Thread.GetDomain().DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run); module = assembly.DefineDynamicModule("module1"); tb = module.DefineType("class1", TypeAttributes.Public); eb = tb.DefineEvent ("event1", EventAttributes.None, typeof (AnEvent)); mb = tb.DefineMethod ("OnAnEvent", MethodAttributes.Public, typeof (void), new Type [] { typeof (AnEvent) }); ILGenerator ilgen = mb.GetILGenerator(); ilgen.Emit (OpCodes.Ret); // These two are required eb.SetAddOnMethod (mb); eb.SetRemoveOnMethod (mb); }
private TypeBuilder GetTypeBuilder(Type sourceType, ModuleBuilder moduleBuilder) { return moduleBuilder.DefineType( SnapshotNameGenerator.Generate(sourceType), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Serializable | TypeAttributes.Sealed, SnapshotBaseType); }
public AbstractProxyBuilder(ModuleBuilder moduleBuilder, string className, Type interfaceType, Type innerType) { Verify.ArgumentNotNull(moduleBuilder, "moduleBuilder"); Verify.ArgumentNotNull(className, "className"); Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentNotNull(innerType, "innerType"); if (!interfaceType.IsInterface) { throw new ArgumentException("must be an interface type", "interfaceType"); } _errorMessages = new List<string>(); _moduleBuilder = moduleBuilder; _className = className; _interfaceType = interfaceType; _innerType = innerType; _typeBuilder = _moduleBuilder.DefineType( _className, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, typeof(object), new Type[] {_interfaceType}); _innerFieldBuilder = _typeBuilder.DefineField("inner", _innerType, FieldAttributes.Private); }
private static Type BuildRedisType(ModuleBuilder moduleBuilder, Type redisPipelineType) { const TypeAttributes typeAttributes = TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit; const MethodAttributes constructorAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; var typeBuilder = moduleBuilder.DefineType("Redis.Dynamic.RedisDynamic", typeAttributes, typeof(RedisBase), Type.EmptyTypes); // Emit constructor: // public RedisDynamic(IRedisConnection redisConnection) var constructorBuilder = typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, new[] { typeof(IRedisConnection) }); var redisConstructor = typeof(RedisBase).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(IRedisConnection) }, null); var generator = constructorBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Call, redisConstructor); generator.Emit(OpCodes.Ret); // Emit all abstract RedisBase methods var redisCommandMethods = typeof(RedisBase).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (var redisCommandMethod in redisCommandMethods.Where(x => x.Name != "CreatePipeline" && x.IsAbstract)) { EmitRedisCommandMethod(typeBuilder, redisCommandMethod); } // Emit CreatePipeline method EmitRedisPipelineMethod(typeBuilder, redisPipelineType); return typeBuilder.CreateType(); }
private Type GenerateAnonymousType(ModuleBuilder dynamicTypeModule) { var dynamicType = dynamicTypeModule.DefineType(ClassName, TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed); var builderArray = dynamicType.DefineGenericParameters(GenericClassParameterNames); var fields = new List<FieldBuilder>(); for (var i = 0; i < FieldNames.Length; i++) { var item = dynamicType.DefineField(FieldNames[i], builderArray[i], FieldAttributes.InitOnly | FieldAttributes.Private); var type = typeof(DebuggerBrowsableAttribute); var customBuilder = new CustomAttributeBuilder(type.GetConstructor(new Type[] { typeof(DebuggerBrowsableState) }), new object[] { DebuggerBrowsableState.Never }); item.SetCustomAttribute(customBuilder); fields.Add(item); } var list2 = new List<PropertyBuilder>(); for (var j = 0; j < PropertyNames.Length; j++) { var builder4 = GenerateProperty(dynamicType, PropertyNames[j], fields[j]); // var type = typeof(JsonPropertyAttribute); // var customBuilder2 = new CustomAttributeBuilder(type.GetConstructor(new Type[0]), new object[0]); // builder4.SetCustomAttribute(customBuilder2); list2.Add(builder4); } GenerateClassAttributes(dynamicType, PropertyNames); GenerateConstructor(dynamicType, PropertyNames, fields); GenerateEqualsMethod(dynamicType, fields.ToArray()); GenerateGetHashCodeMethod(dynamicType, fields.ToArray()); GenerateToStringMethod(dynamicType, PropertyNames, fields.ToArray()); return dynamicType.CreateType().MakeGenericType(PropertyTypes); }
public TypeGen(TypeDeclaration typeDec, Emit.ModuleBuilder modb, string dllProbeDirectory, AssemblyGen parent) { methodList = new List <System.Reflection.Emit.MethodBuilder>(); typeBuilder = modb.DefineType(typeDec.TypeName, TypeAttributes.Public); this.parent = parent; this.typeDec = typeDec; }
internal static TypeBuilder Build(ModuleBuilder proxyModule, Type proxyType, AssemblyDebugging debugAssembly) { TypeBuilder proxyTypeBuilder = null; string proxyName = proxyType.Namespace + "." + proxyType.Name + Proxy.ProxyExtension; var iProxyType = typeof(IProxy<>).MakeGenericType(proxyType); proxyTypeBuilder = proxyModule.DefineType(proxyName, TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public, proxyType, new Type[] { iProxyType }); using (TypeDebugging debugType = debugAssembly.GetTypeDebugging(proxyTypeBuilder)) { var fields = ProxyFieldBuilder.Build( proxyTypeBuilder, proxyType); ProxyConstructorBuilder.Build(proxyTypeBuilder, proxyType, fields[ProxyFieldBuilder.WrappedObjectField], fields[ProxyFieldBuilder.InvokeHandlerField], debugType); ProxyMethodBuilder.Build(proxyTypeBuilder, proxyType, iProxyType, fields[ProxyFieldBuilder.WrappedObjectField], fields[ProxyFieldBuilder.InvokeHandlerField], debugType); } return proxyTypeBuilder; }
protected static TypeDebugging CreateDebuggingType( AssemblyDebugging assembly, ModuleBuilder module, string name, HashSet<Type> interfacesToImplement) { return assembly.GetTypeDebugging(module.DefineType( assembly.Builder.GetName().Name + "." + name, TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public, typeof(object)), interfacesToImplement); }
public AssemblyBindingCompiler(string assemblyName, string className, string outputFileName, DotvvmConfiguration configuration) : base(configuration) { assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndSave, Path.GetDirectoryName(outputFileName)); moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName, Path.GetFileName(outputFileName)); bindingsClass = moduleBuilder.DefineType(className, TypeAttributes.Class | TypeAttributes.Public); OutputFileName = outputFileName; }
internal static TypeBuilder DefineUniqueType(string strInitFullName, TypeAttributes attrs, Type BaseType, Type[] aInterfaceTypes, ModuleBuilder mb) { string className = strInitFullName; for (int i = 2; mb.GetType(className) != null; i++) { className = strInitFullName + "_" + i; } return mb.DefineType(className, attrs, BaseType, aInterfaceTypes); }
//other constructor public Class(Type Class, ModuleBuilder Module) { Type BaseType = Class.BaseType; Type GenericType = BaseType.GetGenericArguments() [0]; TypeBuilder TypeBuilder = Module.DefineType("NaiveORM0ClassesM."+ GenericType.Name + "Derived", TypeAttributes.Public, GenericType); // FieldBuilder ChangedField = CreateChangedClearMethod(TypeBuilder); }
public DefinitionContext(string name) { if (name == null) throw new ArgumentNullException("name"); this.module = assembly.DefineDynamicModule(name); this.globaltype = module.DefineType("Global",TypeAttributes.Public); this.types = new Dictionary<string,Type>(globaltypes); this.methods = new Dictionary<string,MethodInfo>(globalmethods); }
public ProxyBuilder(AssemblyBuilder assembly, Type type) { module = assembly.GetDynamicModule("Proxies"); var parent = typeof (ProxyBase); newType = module.DefineType(type.FullName, TypeAttributes.Public, parent, new[] { type }); executeMethod = parent.GetMethod("Execute"); backingObject = parent.GetField("backingObject"); }
public BuildBinderDescription(ModuleBuilder modBuilder) { TypeBuilder typeBuilder = modBuilder.DefineType("BuildBinder", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed); FieldBuilder fb_request = typeBuilder.DefineField("Request", typeof(Action<Type, OpaqueType>), FieldAttributes.Public | FieldAttributes.Static); Result = typeBuilder.CreateType(); BuildRequest = fb_request; }
private static TypeBuilder CreateShimType(ModuleBuilder moduleBuilder, string typeName, Type superClass) { TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Abstract | TypeAttributes.Public, superClass); ConstructorBuilder constructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[0]); constructor.GetILGenerator().Emit(OpCodes.Ret); ConstructorInfo clsCompliantAttribConstructor = typeof(CLSCompliantAttribute).GetConstructor(new[] { typeof(bool) }); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(clsCompliantAttribConstructor, new object[] { true })); return typeBuilder; }
protected void SetUp () { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "MonoTests.System.Reflection.Emit.FieldBuilderTest"; AssemblyBuilder assembly = Thread.GetDomain ().DefineDynamicAssembly ( assemblyName, AssemblyBuilderAccess.Run); module = assembly.DefineDynamicModule ("module1"); _tb = module.DefineType (genTypeName (), TypeAttributes.Public); }
internal static TypeBuilder DefineUniqueType(String strInitFullName, TypeAttributes attrs, Type BaseType, Type[] aInterfaceTypes, ModuleBuilder mb) { String strFullName = strInitFullName; int PostFix = 2; // Find the first unique name for the type. for (; mb.GetType(strFullName) != null; strFullName = strInitFullName + "_" + PostFix, PostFix++); // Define a type with the determined unique name. return mb.DefineType(strFullName, attrs, BaseType, aInterfaceTypes); }
/// <summary> /// Creates a static field that contains the given value. /// </summary> /// <param name="moduleBuilder">The modulebuilder to write to.</param> /// <param name="value">The value to store.</param> /// <returns>A static field containing the value.</returns> private static FieldInfo CreateField(ModuleBuilder moduleBuilder, object value) { // create a type based on DbConnectionWrapper and call the default constructor TypeBuilder tb = moduleBuilder.DefineType(Guid.NewGuid().ToString()); tb.DefineField("_storage", value.GetType(), FieldAttributes.Static | FieldAttributes.Public); Type t = tb.CreateType(); var field = t.GetField("_storage", BindingFlags.Static | BindingFlags.Public); field.SetValue(null, value); return field; }
internal static Type CreateContextType(ModuleBuilder builder, IEnumerable<KeyValuePair<ITypeDescription, Type>> types) { var typesGroupesByName = from t in types where t.Key.IsBusinessEntity group t by t.Key.Name into byName select new ByNameGrouping(byName.Key,byName); var typeBuilder = builder.DefineType(QueryContextClassName, CodeGenerationUtils.PublicClass(), typeof(ContextRoot)); return new ContextTypeGenerator(builder,typeBuilder).Build(typesGroupesByName); }
public ILCodeGen(string name) { this.symtab = Symboltable.Instance; this.program_name = name; this.asname = new Reflect.AssemblyName(name); this.asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(asname, Emit.AssemblyBuilderAccess.Save); this.modb = asmb.DefineDynamicModule(name); this.typeBuilder = modb.DefineType("fpc2IL"); this.mbuilderTable = new Hashtable(); this.fbuilderTable = new Hashtable(); this.lbuilderTable = new Hashtable(); }
private void inicializar(string nombreCodigoFuente, string nombrePrograma) { if (TablaDireccionesSimbolos.Count > 0) { throw new System.Exception("ERROR-0002: Tabla de direcciones de variables ha sido inicializada previamente"); } String rutaEjecutable = IO.Path.GetDirectoryName(nombrePrograma); //Describo el identificador unico del ensamblado que se esta generando nombre = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(nombrePrograma)); //Creo la representacion basica del ensamblado creado de forma dinamica (assembly) if (rutaEjecutable.Length > 0) { asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave, rutaEjecutable); } else { asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave); } Console.WriteLine("Common Runtime usado para generar el ejecutable del programa: " + asmb.ImageRuntimeVersion); Console.WriteLine("Se esta ejecutando el compilador bajo el CLR version {0}", Environment.Version); //Defino un nuevo modulo de .net de forma dinamica modb = asmb.DefineDynamicModule(IO.Path.GetFileName(nombrePrograma), false); //Creo una nueva clase en el Il Generator stream typeBuilder = modb.DefineType("pseudoGenerado"); //Debido a que los programas en este tiny solo cuentan con un unico metodo principal (Main) de forma estructurada //como un truco defino el metodo Main en un objeto por defecto para ejecutar todas las acciones //expresadas por el lenguaje alli. //formato: NOMBRE -> Main TIPO-> Static RETORNA-> void PARAMETROS-> vacios methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.HideBySig | Reflect.MethodAttributes.Static | Reflect.MethodAttributes.Public, typeof(void), System.Type.EmptyTypes); //Inicializo/Creo el generador/stream de codigo IL con el metodo donde generare el codigo actualmente this.il = methb.GetILGenerator(); //Para iniciar el programa Emito una primera instruccion vacia (no hace nada) il.Emit(Emit.OpCodes.Nop); }
/// <summary> /// Build a new provider /// </summary> /// <param name="assemblyName">Name of the assembly to build.</param> public SigilFunctionProvider(string assemblyName = null) { AlreadyBuildedMethods = new Dictionary <Type, IResponse>(); if (string.IsNullOrEmpty(assemblyName)) { return; } this.assemblyName = new AssemblyName(assemblyName); #if RUN_ONLY var attributes = System.Reflection.Emit.AssemblyBuilderAccess.Run; #else var attributes = System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave; #endif assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(this.assemblyName, attributes, Path.GetTempPath()); moduleBuilder = assemblyBuilder.DefineDynamicModule($"{assemblyName}.dll"); typeBuilder = moduleBuilder.DefineType($"{this.assemblyName.Name}.Handler", TypeAttributes.Public); }
public static Type BuildPropertyObject(System.Collections.Generic.IEnumerable <System.Collections.Generic.KeyValuePair <string, Type> > obj) { string nameOfDLL = "magic.dll"; string nameOfAssembly = "magic_Assembly"; string nameOfModule = "magic_Module"; string nameOfType = "magic_Type"; System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName { Name = nameOfAssembly }; System.Reflection.Emit.AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave); System.Reflection.Emit.ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(nameOfModule, nameOfDLL); System.Reflection.Emit.TypeBuilder typeBuilder = moduleBuilder.DefineType(nameOfType, System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class); foreach (var prop in obj) { string Name = prop.Key; Type DataType = prop.Value; System.Reflection.Emit.FieldBuilder field = typeBuilder.DefineField("_" + Name, DataType, System.Reflection.FieldAttributes.Private); System.Reflection.Emit.PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(Name, System.Reflection.PropertyAttributes.SpecialName, DataType, null); System.Reflection.MethodAttributes methodAttributes = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName; System.Reflection.Emit.MethodBuilder methodBuilderGetter = typeBuilder.DefineMethod("get_" + Name, methodAttributes, DataType, new Type[] { }); System.Reflection.Emit.MethodBuilder methodBuilderSetter = typeBuilder.DefineMethod("set_" + Name, methodAttributes, typeof(void), new Type[] { DataType }); System.Reflection.Emit.ILGenerator ilGeneratorGetter = methodBuilderGetter.GetILGenerator(); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldfld, field); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ret); System.Reflection.Emit.ILGenerator ilGeneratorSetter = methodBuilderSetter.GetILGenerator(); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_1); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Stfld, field); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ret); propertyBuilder.SetGetMethod(methodBuilderGetter); propertyBuilder.SetSetMethod(methodBuilderSetter); } // Yes! you must do this, it should not be needed but it is! Type dynamicType = typeBuilder.CreateType(); // Save to file assemblyBuilder.Save(nameOfDLL); return(dynamicType); }
public CodeGen(stmt stmt, string moduleName, int count) { if (IO.Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } stmts = stmt; Reflect.AssemblyName name = new Reflect.AssemblyName("FAJF"); //name of the assembly Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save); Emit.ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); Emit.TypeBuilder typeBuilder = modb.DefineType("resister"); //name of the class Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); // CodeGenerator this.il = methb.GetILGenerator(); this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>(); counting = 0; counter = count; counters = 0; // Go Compile! this.GenStmt(stmt); il.Emit(Emit.OpCodes.Ret); typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb); asmb.Save(moduleName); // this.il.EmitWriteLine("press any key to continue"); this.symbolTable = null; this.il = null; System.Diagnostics.Process.Start(moduleName); }
// Функция предкодогенерационного обхода синтаксического дерева // Нужен для того, чтобы выполнить некоторую подготовительную работу. Например, задекларировать классы private void BeforeCompile(Node ActiveNode) { if (ActiveNode.IsTerminal) { } else { if ( (ActiveNode.TypeNTerminal == NonTerminal.MainClass) || (ActiveNode.TypeNTerminal == NonTerminal.ClassDecl)) { if (TypeTable.ContainsKey(ActiveNode.Nodes[1].Value)) { throw new System.Exception("Переопределение класса " + ActiveNode.Nodes[1].Value); } else { Emit.TypeBuilder _TypeBuilder = ModBuilder.DefineType(ActiveNode.Nodes[1].Value); TypeTable[ActiveNode.Nodes[1].Value] = _TypeBuilder; if (ActiveNode.TypeNTerminal != NonTerminal.MainClass) { _TypeBuilder.DefineDefaultConstructor(Reflect.MethodAttributes.Public); } } } foreach (Node Child in ActiveNode.Nodes) { BeforeCompile(Child); } } }
/// <summary> /// Generate the declaration for the IgnoresAccessChecksToAttribute type. /// This attribute will be both defined and used in the dynamic assembly. /// Each usage identifies the name of the assembly containing non-public /// types the dynamic assembly needs to access. Normally those types /// would be inaccessible, but this attribute allows them to be visible. /// It works like a reverse InternalsVisibleToAttribute. /// This method returns the ConstructorInfo of the generated attribute. /// </summary> public static ConstructorInfo AddToModule(ModuleBuilder mb) { TypeBuilder attributeTypeBuilder = mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute", TypeAttributes.Public | TypeAttributes.Class, typeof(Attribute)); // Create backing field as: // private string assemblyName; FieldBuilder assemblyNameField = attributeTypeBuilder.DefineField("assemblyName", typeof(string), FieldAttributes.Private); // Create ctor as: // public IgnoresAccessChecksToAttribute(string) ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { assemblyNameField.FieldType }); ILGenerator il = constructorBuilder.GetILGenerator(); // Create ctor body as: // this.assemblyName = {ctor parameter 0} il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, 1); il.Emit(OpCodes.Stfld, assemblyNameField); // return il.Emit(OpCodes.Ret); // Define property as: // public string AssemblyName {get { return this.assemblyName; } } _ = attributeTypeBuilder.DefineProperty( "AssemblyName", PropertyAttributes.None, CallingConventions.HasThis, returnType: typeof(string), parameterTypes: null); MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod( "get_AssemblyName", MethodAttributes.Public, CallingConventions.HasThis, returnType: typeof(string), parameterTypes: null); // Generate body: // return this.assemblyName; il = getterMethodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, assemblyNameField); il.Emit(OpCodes.Ret); // Generate the AttributeUsage attribute for this attribute type: // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo(); // Find the ctor that takes only AttributeTargets ConstructorInfo attributeUsageConstructorInfo = attributeUsageTypeInfo.DeclaredConstructors .Single(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof(AttributeTargets)); // Find the property to set AllowMultiple PropertyInfo allowMultipleProperty = attributeUsageTypeInfo.DeclaredProperties .Single(f => string.Equals(f.Name, "AllowMultiple")); // Create a builder to construct the instance via the ctor and property CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeUsageConstructorInfo, new object[] { AttributeTargets.Assembly }, new PropertyInfo[] { allowMultipleProperty }, new object[] { true }); // Attach this attribute instance to the newly defined attribute type attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder); // Make the TypeInfo real so the constructor can be used. return(attributeTypeBuilder.CreateTypeInfo() !.DeclaredConstructors.Single()); }
private static void CreateDynamicDatabaseModelModule() { // Get tables and their columns var databaseTableInfo = GetDatabaseTableInfo(); AppDomain domain = AppDomain.CurrentDomain; AssemblyName aName = new AssemblyName("Example.DynamicMapping.DynamicDatabaseMapping"); AssemblyBuilder ab = domain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save); System.Reflection.Emit.ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll"); // Define mapping static class of the database TypeBuilder typeDatabaseModel = mb.DefineType("Example.DynamicMapping.DynamicDatabaseMapping.DatabaseModels.DatabaseMapping", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed); // Get base table class Type tableBase = typeof(SqlTableModelBase); ConstructorInfo tableBaseCtor = tableBase.GetConstructor(Type.EmptyTypes); // no parameters // Get base column class Type columnBase = typeof(SqlColumnModelBase); ConstructorInfo fieldBaseCtor = columnBase.GetConstructor(new[] { typeof(string) }); // Needed for creating the class constructors in a loop var tableFields = new List <ReflectionDefineField>(); foreach (var table in databaseTableInfo) { var columnFields = new List <ReflectionDefineField>(); TypeBuilder typeTable = mb.DefineType($"Example.DynamicMapping.DynamicDatabaseMapping.DatabaseModels.{table.Name}", TypeAttributes.Public, typeof(SqlTableModelBase)); // Create the column classes for the table foreach (var column in table.Columns) { TypeBuilder typeColumn = mb.DefineType($"Example.DynamicMapping.DynamicDatabaseMapping.DatabaseModels.{table.Name}.{column.Name}", TypeAttributes.Public, typeof(SqlColumnModelBase)); ConstructorBuilder staticColumnConstructorBuilder = typeColumn.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.HasThis, new[] { typeof(string) }); ILGenerator staticColumnConstructorILGenerator = staticColumnConstructorBuilder.GetILGenerator(); staticColumnConstructorILGenerator.Emit(OpCodes.Ldarg_0); staticColumnConstructorILGenerator.Emit(OpCodes.Ldarg_1); staticColumnConstructorILGenerator.Emit(OpCodes.Call, fieldBaseCtor); staticColumnConstructorILGenerator.Emit(OpCodes.Nop); staticColumnConstructorILGenerator.Emit(OpCodes.Nop); staticColumnConstructorILGenerator.Emit(OpCodes.Ret); var createdColumn = typeColumn.CreateType(); ConstructorInfo columnConstructor = createdColumn.GetConstructor(new[] { typeof(string) }); columnFields.Add(new ReflectionDefineField() { ConstructorInfo = columnConstructor, Type = createdColumn }); } ConstructorBuilder staticTableConstructorBuilder = typeTable.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.HasThis, Type.EmptyTypes); ILGenerator staticTableConstructorILGenerator = staticTableConstructorBuilder.GetILGenerator(); staticTableConstructorILGenerator.Emit(OpCodes.Ldarg_0); staticTableConstructorILGenerator.Emit(OpCodes.Call, tableBaseCtor); // Initialise constructor of column classes and assign to property on table class foreach (var field in columnFields) { FieldBuilder fieldColumn = typeTable.DefineField(field.ConstructorInfo.DeclaringType.Name, field.Type, FieldAttributes.InitOnly | FieldAttributes.Public); staticTableConstructorILGenerator.Emit(OpCodes.Ldarg_0); staticTableConstructorILGenerator.Emit(OpCodes.Ldstr, table.Name); staticTableConstructorILGenerator.Emit(OpCodes.Newobj, field.ConstructorInfo); staticTableConstructorILGenerator.Emit(OpCodes.Stfld, fieldColumn); // Stfld => non-static field! } staticTableConstructorILGenerator.Emit(OpCodes.Ret); // Create the table class var createdTable = typeTable.CreateType(); ConstructorInfo tableConstructor = createdTable.GetConstructor(Type.EmptyTypes); tableFields.Add(new ReflectionDefineField() { ConstructorInfo = tableConstructor, Type = createdTable }); } ConstructorBuilder staticDatabaseConstructorBuilder = typeDatabaseModel.DefineConstructor(MethodAttributes.Private | MethodAttributes.PrivateScope | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes); ILGenerator staticDatabaseConstructorILGenerator = staticDatabaseConstructorBuilder.GetILGenerator(); // Initialise constructor of table classes and assign to property on mapping class foreach (var field in tableFields) { FieldBuilder fieldDatabase = typeDatabaseModel.DefineField(field.ConstructorInfo.DeclaringType.Name, field.Type, FieldAttributes.InitOnly | FieldAttributes.Public | FieldAttributes.Static); staticDatabaseConstructorILGenerator.Emit(OpCodes.Nop); staticDatabaseConstructorILGenerator.Emit(OpCodes.Newobj, field.ConstructorInfo); staticDatabaseConstructorILGenerator.Emit(OpCodes.Stsfld, fieldDatabase); // Stsfld => static field! } staticDatabaseConstructorILGenerator.Emit(OpCodes.Ret); // Create the mapping class var createdDatabaseModel = typeDatabaseModel.CreateType(); ab.Save(aName.Name + ".dll"); // Save .dll module }