Inheritance: System.Reflection.Module, _ModuleBuilder
Example #1
0
 // Constructs a PropertyBuilder.  
 //
 internal PropertyBuilder(
     ModuleBuilder       mod,            // the module containing this PropertyBuilder
     String              name,           // property name
     SignatureHelper     sig,            // property signature descriptor info
     PropertyAttributes  attr,           // property attribute such as DefaultProperty, Bindable, DisplayBind, etc
     Type                returnType,     // return type of the property.
     PropertyToken       prToken,        // the metadata token for this property
     TypeBuilder         containingType) // the containing type
 {
     if (name == null)
         throw new ArgumentNullException("name");
     if (name.Length == 0)
         throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
     if (name[0] == '\0')
         throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
     Contract.EndContractBlock();
     
     m_name = name;
     m_moduleBuilder = mod;
     m_signature = sig;
     m_attributes = attr;
     m_returnType = returnType;
     m_prToken = prToken;
     m_tkProperty = prToken.Token;
     m_containingType = containingType;
 }
         /// <summary>
        /// Initializes a new instance of the <see cref="SetAccessorFactory"/> class.
        /// </summary>
        /// <param name="allowCodeGeneration">if set to <c>true</c> [allow code generation].</param>
        public SetAccessorFactory(bool allowCodeGeneration)
		{
            if (allowCodeGeneration)
            {
                // Detect runtime environment and create the appropriate factory
                if (Environment.Version.Major >= 2)
                {
                    _createPropertySetAccessor = new CreatePropertySetAccessor(CreateDynamicPropertySetAccessor);
                    _createFieldSetAccessor = new CreateFieldSetAccessor(CreateDynamicFieldSetAccessor);
                }
                else
                {
                    AssemblyName assemblyName = new AssemblyName();
                    assemblyName.Name = "iBATIS.FastSetAccessor" + HashCodeProvider.GetIdentityHashCode(this);

                    // Create a new assembly with one module
                    _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                    _moduleBuilder = _assemblyBuilder.DefineDynamicModule(assemblyName.Name + ".dll");

                    _createPropertySetAccessor = new CreatePropertySetAccessor(CreatePropertyAccessor);
                    _createFieldSetAccessor = new CreateFieldSetAccessor(CreateFieldAccessor);
                }
            }
            else
            {
                _createPropertySetAccessor = new CreatePropertySetAccessor(CreateReflectionPropertySetAccessor);
                _createFieldSetAccessor = new CreateFieldSetAccessor(CreateReflectionFieldSetAccessor);
            }
        }
        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;
        }
Example #4
0
        internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, String methodName, 
            CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
        {
            // This is a kind of MethodInfo to represent methods for array type of unbaked type

            // Another way to look at this class is as a glorified MethodToken wrapper. At the time of this comment
            // this class is only constructed inside ModuleBuilder.GetArrayMethod and the only interesting thing 
            // passed into it is this MethodToken. The MethodToken was forged using a TypeSpec for an Array type and
            // the name of the method on Array. 
            // As none of the methods on Array have CustomModifiers their is no need to pass those around in here.
            m_mdMethod = token;

            // The ParameterTypes are also a bit interesting in that they may be unbaked TypeBuilders.
            m_returnType = returnType;
            if (parameterTypes != null)
            {
                m_parameterTypes = new Type[parameterTypes.Length];
                Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
            }
            else
            {
                m_parameterTypes = EmptyArray<Type>.Value; 
            }
   
            m_module = mod;
            m_containingType = arrayClass;
            m_name = methodName;
            m_callingConvention = callingConvention;

            m_signature = SignatureHelper.GetMethodSigHelper(
                mod, callingConvention, returnType, null, null, parameterTypes, null, null);
        }
Example #5
0
 public Scope(ModuleBuilder moduleBuilder)
 {
     _vars = new Dictionary<string, ParameterExpression>();
     _types = new Dictionary<string, Type>();
     _func = new Dictionary<string, LambdaExpression>();
     _moduleBuilder = moduleBuilder;
 }
Example #6
0
        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);
        }
 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);
		}
 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));
     }
 }
Example #10
0
 static PropertyAccessor()
 {
     AssemblyName asmName = new AssemblyName();
     asmName.Name = "$Assembly.Hprose.IO.PropertyAccessor";
     asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
     modBuilder = asmBuilder.DefineDynamicModule("$Module.PropertyAccessor");
 }
Example #11
0
 static MethodInvoker(){
   MethodInvoker.invokerFor = new SimpleHashtable(64);
   AssemblyName name = new AssemblyName();
   name.Name = "JScript MethodInvoker Assembly";
   MethodInvoker.assembly = Thread.GetDomain().DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
   MethodInvoker.module = MethodInvoker.assembly.DefineDynamicModule("JScript MethodInvoker Module");
 }
Example #12
0
 public DataTypeBuilder(string name)
 {
     var assemblyName = new AssemblyName {Name = name};
     _moduleBuilder =
         AppDomain.CurrentDomain.DefineDynamicAssembly(
             assemblyName, AssemblyBuilderAccess.Run).DefineDynamicModule(name);
 }
 internal ModuleBuilderData(ModuleBuilder module, string strModuleName, string strFileName, int tkFile)
 {
     this.m_globalTypeBuilder = new TypeBuilder(module);
     this.m_module = module;
     this.m_tkFile = tkFile;
     this.InitNames(strModuleName, strFileName);
 }
Example #14
0
        internal static Type makeRecord(String name,Type basetype)
        {
            if(assembly == null)
            {
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = "RecordAssembly";
            assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,AssemblyBuilderAccess.Run);
            module = assembly.DefineDynamicModule("RecordModule");
            }

            TypeBuilder tb = module.DefineType(name,TypeAttributes.Class|TypeAttributes.Public,basetype);
            Type[] paramTypes = Type.EmptyTypes;
            ConstructorBuilder cb = tb.DefineConstructor(MethodAttributes.Public,
                                                                    CallingConventions.Standard,
                                                                    paramTypes);
            ILGenerator constructorIL = cb.GetILGenerator();
            constructorIL.Emit(OpCodes.Ldarg_0);
            ConstructorInfo superConstructor = basetype.GetConstructor(Type.EmptyTypes);
            constructorIL.Emit(OpCodes.Call, superConstructor);
            constructorIL.Emit(OpCodes.Ret);

            Type t = tb.CreateType();
            //Import.AddType(t); //must do in lisp
            return t;
        }
Example #15
0
        // Главная функция кодогенератора. Получает на вход синтаксическое дерево, обходит его и в хое его обхода с
        //     помощью библиотеки System.Reflection строит исполняемый файл на MSIL, который потом можно запускать вне компилятора (однако, на компьютере должна быть установлена .Net Framwork)
        //     Путь к файлу задаётся в интерфейсе компилятора
        public bool Proceed(Node Tree, RichTextBox RTB, string FileName)
        {
            _Tree = Tree;
            _RTB  = RTB;
            InitFileName(FileName);

            try
            {
                Reflect.AssemblyName Name = new Reflect.AssemblyName(FileName);
                AsmBuilder       = System.AppDomain.CurrentDomain.DefineDynamicAssembly(Name, Emit.AssemblyBuilderAccess.Save);
                ModBuilder       = AsmBuilder.DefineDynamicModule(FileName);
                TypeTable        = new Collections.Dictionary <string, Emit.TypeBuilder>();
                CreatedTypeTable = new Collections.Dictionary <string, System.Type>();
                SymbolTable      = new Collections.List <Collections.Dictionary <string, Emit.LocalBuilder> >();

                BeforeCompile(Tree);
                CreateCode(Tree);

                AsmBuilder.Save(FileName);
                this.SymbolTable        = null;
                this.AssemblerGenerator = null;
                this.TypeTable          = null;

                File.Move(FileName, FileName + ".exe");
                File.Delete(FileName);

                return(true);
            }
            catch (System.Exception Exc)
            {
                _RTB.Text = Exc.Message;

                return(false);
            }
        }
Example #16
0
		public AssemblyEmitter( string assemblyName, bool canSave )
		{
			m_AssemblyName = assemblyName;

			m_AppDomain = AppDomain.CurrentDomain;

			m_AssemblyBuilder = m_AppDomain.DefineDynamicAssembly(
				new AssemblyName( assemblyName ),
				canSave ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run
			);

			if ( canSave )
			{
				m_ModuleBuilder = m_AssemblyBuilder.DefineDynamicModule(
					assemblyName,
					String.Format( "{0}.dll", assemblyName.ToLower() ),
					false
				);
			}
			else
			{
				m_ModuleBuilder = m_AssemblyBuilder.DefineDynamicModule(
					assemblyName,
					false
				);
			}
		}
Example #17
0
        public MethodInfo GetInvokeMethod(string methodName, Type returnType, Type[] types)
        {
            string entryName = methodName;
            if (assemblyBuilder == null)
            {
                AssemblyName assemblyName = new AssemblyName(AssemblyName);
                assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                moduleBuilder = assemblyBuilder.DefineDynamicModule(AssemblyName);
            }

            var defineType = moduleBuilder.DefineType(GetDefineTypeName(methodName));
            var methodBuilder = defineType.DefinePInvokeMethod(methodName, dllName, entryName,
                       MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
                       CallingConventions.Standard,
                       returnType, types,
                       CallingConvention, CharSet);
            if ((returnType != null) && (returnType != typeof(void)))
            {
                methodBuilder.SetImplementationFlags(MethodImplAttributes.PreserveSig | methodBuilder.GetMethodImplementationFlags());
            }
            var type = defineType.CreateType();

            var method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
            return method;
        }
Example #18
0
        static XmlILModule() {
            AssemblyName asmName;
            AssemblyBuilder asmBldr;

            CreateModulePermissionSet = new PermissionSet(PermissionState.None);
            // CreateDelegate demands MemberAccess permission
            CreateModulePermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            // DynamicMethod constructor demands ControlEvidence permissions. 
            // Emitting symbols in DefineDynamicModule (to allow to debug the stylesheet) requires UnmanagedCode permission. 
            CreateModulePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.UnmanagedCode));

            AssemblyId = 0;

            // 1. LRE assembly only needs to execute
            // 2. No temp files need be created
            // 3. Never allow assembly to Assert permissions
            asmName = CreateAssemblyName();
            asmBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);

            try {
                CreateModulePermissionSet.Assert();

                // Add custom attribute to assembly marking it as security transparent so that Assert will not be allowed
                // and link demands will be converted to full demands.
                asmBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.Transparent, new object[] {}));

                // Store LREModule once.  If multiple threads are doing this, then some threads might get different
                // modules.  This is OK, since it's not mandatory to share, just preferable.
                LREModule = asmBldr.DefineDynamicModule("System.Xml.Xsl.CompiledQuery", false);
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
        }
Example #19
0
 public GenContext(string assyName, string directory, CompilerMode mode)
 {
     AssemblyName aname = new AssemblyName(assyName);
     _assyBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(aname, AssemblyBuilderAccess.RunAndSave,directory);
     _moduleBldr = _assyBldr.DefineDynamicModule(aname.Name, aname.Name + ".dll", true);
     _mode = mode;
 }
Example #20
0
 static FieldAccessor(){
   FieldAccessor.accessorFor = new SimpleHashtable(32);
   AssemblyName name = new AssemblyName();
   name.Name = "JScript FieldAccessor Assembly";
   FieldAccessor.assembly = Thread.GetDomain().DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
   FieldAccessor.module = FieldAccessor.assembly.DefineDynamicModule("JScript FieldAccessor Module");
 }
        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;
        }
		public NavigatorProxyBuilder(ModuleBuilder moduleBuilder, string className, Type interfaceType, Type innerType)
			: base(moduleBuilder, className, interfaceType, innerType)
		{
			_navigateValues = new List<string>();

			_innerNavigateMethod = FindInnerNavigateMethod(innerType);
			if (_innerNavigateMethod == null)
			{
				AddErrorMessage("Cannot find method with signature 'void Navigate(string)' in type {0}", innerType);
			}

			_innerCanNavigateMethod = FindInnerCanNavigateMethod(innerType);
			if (_innerCanNavigateMethod == null)
			{
				AddErrorMessage("Cannot find method with signature 'bool CanNavigate(string)' in type {0}", innerType);
			}

			_outerNavigateEnumMethod = FindOuterNavigateEnumMethod(interfaceType);
			if (_outerNavigateEnumMethod != null)
			{
				_navigateValueEnumType = _outerNavigateEnumMethod.GetParameters()[0].ParameterType;
				_outerCanNavigateEnumMethod = FindOuterCanNavigateEnumMethod(interfaceType, _navigateValueEnumType);
				_navigateValues.AddRange(Enum.GetNames(_navigateValueEnumType));
			}

			FindEvents();
			_outerNavigateMethods = FindOuterNavigateMethods();
			_outerCanNavigateProperties = FindOuterCanNavigateProperties();
		}
Example #23
0
 public static void Clear()
 {
     _dynamicAssembly = null;
     _moduleBuilder = null;
     _typeBuilder = null;
     _accessorList.Clear();
 }
Example #24
0
        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);

        }
Example #25
0
    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 DynamicAssemblyManager()
        {
#if !SILVERLIGHT
            assemblyName = new AssemblyName("NLiteDynamicAssembly");
            assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                assemblyName,
                AssemblyBuilderAccess.RunAndSave
                );

            moduleBuilder = assemblyBuilder.DefineDynamicModule(
                assemblyName.Name,
                assemblyName.Name + ".dll",
                true);

            Module = assemblyBuilder.GetModules().FirstOrDefault();
           
#else
            assemblyName = new AssemblyName("EmitMapperAssembly.SL");
            assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                  assemblyName,
                  AssemblyBuilderAccess.Run
                  );
            moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, true);
#endif
        }
        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();
        }
		/// <summary>
		///		Initializes a new instance of the <see cref="SerializerEmitter"/> class for enum.
		/// </summary>
		/// <param name="context">A <see cref="SerializationContext"/>.</param>
		/// <param name="host">The host <see cref="ModuleBuilder"/>.</param>
		/// <param name="specification">The specification of the serializer.</param>
		/// <param name="isDebuggable">Set to <c>true</c> when <paramref name="host"/> is debuggable.</param>
		public SerializerEmitter( SerializationContext context, ModuleBuilder host, SerializerSpecification specification, bool isDebuggable )
			: this( host, specification, typeof( EnumMessagePackSerializer<> ).MakeGenericType( specification.TargetType ), isDebuggable )
		{
			Tracer.Emit.TraceEvent( Tracer.EventType.DefineType, Tracer.EventId.DefineType, "Create {0}", specification.SerializerTypeFullName );

			this._defaultEnumSerializationMethod = context.EnumSerializationOptions.SerializationMethod;
		}
Example #29
0
 private void CreateCallee()
 {
     AssemblyName myAssemblyName = new AssemblyName();
     myAssemblyName.Name = "EnumAssembly";
     _myAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
     _myModuleBuilder = TestLibrary.Utilities.GetModuleBuilder(_myAssemblyBuilder, "EnumModule.mod");
 }
Example #30
0
 public Type Compile(IMetadataSchema schema, ModuleBuilder module, string @namespace, string typeName)
 {
     if (schema == null)
     {
         throw new ArgumentNullException(nameof(schema));
     }
     if (schema.Definitions == null)
     {
         throw new ArgumentException("There is no definition is schema.", nameof(schema));
     }
     if (module == null)
     {
         throw new ArgumentNullException(nameof(module));
     }
     if (@namespace == null)
     {
         throw new ArgumentNullException(nameof(@namespace));
     }
     if (string.IsNullOrWhiteSpace(@namespace))
     {
         throw new ArgumentException("namespace cannot be white space.", nameof(@namespace));
     }
     if (typeName == null)
     {
         throw new ArgumentNullException(nameof(typeName));
     }
     if (string.IsNullOrWhiteSpace(typeName))
     {
         throw new ArgumentException("typeName cannot be white space.", nameof(typeName));
     }
     ValidateProperties();
     return CompileCore(schema, module, @namespace, typeName);
 }
 static RuntimeTypeProvider()
 {
     ModuleBuilder = Thread
         .GetDomain()
         .DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess.Run)
         .DefineDynamicModule(AssemblyName.Name);
 }
Example #32
0
 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;
 }
Example #33
0
        public override void GenerateCode(ILGenerator codeGenerator, TypeBuilder typeBuilder, ModuleBuilder moduleBuilder)
        {
            LeftOperand.GenerateCode(codeGenerator, typeBuilder, moduleBuilder);
            RightOperand.GenerateCode(codeGenerator, typeBuilder, moduleBuilder);

            Label endLabel = codeGenerator.DefineLabel();
            Label trueLabel = codeGenerator.DefineLabel();

            if (LeftOperand.ReturnType == StringType.StringInstance)
            {
                codeGenerator.Emit(OpCodes.Call, typeof(String).GetMethod("CompareTo", new Type[] { typeof(string) }));
                codeGenerator.Emit(OpCodes.Ldc_I4_0);
                codeGenerator.Emit(OpCodes.Bne_Un, trueLabel);
            }
            else
                codeGenerator.Emit(OpCodes.Bne_Un, trueLabel);

            codeGenerator.Emit(OpCodes.Ldc_I4_0);
            codeGenerator.Emit(OpCodes.Br, endLabel);

            codeGenerator.MarkLabel(trueLabel);
            codeGenerator.Emit(OpCodes.Ldc_I4_1);

            codeGenerator.MarkLabel(endLabel);
        }
Example #34
0
        public static RowViewModelBase Create(ModuleBuilder mb, SpreadsheetViewModel viewModel, int rowNumber, int columns)
        {
            if (RowType == null)
                RowType = CreateType(mb, columns);

            return (RowViewModelBase)Activator.CreateInstance(RowType, viewModel, rowNumber);
        }
Example #35
0
 private static System.Reflection.Emit.ModuleBuilder GetDynamicModule()
 {
     if (DynamicAssembly == null)
     {
         DynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run);
         ModuleBuilder   = DynamicAssembly.DefineDynamicModule("MainModule");
     }
     return(ModuleBuilder);
 }
 public WrappedPropertyProxyBuilder(ModuleDefinition module,
                                    TypeReference proxyBaseTypeDef,
                                    TypeReference propertyWrapperType,
                                    bool isPublic         = true,
                                    string typeNameFormat = "Fast{0}Proxy",
                                    string proxyNamespace = null)
     : base(module, typeNameFormat, proxyBaseTypeDef, isPublic, proxyNamespace: proxyNamespace)
 {
     this.propertyWrapperType = propertyWrapperType;
 }
        internal ReflectionEmitModuleInfo(ScriptEngine engine)
        {
            Engine = engine;

            // Create a dynamic assembly and module.
            AssemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(
                new AssemblyName("Nitro Dynamic Assembly"), AssemblyBuilderAccess.Run);

            // Create a dynamic module.
            ModuleBuilder = AssemblyBuilder.DefineDynamicModule("Module", ScriptEngine.EnableDebugging);
        }
Example #38
0
 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();
 }
Example #39
0
 public ProxyBuilder(
     ModuleDefinition module,
     string proxyNameFormat,
     TypeReference proxyBaseTypeDef,
     bool isPublic,
     Action <PropertyInfo, PropertyDefinition, TypeReference, TypeReference> onGeneratePropertyMethodsFunc =
     null,
     string proxyNamespace = null)
 {
     this.proxyNamespace = proxyNamespace ?? module.Assembly.GetName().Name;
     Module = module;
     this.proxyBaseTypeDef = proxyBaseTypeDef;
     this.onGeneratePropertyMethodsFunc = onGeneratePropertyMethodsFunc;
     this.proxyNameFormat = proxyNameFormat;
     this.isPublic        = isPublic;
 }
Example #40
0
        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);
        }
Example #42
0
        public AssemblyGen(TypeDeclaration methodDec, string moduleName, string dllProbeDirectory)
        {
            if (IO.Path.GetFileName(moduleName) != moduleName)
            {
                throw new System.Exception("can only output into current directory!");
            }

            this.dllProbeDirectory = dllProbeDirectory;

            typeList = new List <TypeGen>();

            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);
            GenerateType(methodDec, modb, dllProbeDirectory);
            modb.CreateGlobalFunctions();
            asmb.SetEntryPoint(GetEntryPoint());
            asmb.Save(moduleName);
        }
Example #43
0
    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);
    }
Example #44
0
            internal RefEmit.ModuleBuilder GetOrCreateDynamicModule()
            {
                if (dynamicModule == null)
                {
                    DebuggerUtilities.CallBeforeAcquiringLock(); //see method comment

                    lock (this)
                    {
                        if (dynamicModule == null)
                        {
                            dynamicModule = CreateDynamicModule(
#if DEBUG
                                EnableAssemblySave ? RefEmit.AssemblyBuilderAccess.RunAndSave :
#endif
                                RefEmit.AssemblyBuilderAccess.Run, dynamicAssemblyName, UncollectibleModuleFileName);
                        }
                    }
                }

                return(dynamicModule);
            }
Example #45
0
        private void GenerateType(TypeDeclaration typeDec, Emit.ModuleBuilder modb, string dllProbeDirectory)
        {
            TypeDeclaration temp = null;
            bool            flag = true;

            while (flag)
            {
                if (typeDec is TypeSequence)
                {
                    temp    = (typeDec as TypeSequence).First;
                    typeDec = (typeDec as TypeSequence).Second;
                }
                else
                {
                    temp = typeDec;
                    flag = false;
                }
                child = new TypeGen(temp, modb, dllProbeDirectory, this);
                child.GenerateCode();
                typeList.Add(child);
            }
        }
Example #46
0
    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);
    }
Example #47
0
 internal MethodToken GetToken(ModuleBuilder mod)
 {
     return(mod.GetArrayMethodToken(this.m_containingType, this.m_name, this.m_callingConvention, this.m_returnType, this.m_parameterTypes));
 }
 internal ModuleBuilderData(ModuleBuilder module, String strModuleName, String strFileName)
 {
     Init(module, strModuleName, strFileName);
 }
Example #49
0
        internal void CreateMethodBodyHelper(ILGenerator il)
        {
            // Sets the IL of the method.  An ILGenerator is passed as an argument and the method
            // queries this instance to get all of the information which it needs.
            if (il == null)
            {
                throw new ArgumentNullException(nameof(il));
            }

            __ExceptionInfo[] excp;
            int counter = 0;

            int[]         filterAddrs;
            int[]         catchAddrs;
            int[]         catchEndAddrs;
            Type[]        catchClass;
            int[]         type;
            int           numCatch;
            int           start, end;
            ModuleBuilder dynMod = (ModuleBuilder)m_module;

            m_containingType.ThrowIfCreated();

            if (m_bIsBaked)
            {
                throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody);
            }

            if (il.m_methodBuilder != this && il.m_methodBuilder != null)
            {
                // you don't need to call DefineBody when you get your ILGenerator
                // through MethodBuilder::GetILGenerator.
                //

                throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage);
            }

            ThrowIfShouldNotHaveBody();

            if (il.m_ScopeTree.m_iOpenScopeCount != 0)
            {
                // There are still unclosed local scope
                throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope);
            }


            m_ubBody = il.BakeByteArray();

            m_mdMethodFixups = il.GetTokenFixups();

            //Okay, now the fun part.  Calculate all of the exceptions.
            excp = il.GetExceptions();
            int numExceptions = CalculateNumberOfExceptions(excp);

            if (numExceptions > 0)
            {
                m_exceptions = new ExceptionHandler[numExceptions];

                for (int i = 0; i < excp.Length; i++)
                {
                    filterAddrs   = excp[i].GetFilterAddresses();
                    catchAddrs    = excp[i].GetCatchAddresses();
                    catchEndAddrs = excp[i].GetCatchEndAddresses();
                    catchClass    = excp[i].GetCatchClass();

                    numCatch = excp[i].GetNumberOfCatches();
                    start    = excp[i].GetStartAddress();
                    end      = excp[i].GetEndAddress();
                    type     = excp[i].GetExceptionTypes();
                    for (int j = 0; j < numCatch; j++)
                    {
                        int tkExceptionClass = 0;
                        if (catchClass[j] != null)
                        {
                            tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token;
                        }

                        switch (type[j])
                        {
                        case __ExceptionInfo.None:
                        case __ExceptionInfo.Fault:
                        case __ExceptionInfo.Filter:
                            m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
                            break;

                        case __ExceptionInfo.Finally:
                            m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
                            break;
                        }
                    }
                }
            }


            m_bIsBaked = true;

            if (dynMod.GetSymWriter() != null)
            {
                // set the debugging information such as scope and line number
                // if it is in a debug module
                //
                SymbolToken   tk        = new SymbolToken(MetadataTokenInternal);
                ISymbolWriter symWriter = dynMod.GetSymWriter();

                // call OpenMethod to make this method the current method
                symWriter.OpenMethod(tk);

                // call OpenScope because OpenMethod no longer implicitly creating
                // the top-levelsmethod scope
                //
                symWriter.OpenScope(0);

                if (m_symCustomAttrs != null)
                {
                    foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
                    {
                        dynMod.GetSymWriter().SetSymAttribute(
                            new SymbolToken(MetadataTokenInternal),
                            symCustomAttr.m_name,
                            symCustomAttr.m_data);
                    }
                }

                if (m_localSymInfo != null)
                {
                    m_localSymInfo.EmitLocalSymInfo(symWriter);
                }
                il.m_ScopeTree.EmitScopeTree(symWriter);
                il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
                symWriter.CloseScope(il.ILOffset);
                symWriter.CloseMethod();
            }
        }
Example #50
0
        private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention,
                          Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
                          Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
                          ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (name.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
            }

            if (name[0] == '\0')
            {
                throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
            }

            if (mod == null)
            {
                throw new ArgumentNullException(nameof(mod));
            }

            if (parameterTypes != null)
            {
                foreach (Type t in parameterTypes)
                {
                    if (t == null)
                    {
                        throw new ArgumentNullException(nameof(parameterTypes));
                    }
                }
            }

            m_strName        = name;
            m_module         = mod;
            m_containingType = type;

            //
            //if (returnType == null)
            //{
            //    m_returnType = typeof(void);
            //}
            //else
            {
                m_returnType = returnType;
            }

            if ((attributes & MethodAttributes.Static) == 0)
            {
                // turn on the has this calling convention
                callingConvention = callingConvention | CallingConventions.HasThis;
            }
            else if ((attributes & MethodAttributes.Virtual) != 0)
            {
                // A method can't be both static and virtual
                throw new ArgumentException(SR.Arg_NoStaticVirtual);
            }

            if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName)
            {
                if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface)
                {
                    // methods on interface have to be abstract + virtual except special name methods such as type initializer
                    if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
                        (MethodAttributes.Abstract | MethodAttributes.Virtual) &&
                        (attributes & MethodAttributes.Static) == 0)
                    {
                        throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod);
                    }
                }
            }

            m_callingConvention = callingConvention;

            if (parameterTypes != null)
            {
                m_parameterTypes = new Type[parameterTypes.Length];
                Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
            }
            else
            {
                m_parameterTypes = null;
            }

            m_returnTypeRequiredCustomModifiers    = returnTypeRequiredCustomModifiers;
            m_returnTypeOptionalCustomModifiers    = returnTypeOptionalCustomModifiers;
            m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
            m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;

            //            m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
            //                returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
            //                parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);

            m_iAttributes     = attributes;
            m_bIsGlobalMethod = bIsGlobalMethod;
            m_bIsBaked        = false;
            m_fInitLocals     = true;

            m_localSymInfo = new LocalSymInfo();
            m_ubBody       = null;
            m_ilGenerator  = null;

            // Default is managed IL. Manged IL has bit flag 0x0020 set off
            m_dwMethodImplFlags = MethodImplAttributes.IL;
        }
Example #51
0
 public ModuleBuilderTokenGenerator(ModuleBuilder mb)
 {
     this.mb = mb;
 }
Example #52
0
 private static extern int getUSIndex(ModuleBuilder mb, string str);
Example #53
0
 private static extern int getToken(ModuleBuilder mb, object obj, bool create_open_instance);
Example #54
0
 private static extern int getMethodToken(ModuleBuilder mb, MethodBase method,
                                          Type[] opt_param_types);
Example #55
0
 private static extern void basic_init(ModuleBuilder ab);
Example #56
0
 private static extern void set_wrappers_type(ModuleBuilder mb, Type?ab);
Example #57
0
        public void CreateAssembly()
        {
            // we need to process global assembly attributes before creating assembly name
            _assembly_name = CreateAssemblyName();

            _assembly_name.Name = Path.GetFileNameWithoutExtension(_OutputFileName);

            var assembly_requirements =
                (Manager.Options.CompileToMemory)
                    ? Emit.AssemblyBuilderAccess.Run
                    : Emit.AssemblyBuilderAccess.Save;

            var dir = Path.GetDirectoryName(Path.GetFullPath(_OutputFileName));
            if (!Directory.Exists(dir))
                Message.FatalError($"specified output directory `$dir' does not exist");

            PermissionSet required;
            PermissionSet optional;
            PermissionSet refused;

            foreach ((action, perm_set) in Manager.AttributeCompiler.GetPermissionSets(assembly_attributes))
            {
                switch (action)
                {
                    case Permissions.SecurityAction.RequestMinimum:
                        required = perm_set;
                        break;
                    case Permissions.SecurityAction.RequestOptional:
                        optional = perm_set;
                        break;
                    case Permissions.SecurityAction.RequestRefuse:
                        refused = perm_set;
                        break;
                    default:
                        Message.FatalError($"$action is not valid here");
                        break;
                }
            }

            /* define a dynamic assembly */
            this._assembly_builder =
                System.AppDomain.CurrentDomain.DefineDynamicAssembly
                (this._assembly_name,
                    assembly_requirements,
                    dir, required, optional, refused);

            GetInformationalAssemblyAttributes().Iter(this._assembly_builder.SetCustomAttribute);

            if (_assembly_name.Name == "")
                Message.FatalError("name of output assembly cannot be empty");

            /* create a dynamic module */
            this._module_builder =
                (Manager.Options.CompileToMemory)
                    // we cannot give output filename if we are compiling only to Run
                    ? this._assembly_builder.DefineDynamicModule(_assembly_name.Name, Manager.Options.EmitDebug)
                    : this._assembly_builder.DefineDynamicModule(_assembly_name.Name,
                        Path.GetFileName(_OutputFileName),
                        Manager.Options.EmitDebug);

            if (Manager.Options.EmitDebug)
                _debug_emit = _module_builder.GetSymWriter();
        }
Example #58
0
 internal ConstructorBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention,
                             Type[]?parameterTypes, ModuleBuilder mod, TypeBuilder type) :
     this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
 {
 }
        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
        }
Example #60
0
 internal QCallModule(ref System.Reflection.Emit.ModuleBuilder module)
 {
     _ptr    = Unsafe.AsPointer(ref module);
     _module = module.GetNativeHandle().GetUnderlyingNativeHandle();
 }