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 ); } }
/// <summary> /// Creates a new TypeBuilder in the given domain /// </summary> /// <param name="domain">The domain.</param> /// <param name="assemblyNameStr">The assembly name string.</param> /// <param name="dynamicModuleName">Name of the dynamic module.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public static TypeBuilder GetClassTypeBuilder(AppDomain domain, string assemblyNameStr, string dynamicModuleName, string typeName) { AssemblyName assemblyName = new AssemblyName(assemblyNameStr); AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder module = assemblyBuilder.DefineDynamicModule(dynamicModuleName); return module.DefineType(typeName, TypeAttributes.Public | TypeAttributes.Class); }
// 调用者传入一个AppDomain类型 public static void CreateMyAsm(AppDomain curAppDomain) { // 建立通用的程序集特征 AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "MyAssembly"; assemblyName.Version = new Version("1.0.0.0"); // 在当前AppDomain(应用程序域)中创建一个新的程序集 AssemblyBuilder assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save); // 鉴于我们构造的是一个单文件程序集,模块的名字就是程序集的名字 ModuleBuilder module = assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll"); // 定义一个公共类“HelloWorld” TypeBuilder helloWorldClass = module.DefineType("MyAssembly.HelloWorld", TypeAttributes.Public); // 定义一个私有字符串成员变量“theMessage” FieldBuilder msgField = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"), FieldAttributes.Private); // 创建自定义的构造函数 Type[] constructorArgs = new Type[1]; constructorArgs[0] = typeof(string); ConstructorBuilder constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs); ILGenerator constructorIL = constructor.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); Type objectClass = typeof(object); ConstructorInfo superConstructor = objectClass.GetConstructor(new Type[0]); constructorIL.Emit(OpCodes.Call, superConstructor); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Ldarg_1); constructorIL.Emit(OpCodes.Stfld, msgField); constructorIL.Emit(OpCodes.Ret); helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public); MethodBuilder getMsgMethod = helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, typeof(string), null); ILGenerator methodIL = getMsgMethod.GetILGenerator(); methodIL.Emit(OpCodes.Ldarg_0); methodIL.Emit(OpCodes.Ldfld, msgField); methodIL.Emit(OpCodes.Ret); MethodBuilder sayHiMethod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null); methodIL = sayHiMethod.GetILGenerator(); methodIL.EmitWriteLine("Hello form the HelloWorld class!"); methodIL.Emit(OpCodes.Ret); helloWorldClass.CreateType(); assembly.Save("MyAssembly.dll"); }
public MainWindow() { Microsoft.CodeAnalysis.CSharp.Scrip InitializeComponent(); otherDomain = AppDomain.CreateDomain("Other"); otherDomain.DefineDynamicAssembly(new AssemblyName("Fiddle.dll"), AssemblyBuilderAccess.RunAndCollect); otherDomain.AssemblyLoad += Executor.CurrentDomain_AssemblyLoad; }
public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name) { #if DEBUG AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; #else AssemblyBuilderAccess access = AssemblyBuilderAccess.Run; #endif return appDomain.DefineDynamicAssembly(name, access); }
public void BeginModule(string ifile) { appdomain = System.Threading.Thread.GetDomain(); appname = getAssemblyName(filename); appbuild = appdomain.DefineDynamicAssembly(appname, AssemblyBuilderAccess.Save, "."); emodule = appbuild.DefineDynamicModule(filename + "_module", io.GetOutputFilename(), io.getGenDebug()); Guid g = System.Guid.Empty; if (io.getGenDebug()) srcdoc = emodule.DefineDocument(ifile, g, g, g); }
public EmitTranslator(AppDomain hostDomain, string name) { AssemblyName asmName = new AssemblyName(name); m_assembly = hostDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); m_module = m_assembly.DefineDynamicModule(name + ".exe", true); m_typeTable = new ExtensionTable<Type>(); m_methodTable = new ExtensionTable<MethodInfo>(); m_ctorTable = new ExtensionTable<ConstructorInfo>(); m_fieldTable = new ExtensionTable<FieldInfo>(); }
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); }
static void CreateMyAsm(AppDomain currAppDomain) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "MyAssembly"; assemblyName.Version = new Version("1.0.0.0"); AssemblyBuilder assembly = currAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save); ModuleBuilder module = assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll"); TypeBuilder helloWorldClass = module.DefineType("MyAssembly.HelloWorld", TypeAttributes.Public); FieldBuilder msgField = helloWorldClass.DefineField("theMessage", typeof(string), FieldAttributes.Private); Type[] constructorArgs = new Type[1]; constructorArgs[0] = typeof(string); ConstructorBuilder constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs); ILGenerator constructorIL = constructor.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); Type objectClass = typeof(object); ConstructorInfo superConstructor = objectClass.GetConstructor(new Type[0]); constructorIL.Emit(OpCodes.Call, superConstructor); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Ldarg_1); constructorIL.Emit(OpCodes.Stfld, msgField); constructorIL.Emit(OpCodes.Ret); helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public); MethodBuilder getMsgMethod = helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, typeof(string), null); ILGenerator methodIL = getMsgMethod.GetILGenerator(); methodIL.Emit(OpCodes.Ldarg_0); methodIL.Emit(OpCodes.Ldfld, msgField); methodIL.Emit(OpCodes.Ret); MethodBuilder sayHiMethod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null); methodIL = sayHiMethod.GetILGenerator(); methodIL.EmitWriteLine("Hello from the HelloWorld class"); methodIL.Emit(OpCodes.Ret); helloWorldClass.CreateType(); assembly.Save("MyAssembly.dll"); }
public ClassDeserializer(ClassManager parent) { m_parent = parent; var an = new AssemblyName() { Name = "HelloReflectionEmit" }; m_ad = AppDomain.CurrentDomain; m_ab = m_ad.DefineDynamicAssembly(an, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave); m_mb = m_ab.DefineDynamicModule(an.Name, "Hello.exe"); m_stack = new Stack<ClassFrame>(); }
public void BeginModule(string fileName) { FileInfo f = new FileInfo(fileName); appDomain = Thread.GetDomain(); asmName = new AssemblyName(); asmName.Name = f.Name; asmBuilder = appDomain.DefineDynamicAssembly( asmName, AssemblyBuilderAccess.RunAndSave, f.DirectoryName ); modBuilder = asmBuilder.DefineDynamicModule( asmName.Name, asmName.Name); }
/// <summary> /// Create new enum from arrays /// </summary> /// <param name="list">List with the values for the new enum</param> /// <param name="currentEnumValue">Value to set to the new enum</param> /// <returns></returns> public static System.Enum CreateEnumFromArrays(List <string> list, int currentEnumValue) { System.AppDomain currentDomain = System.AppDomain.CurrentDomain; AssemblyName assemblyName = new AssemblyName("EnumSoundType"); AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.ReflectionOnly); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); EnumBuilder enumBuilder = moduleBuilder.DefineEnum("EnumSoundType", TypeAttributes.Public, typeof(int)); for (int i = 0; i < list.Count; i++) { enumBuilder.DefineLiteral(list[i], i); } System.Type tempSoundTypeEnum = enumBuilder.CreateType(); return((System.Enum)System.Enum.ToObject(tempSoundTypeEnum, currentEnumValue)); }
public static void Create( AppDomain domain, string asmName, string progName ) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = asmName; assemblyName.Version = new Version("1.0.0.0"); AssemblyBuilder assembler = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save); ModuleBuilder moduleBuilder = assembler.DefineDynamicModule( asmName, asmName + ".dll" ); TypeBuilder helloWorldBuilder = moduleBuilder.DefineType(asmName + "." + progName, TypeAttributes.Public); FieldBuilder fieldBuilder = helloWorldBuilder.DefineField("theMessage", Type.GetType("System.String"), FieldAttributes.Private); Type[] constructorArgs = new Type[1]; constructorArgs[0] = typeof (string); ConstructorBuilder constructor = helloWorldBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs); ILGenerator constructorIl = constructor.GetILGenerator(); constructorIl.Emit(OpCodes.Ldarg_0); Type objectClass = typeof(object); ConstructorInfo superConstructor = objectClass.GetConstructor(new Type[0]); constructorIl.Emit(OpCodes.Call, superConstructor); constructorIl.Emit( OpCodes.Ldarg_0 ); constructorIl.Emit( OpCodes.Ldarg_1 ); constructorIl.Emit( OpCodes.Stfld, fieldBuilder ); constructorIl.Emit( OpCodes.Ret ); helloWorldBuilder.DefineDefaultConstructor(MethodAttributes.Public); MethodBuilder methodBuilder = helloWorldBuilder.DefineMethod("GetMsg", MethodAttributes.Public, typeof (string), null); ILGenerator methodIl = methodBuilder.GetILGenerator(); methodIl.Emit( OpCodes.Ldarg_0 ); methodIl.Emit( OpCodes.Ldfld, fieldBuilder ); methodIl.Emit( OpCodes.Ret ); MethodBuilder executor = helloWorldBuilder.DefineMethod("SayHello", MethodAttributes.Public, null, null); methodIl = executor.GetILGenerator(); methodIl.EmitWriteLine("Hello from the HelloWorld class!"); methodIl.Emit(OpCodes.Ret); helloWorldBuilder.CreateType(); assembler.Save( asmName + ".dll" ); }
//Create new enum from arrays public static System.Enum CreateEnum(List <string> list) { System.AppDomain currentDomain = System.AppDomain.CurrentDomain; AssemblyName aName = new AssemblyName("Enum"); AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); EnumBuilder enumerator = mb.DefineEnum("Enum", TypeAttributes.Public, typeof(int)); int i = 0; enumerator.DefineLiteral("None", i); //Here = enum{ None } foreach (string names in list) { i++; enumerator.DefineLiteral(names, i); } //Here = enum { None, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } System.Type finished = enumerator.CreateType(); return((System.Enum)System.Enum.ToObject(finished, 0)); }
// The caller sends in an AppDomain type. public static void CreateMyAsm(AppDomain curAppDomain) { // Establish general assembly characteristics. AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "MyAssembly"; assemblyName.Version = new Version("1.0.0.0"); // Create new assembly within the current AppDomain. AssemblyBuilder assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save); // Given that we are building a single-file // assembly, the name of the module is the same as the assembly. ModuleBuilder module = assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll"); // Define a public class named "HelloWorld". TypeBuilder helloWorldClass = module.DefineType("MyAssembly.HelloWorld", TypeAttributes.Public); // Define a private String member variable named "theMessage". FieldBuilder msgField = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"), FieldAttributes.Private); // Create the custom ctor. Type[] constructorArgs = new Type[1]; constructorArgs[0] = typeof(string); ConstructorBuilder constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs); ILGenerator constructorIL = constructor.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); Type objectClass = typeof(object); ConstructorInfo superConstructor = objectClass.GetConstructor(new Type[0]); constructorIL.Emit(OpCodes.Call, superConstructor); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Ldarg_1); constructorIL.Emit(OpCodes.Stfld, msgField); constructorIL.Emit(OpCodes.Ret); // Create the default ctor. helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public); // Now create the GetMsg() method. MethodBuilder getMsgMethod = helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, typeof(string), null); ILGenerator methodIL = getMsgMethod.GetILGenerator(); methodIL.Emit(OpCodes.Ldarg_0); methodIL.Emit(OpCodes.Ldfld, msgField); methodIL.Emit(OpCodes.Ret); // Create the SayHello method. MethodBuilder sayHiMethod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null); methodIL = sayHiMethod.GetILGenerator(); methodIL.EmitWriteLine("Hello from the HelloWorld class!"); methodIL.Emit(OpCodes.Ret); // 'Bake' the class HelloWorld. // (Baking is the formal term for emitting the type) helloWorldClass.CreateType(); // (Optionally) save the assembly to file. assembly.Save("MyAssembly.dll"); }
void Initialize(Universe universe, string assemblyName, AssemblyBuilderAccess access, CompilerOptions options, ITypeMapper typeMapper = null) { if (universe == null) throw new ArgumentNullException(nameof(universe)); if (options == null) throw new ArgumentNullException(nameof(options)); _compilerOptions = options; if (typeMapper == null) #if FEAT_IKVM typeMapper = new TypeMapper(universe); #else typeMapper = new TypeMapper(); #endif ExpressionFactory = new ExpressionFactory(typeMapper); StaticFactory = new StaticFactory(typeMapper); #if SILVERLIGHT bool save = false; #else bool save = (access & AssemblyBuilderAccess.Save) != 0; #endif string path = options.OutputPath; if (path == null && save) throw new ArgumentNullException("options.OutputPath"); Universe = universe; TypeMapper = typeMapper; _access = access; if (Helpers.IsNullOrEmpty(assemblyName)) { if (save) throw new ArgumentNullException(nameof(assemblyName)); assemblyName = Guid.NewGuid().ToString(); } string moduleName = path == null ? assemblyName : assemblyName + Path.GetExtension(path); _fileName = path; AssemblyName an = new AssemblyName(); an.Name = assemblyName; AssemblyBuilder = #if !SILVERLIGHT path != null ? Universe.DefineDynamicAssembly(an, access, Path.GetDirectoryName(path)) : #endif Universe.DefineDynamicAssembly(an, access); #if FEAT_IKVM if (!Helpers.IsNullOrEmpty(options.KeyFile)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(File.OpenRead(options.KeyFile))); } else if (!Helpers.IsNullOrEmpty(options.KeyContainer)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(options.KeyContainer)); } else if (!Helpers.IsNullOrEmpty(options.PublicKey)) { AssemblyBuilder.__SetAssemblyPublicKey(FromHex(options.PublicKey)); } if (!Helpers.IsNullOrEmpty(options.ImageRuntimeVersion) && options.MetaDataVersion != 0) { AssemblyBuilder.__SetImageRuntimeVersion(options.ImageRuntimeVersion, options.MetaDataVersion); } ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, path, options.SymbolInfo); #else if (save) { #if !SILVERLIGHT ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, Path.GetFileName(path)); #else throw new NotSupportedException("Can't save on this platform"); #endif } else ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName); #endif }
public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name) { return assembly ?? (assembly = appDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndSave)); }
static void DefineDynamicAssembly (AppDomain domain) { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "MyDynamicAssembly"; AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule ("MyDynamicModule"); TypeBuilder typeBuilder = moduleBuilder.DefineType ("MyDynamicType", TypeAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard, null); ILGenerator ilGenerator = constructorBuilder.GetILGenerator (); ilGenerator.EmitWriteLine ("MyDynamicType instantiated!"); ilGenerator.Emit (OpCodes.Ret); typeBuilder.CreateType (); }
/// <summary> /// Constructs a Program object with the given options and name. The name determines /// the module name and thus should be valid as per module name rules. The isExecutable /// flag specifies whether the program is directly executable and thus is an EXE file /// or is a library and thus is a DLL. /// </summary> /// <param name="opts">A set of options</param> /// <param name="name">String containing the program name</param> /// <param name="isExecutable">Specifies whether or not the program is directly executable</param> public Program(Options opts, string name, bool isExecutable) { if (opts == null) { throw new ArgumentNullException("opts"); } if (name == null) { throw new ArgumentNullException("name"); } _opts = opts; _isExecutable = isExecutable; _ad = AppDomain.CurrentDomain; _an = new AssemblyName(); // For .NET conventions, make the initial letter of the name // uppercase. name = name.CapitaliseString(); _an.Name = name; _an.Version = new Version(_opts.VersionString); bool isSaveable = !string.IsNullOrEmpty(opts.OutputFile); AssemblyBuilderAccess access = isSaveable ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run; _ab = _ad.DefineDynamicAssembly(_an, access); // Make this assembly debuggable if the debug option was specified. if (_opts.GenerateDebug) { AddDebuggable(_ab); } // Don't make the main class abstract if the program is being run from // memory as otherwise the caller will be unable to create an instance. TypeAttributes typeAttributes = TypeAttributes.Public; if (isSaveable) { _mb = _ab.DefineDynamicModule(name, OutputFilename, true); typeAttributes |= TypeAttributes.Abstract | TypeAttributes.Sealed; } else { _mb = _ab.DefineDynamicModule(name, true); } // Create an implicit namespace using the output file name if // one is specified. string className = string.Empty; if (!string.IsNullOrEmpty(opts.OutputFile)) { className = String.Concat(opts.OutputFile.CapitaliseString(), "."); } className = String.Concat(className, name); _tb = _mb.DefineType(className, typeAttributes); }
protected virtual AssemblyBuilder Initialise(AppDomain Domain, String AssembelyName, String ModuleName) { BaseAssemblyName = new AssemblyName(AssembelyName); BaseAssemblyBuilder = Domain.DefineDynamicAssembly(BaseAssemblyName, AssemblyBuilderAccess.Run); BaseModuleBuilder = BaseAssemblyBuilder.DefineDynamicModule(ModuleName); // Hook up the event listening. TypeResolveHandler typeResolveHandler = new TypeResolveHandler(BaseModuleBuilder); // Add a listener for the type resolve events. ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent); BaseAppDomain.TypeResolve += resolveHandler; return BaseAssemblyBuilder; }
void Initialize(AppDomain domain, AssemblyName name, AssemblyBuilderAccess access, string fileName, bool symbolInfo) { this.access = access; this.fileName = fileName; if (fileName == null && (access & AssemblyBuilderAccess.Save) != 0) throw new ArgumentNullException("fileName", Properties.Messages.ErrAsmMissingSaveFile); if (fileName == null) asm = domain.DefineDynamicAssembly(name, access); else asm = domain.DefineDynamicAssembly(name, access, Path.GetDirectoryName(fileName)); if (fileName == null) mod = asm.DefineDynamicModule(name.Name, symbolInfo); else mod = asm.DefineDynamicModule(Path.GetFileName(fileName), Path.GetFileName(fileName), symbolInfo); }
static internal AssemblyBuilder CreateAssemblyBuilder(AppDomain appDomain, string name) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = name; assemblyName.Version = new Version(1, 0, 0, 0); if (DiagnosticsSwitches.KeepTempFiles.Enabled) return appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, TempFilesLocation); else return appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); }
private void GenerateMockAssembly(string name, string path, AppDomain currentDomain) { string filename = name + ".dll"; AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = name; // Generate the mock component: AssemblyBuilder builder = currentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save, path); ModuleBuilder module = builder.DefineDynamicModule(name, filename, true); GenerateMockType(module); builder.Save(filename); }
static public ModuleBuilder DefineDynamicModule(this AppDomain domain) { var _identity = Guid.NewGuid().ToString("N"); return(domain.DefineDynamicAssembly(new AssemblyName(string.Concat(Metadata <Assembly> .Type.Name, _identity)), AssemblyBuilderAccess.Run).DefineDynamicModule(string.Concat(Metadata <Module> .Type.Name, _identity), false)); }
// // Initializes the code generator variables for interactive use (repl) // static public void InitDynamic (CompilerContext ctx, string name) { current_domain = AppDomain.CurrentDomain; AssemblyName an = Assembly.GetAssemblyName (name, name); Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run); RootContext.ToplevelTypes = new ModuleCompiled (ctx, true); RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false); Assembly.Name = Assembly.Builder.GetName (); }
//Метод, переводящий семантическое дерево в сборку .NET public void ConvertFromTree(SemanticTree.IProgramNode p, string TargetFileName, string SourceFileName, CompilerOptions options, string[] ResourceFiles) { //SystemLibrary.SystemLibInitializer.RestoreStandardFunctions(); bool RunOnly = false; string fname = TargetFileName; comp_opt = options; ad = Thread.GetDomain(); //получаем домен приложения //ad = ad.DomainManager.CreateDomain("D1", null, null); an = new AssemblyName(); //создаем имя сборки an.Version = new Version("1.0.0.0"); string dir = Directory.GetCurrentDirectory(); string source_name = fname;//p.Location.document.file_name; int pos = source_name.LastIndexOf(Path.DirectorySeparatorChar); if (pos != -1) //если имя файла указано с путем, то выделяем { dir = source_name.Substring(0, pos + 1); an.CodeBase = String.Concat("file:///", source_name.Substring(0, pos)); source_name = source_name.Substring(pos + 1); } string name = source_name.Substring(0, source_name.LastIndexOf('.')); if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) an.Name = name;// + ".exe"; else an.Name = name; //+ ".dll"; if (name == "PABCRtl" || name == "PABCRtl32") { an.Flags = AssemblyNameFlags.PublicKey; an.VersionCompatibility = System.Configuration.Assemblies.AssemblyVersionCompatibility.SameProcess; an.HashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm.None; FileStream publicKeyStream = File.Open(Path.Combine(Path.GetDirectoryName(TargetFileName), name == "PABCRtl" ? "PublicKey.snk" : "PublicKey32.snk"), FileMode.Open); byte[] publicKey = new byte[publicKeyStream.Length]; publicKeyStream.Read(publicKey, 0, (int)publicKeyStream.Length); // Provide the assembly with a public key. an.SetPublicKey(publicKey); publicKeyStream.Close(); } if (RunOnly) ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run, dir);//определяем сборку else ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save, dir);//определяем сборку //int nn = ad.GetAssemblies().Length; if (options.NeedDefineVersionInfo) { ab.DefineVersionInfoResource(options.Product, options.ProductVersion, options.Company, options.Copyright, options.TradeMark); } if (options.MainResourceFileName != null) { try { ab.DefineUnmanagedResource(options.MainResourceFileName); } catch { throw new TreeConverter.SourceFileError(options.MainResourceFileName); } } else if (options.MainResourceData != null) { try { ab.DefineUnmanagedResource(options.MainResourceData); } catch { throw new TreeConverter.SourceFileError(""); } } save_debug_info = comp_opt.dbg_attrs == DebugAttributes.Debug || comp_opt.dbg_attrs == DebugAttributes.ForDebbuging; add_special_debug_variables = comp_opt.dbg_attrs == DebugAttributes.ForDebbuging; //bool emit_sym = true; if (save_debug_info) //если модуль отладочный, то устанавливаем атрибут, запрещающий inline методов ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x01, 0x01, 0x00, 0x00 }); //ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00 }); //else // ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 }); if (RunOnly) mb = ab.DefineDynamicModule(name, save_debug_info); else { if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) mb = ab.DefineDynamicModule(name + ".exe", an.Name + ".exe", save_debug_info); //определяем модуль (save_debug_info - флаг включать отладочную информацию) else mb = ab.DefineDynamicModule(name + ".dll", an.Name + ".dll", save_debug_info); } cur_unit = Path.GetFileNameWithoutExtension(SourceFileName); string entry_cur_unit = cur_unit; entry_type = mb.DefineType(cur_unit + ".Program", TypeAttributes.Public);//определяем синтетический статический класс основной программы cur_type = entry_type; //точка входа в приложение if (p.main_function != null) { ConvertFunctionHeader(p.main_function); entry_meth = helper.GetMethod(p.main_function).mi as MethodBuilder; /*entry_meth = entry_type.DefineMethod(p.main_function.name, MethodAttributes.Public | MethodAttributes.Static, typeof(void), GetParamTypes(p.main_function)); for (int i = 0; i < p.main_function.parameters.Length; i++) { if (p.main_function.parameters[i].parameter_type == parameter_type.var) entry_meth.DefineParameter(i + 1, ParameterAttributes.Retval, p.main_function.parameters[i].name); else entry_meth.DefineParameter(i + 1, ParameterAttributes.None, p.main_function.parameters[i].name); }*/ cur_meth = entry_meth; il = cur_meth.GetILGenerator(); if (options.target != TargetType.Dll && options.dbg_attrs == DebugAttributes.ForDebbuging) AddSpecialInitDebugCode(); } ILGenerator tmp_il = il; MethodBuilder tmp_meth = cur_meth; //при отладке компилятора здесь иногда ничего нет! ICommonNamespaceNode[] cnns = p.namespaces; //создаем отладочные документы if (save_debug_info) { first_doc = mb.DefineDocument(SourceFileName, SymDocumentType.Text, SymLanguageType.Pascal, SymLanguageVendor.Microsoft); for (int iii = 0; iii < cnns.Length; iii++) { if (cnns[iii].Location != null) doc = mb.DefineDocument(cnns[iii].Location.document.file_name, SymDocumentType.Text, SymLanguageType.Pascal, SymLanguageVendor.Microsoft); else doc = first_doc; sym_docs.Add(cnns[iii], doc);//сохраняем его в таблице документов } first_doc = sym_docs[cnns[0]]; if (p.main_function != null) { if (p.main_function.function_code is IStatementsListNode) EntryPointLocation = ((IStatementsListNode)p.main_function.function_code).LeftLogicalBracketLocation; else EntryPointLocation = p.main_function.function_code.Location; } else EntryPointLocation = null; } ICommonNamespaceNode entry_ns = null; //Переводим заголовки типов for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; bool is_main_namespace = cnns[iii].namespace_name == "" && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && cnns[iii].namespace_name == ""; ICommonNamespaceNode cnn = cnns[iii]; cur_type = entry_type; if (!is_main_namespace) cur_unit = cnn.namespace_name; else cur_unit = entry_cur_unit; if (iii == cnns.Length - 1 && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && iii == cnns.Length - 1) entry_ns = cnn; ConvertTypeHeaders(cnn.types); } //Переводим псевдоинстанции generic-типов foreach (ICommonTypeNode ictn in p.generic_type_instances) { ConvertTypeHeaderInSpecialOrder(ictn); } Dictionary<ICommonNamespaceNode, TypeBuilder> NamespacesTypes = new Dictionary<ICommonNamespaceNode, TypeBuilder>(); for (int iii = 0; iii < cnns.Length; iii++) { bool is_main_namespace = cnns[iii].namespace_name == "" && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && cnns[iii].namespace_name == ""; if (!is_main_namespace) { //определяем синтетический класс для модуля cur_type = mb.DefineType(cnns[iii].namespace_name + "." + cnns[iii].namespace_name, TypeAttributes.Public); types.Add(cur_type); NamespaceTypesList.Add(cur_type); NamespacesTypes.Add(cnns[iii], cur_type); if (cnns[iii].IsMain) { TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$GlobAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public); cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 }); attr_class.CreateType(); } else { TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$ClassUnitAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public); cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 }); attr_class.CreateType(); } } else { NamespacesTypes.Add(cnns[iii], entry_type); } } if (comp_opt.target == TargetType.Dll) { for (int iii = 0; iii < cnns.Length; iii++) { string tmp = cur_unit; if (cnns[iii].namespace_name != "") cur_unit = cnns[iii].namespace_name; else cur_unit = entry_cur_unit; foreach (ITemplateClass tc in cnns[iii].templates) { CreateTemplateClass(tc); } cur_unit = tmp; } for (int iii = 0; iii < cnns.Length; iii++) { string tmp = cur_unit; if (cnns[iii].namespace_name != "") cur_unit = cnns[iii].namespace_name; else cur_unit = entry_cur_unit; foreach (ITypeSynonym ts in cnns[iii].type_synonims) { CreateTypeSynonim(ts); } cur_unit = tmp; } } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; ConvertTypeMemberHeaders(cnns[iii].types); // cur_type = NamespacesTypes[cnns[iii]]; // cur_unit_type = NamespacesTypes[cnns[iii]]; // ConvertFunctionHeaders(cnns[iii].functions); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; ConvertFunctionHeaders(cnns[iii].functions); } if (p.InitializationCode != null) { tmp_il = il; if (entry_meth != null) { il = entry_meth.GetILGenerator(); ConvertStatement(p.InitializationCode); } else { //il = unit_cci.GetILGenerator(); //ConvertStatement(p.InitializationCode); } il = tmp_il; } //Переводим псевдоинстанции generic-типов foreach (IGenericTypeInstance ictn in p.generic_type_instances) { ConvertGenericInstanceTypeMembers(ictn); } //Переводим псевдоинстанции функций foreach (IGenericFunctionInstance igfi in p.generic_function_instances) { ConvertGenericFunctionInstance(igfi); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; //генерим инциализацию для полей foreach (SemanticTree.ICommonTypeNode ctn in cnns[iii].types) GenerateInitCodeForFields(ctn); } ConstructorBuilder unit_cci = null; //Переводим заголовки всего остального (процедур, переменных) for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; bool is_main_namespace = iii == cnns.Length - 1 && comp_opt.target != TargetType.Dll; ICommonNamespaceNode cnn = cnns[iii]; string tmp_unit_name = cur_unit; if (!is_main_namespace) cur_unit = cnn.namespace_name; else cur_unit = entry_cur_unit; cur_type = NamespacesTypes[cnn]; //ConvertFunctionHeaders(cnn.functions); if (!is_main_namespace) { //определяем статический конструктор класса для модуля ConstructorBuilder cb = cur_type.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes); il = cb.GetILGenerator(); if (cnn.IsMain) unit_cci = cb; ModulesInitILGenerators.Add(cur_type, il); //переводим глобальные переменные модуля ConvertGlobalVariables(cnn.variables); //перводим константы ConvertNamespaceConstants(cnn.constants); ConvertNamespaceEvents(cnn.events); //il.Emit(OpCodes.Ret); } else { //Не нарвится мне порядок вызова. надо с этим разобраться init_variables_mb = helper.GetMethodBuilder(cnn.functions[cnn.functions.Length-1]);// cur_type.DefineMethod("$InitVariables", MethodAttributes.Public | MethodAttributes.Static); il = entry_meth.GetILGenerator(); ModulesInitILGenerators.Add(cur_type, il); il = init_variables_mb.GetILGenerator(); ConvertGlobalVariables(cnn.variables); il = entry_meth.GetILGenerator(); //перводим константы ConvertNamespaceConstants(cnn.constants); ConvertNamespaceEvents(cnn.events); //il.Emit(OpCodes.Ret); } cur_unit = tmp_unit_name; } if (p.InitializationCode != null) { tmp_il = il; if (entry_meth == null) { il = unit_cci.GetILGenerator(); ConvertStatement(p.InitializationCode); } il = tmp_il; } cur_type = entry_type; //is_in_unit = false; //переводим реализации for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; bool is_main_namespace = iii == 0 && comp_opt.target != TargetType.Dll; ICommonNamespaceNode cnn = cnns[iii]; string tmp_unit_name = cur_unit; if (!is_main_namespace) cur_unit = cnn.namespace_name; //if (iii > 0) is_in_unit = true; cur_unit_type = NamespacesTypes[cnns[iii]]; cur_type = cur_unit_type; ConvertTypeImplementations(cnn.types); ConvertFunctionsBodies(cnn.functions); cur_unit = tmp_unit_name; } if (comp_opt.target != TargetType.Dll && p.main_function != null) { cur_unit_type = NamespacesTypes[cnns[0]]; cur_type = cur_unit_type; ConvertBody(p.main_function.function_code); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; //вставляем ret в int_meth foreach (SemanticTree.ICommonTypeNode ctn in cnns[iii].types) GenerateRetForInitMeth(ctn); ModulesInitILGenerators[cur_type].Emit(OpCodes.Ret); } for (int iii = 0; iii < cnns.Length; iii++) { MakeAttribute(cnns[iii]); } doc = first_doc; cur_type = entry_type; // il = entry_type.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes).GetILGenerator(); // if (p.InitializationCode != null) // ConvertStatement(p.InitializationCode); /*cur_meth = entry_meth; il = entry_meth.GetILGenerator(); //переводим тело основной программы //Тут только вызовы init, final if (p.main_function != null) { ConvertBody(p.main_function.function_code); il.Emit(OpCodes.Ret); }*/ CloseTypes();//закрываем типы entry_type.CreateType(); switch (comp_opt.target) { case TargetType.Exe: ab.SetEntryPoint(entry_meth, PEFileKinds.ConsoleApplication); break; case TargetType.WinExe: if (!comp_opt.ForRunningWithEnvironment) ab.SetEntryPoint(entry_meth, PEFileKinds.WindowApplication); else ab.SetEntryPoint(entry_meth, PEFileKinds.ConsoleApplication); break; } /**/ try { //ne osobo vazhnaja vesh, sohranjaet v exe-shnik spisok ispolzuemyh prostranstv imen, dlja strahovki obernuli try catch if (comp_opt.dbg_attrs == DebugAttributes.ForDebbuging) { string[] namespaces = p.UsedNamespaces; TypeBuilder attr_class = mb.DefineType("$UsedNsAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); FieldBuilder fld_ns = attr_class.DefineField("ns", TypeFactory.StringType, FieldAttributes.Public); FieldBuilder fld_count = attr_class.DefineField("count", TypeFactory.Int32Type, FieldAttributes.Public); ConstructorBuilder attr_ci = attr_class.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[2] { TypeFactory.Int32Type, TypeFactory.StringType }); ILGenerator attr_il = attr_ci.GetILGenerator(); attr_il.Emit(OpCodes.Ldarg_0); attr_il.Emit(OpCodes.Ldarg_1); attr_il.Emit(OpCodes.Stfld, fld_count); attr_il.Emit(OpCodes.Ldarg_0); attr_il.Emit(OpCodes.Ldarg_2); attr_il.Emit(OpCodes.Stfld, fld_ns); attr_il.Emit(OpCodes.Ret); int len = 2 + 2 + 4 + 1; foreach (string ns in namespaces) { len += ns.Length + 1; } byte[] bytes = new byte[len]; bytes[0] = 1; bytes[1] = 0; using (BinaryWriter bw = new BinaryWriter(new MemoryStream())) { bw.Write(namespaces.Length); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (string ns in namespaces) { sb.Append(Convert.ToChar(ns.Length)); sb.Append(ns); //bw.Write(ns); } if (sb.Length > 127) { len += 1; bytes = new byte[len]; bytes[0] = 1; bytes[1] = 0; } bw.Write(sb.ToString()); bw.Seek(0, SeekOrigin.Begin); bw.BaseStream.Read(bytes, 2, len - 4); if (sb.Length > 127) { bytes[7] = (byte)(sb.Length & 0xFF); bytes[6] = (byte)(0x80 | ((sb.Length & 0xFF00) >> 8)); } } entry_type.SetCustomAttribute(attr_ci, bytes); attr_class.CreateType(); } } catch (Exception e) { } if (an.Name == "PABCRtl" || an.Name == "PABCRtl32") { CustomAttributeBuilder cab = new CustomAttributeBuilder(typeof(AssemblyKeyFileAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { an.Name == "PABCRtl" ? "PublicKey.snk" : "PublicKey32.snk" }); ab.SetCustomAttribute(cab); cab = new CustomAttributeBuilder(typeof(AssemblyDelaySignAttribute).GetConstructor(new Type[] { typeof(bool) }), new object[] { true }); ab.SetCustomAttribute(cab); cab = new CustomAttributeBuilder(typeof(TargetFrameworkAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { ".NETFramework,Version=v4.0" }); ab.SetCustomAttribute(cab); } ab.SetCustomAttribute(new CustomAttributeBuilder(typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }), new object[] { SecurityRuleSet.Level2 }, new PropertyInfo[] { typeof(SecurityRulesAttribute).GetProperty("SkipVerificationInFullTrust") }, new object[] { true })); /*ab.SetCustomAttribute(new CustomAttributeBuilder(typeof(System.Security.Permissions.SecurityPermissionAttribute).GetConstructor(new Type[] { typeof(System.Security.Permissions.SecurityAction) }), new object[] { System.Security.Permissions.SecurityAction.RequestMinimum }, new PropertyInfo[] { typeof(System.Security.Permissions.SecurityPermissionAttribute).GetProperty("UnmanagedCode") }, new object[] { true }));*/ if (entry_meth != null && comp_opt.target == TargetType.WinExe) { entry_meth.SetCustomAttribute(typeof(STAThreadAttribute).GetConstructor(Type.EmptyTypes), new byte[] { 0x01, 0x00, 0x00, 0x00 }); } List<FileStream> ResStreams = new List<FileStream>(); if (ResourceFiles != null) foreach (string resname in ResourceFiles) { FileStream stream = File.OpenRead(resname); ResStreams.Add(stream); mb.DefineManifestResource(Path.GetFileName(resname), stream, ResourceAttributes.Public); //System.Resources.ResourceManager rm; //System.Resources.ResourceSet rs;rs. } ab.SetCustomAttribute(typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute).GetConstructor(new Type[1] { TypeFactory.Int32Type }), new byte[] { 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }); //ab.SetCustomAttribute(typeof(System.Runtime.CompilerServices.RuntimeCompatibilityAttribute, if (RunOnly) { object main_class = ab.CreateInstance(cur_unit + ".Program"); MethodInfo methodInfo = main_class.GetType().GetMethod("Main"); //AppDomain.CreateDomain( methodInfo.Invoke(main_class, null); //ad.ExecuteAssemblyByName(assembly_to_run.GetName(), new System.Security.Policy.Evidence(), null); } else { int tries = 0; bool not_done = true; do { try { if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) { if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x86) ab.Save(an.Name + ".exe", PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); //else if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x64) // ab.Save(an.Name + ".exe", PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); else ab.Save(an.Name + ".exe"); //сохраняем сборку } else { if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x86) ab.Save(an.Name + ".dll", PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); //else if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x64) // ab.Save(an.Name + ".dll", PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); else ab.Save(an.Name + ".dll"); } not_done = false; } catch (System.Runtime.InteropServices.COMException e) { throw new TreeConverter.SaveAssemblyError(e.Message); } catch (System.IO.IOException e) { if (tries < num_try_save) tries++; else throw new TreeConverter.SaveAssemblyError(e.Message); } } while (not_done); } foreach (FileStream fs in ResStreams) fs.Close(); //ad.ExecuteAssemblyByName(an, new System.Security.Policy.Evidence()); //это уже не нужно //Console.WriteLine(Environment.TickCount-ticks); }
// // Initializes the code generator variables // static public bool Init (string name, string output, bool want_debugging_support, CompilerContext ctx) { FileName = output; AssemblyName an = Assembly.GetAssemblyName (name, output); if (an == null) return false; if (an.KeyPair != null) { // If we are going to strong name our assembly make // sure all its refs are strong named foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) { AssemblyName ref_name = a.GetName (); byte [] b = ref_name.GetPublicKeyToken (); if (b == null || b.Length == 0) { ctx.Report.Error (1577, "Assembly generation failed " + "-- Referenced assembly '" + ref_name.Name + "' does not have a strong name."); //Environment.Exit (1); } } } current_domain = AppDomain.CurrentDomain; try { Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.RunAndSave, Dirname (name)); } catch (ArgumentException) { // specified key may not be exportable outside it's container if (RootContext.StrongNameKeyContainer != null) { ctx.Report.Error (1548, "Could not access the key inside the container `" + RootContext.StrongNameKeyContainer + "'."); Environment.Exit (1); } throw; } catch (CryptographicException) { if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) { ctx.Report.Error (1548, "Could not use the specified key to strongname the assembly."); Environment.Exit (1); } return false; } // Get the complete AssemblyName from the builder // (We need to get the public key and token) Assembly.Name = Assembly.Builder.GetName (); // // Pass a path-less name to DefineDynamicModule. Wonder how // this copes with output in different directories then. // FIXME: figure out how this copes with --output /tmp/blah // // If the third argument is true, the ModuleBuilder will dynamically // load the default symbol writer. // try { RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule ( Basename (name), Basename (output), want_debugging_support); #if !MS_COMPATIBLE // TODO: We should use SymbolWriter from DefineDynamicModule if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) { ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'", "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)"); return false; } #endif } catch (ExecutionEngineException e) { ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'", e.Message); return false; } return true; }
private void BuildAssembly(AppDomain appDomain, string dir, string filename) { // Prepare the assembly-level permissions. PermissionSet requiredPermissions = new PermissionSet(null); PermissionSet optionalPermissions = new PermissionSet(null); PermissionSet refusedPermissions = new PermissionSet(null); foreach (SecurityDeclaration securityDeclaration in assemblyDefinition.SecurityDeclarations) { switch (securityDeclaration.Action) { case Mono.Cecil.SecurityAction.RequestMinimum: requiredPermissions = requiredPermissions.Union(securityDeclaration.PermissionSet); break; case Mono.Cecil.SecurityAction.RequestOptional: optionalPermissions = optionalPermissions.Union(securityDeclaration.PermissionSet); break; case Mono.Cecil.SecurityAction.RequestRefuse: refusedPermissions = refusedPermissions.Union(securityDeclaration.PermissionSet); break; } } // Build the dynamic assembly. AssemblyBuilder assemblyBuilder = appDomain.DefineDynamicAssembly( new AssemblyName(assemblyDefinition.Name.FullName), AssemblyBuilderAccess.RunAndSave, dir, requiredPermissions, optionalPermissions, refusedPermissions); dynamicAssembly = new DynamicAssembly(assemblyBuilder, filename); // TODO: Set entry point and assembly kind. foreach (ModuleDefinition moduleDefinition in assemblyDefinition.Modules) BuildModule(moduleDefinition); metadataPass.Add(delegate { InitializeCustomAttributes(assemblyBuilder.SetCustomAttribute, assemblyDefinition.CustomAttributes); }); }
// // Initializes the code generator // public bool Create (AppDomain domain, AssemblyBuilderAccess access) { ResolveAssemblySecurityAttributes (); var an = new AssemblyName (name); if (public_key != null && RootContext.Target != Target.Module) { if (delay_sign) { an.SetPublicKey (public_key); } else { if (public_key.Length == 16) { Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies"); } else if (private_key == null) { Error_AssemblySigning ("The specified key file does not have a private key"); } else { an.KeyPair = private_key; } } } try { Builder = file_name == null ? domain.DefineDynamicAssembly (an, access) : domain.DefineDynamicAssembly (an, access, Dirname (file_name)); } catch (ArgumentException) { // specified key may not be exportable outside it's container if (RootContext.StrongNameKeyContainer != null) { Report.Error (1548, "Could not access the key inside the container `" + RootContext.StrongNameKeyContainer + "'."); } throw; } builder_extra = new AssemblyBuilderExtension (Builder, Compiler); return true; }
internal static void Init(string file_name) { app_domain = Thread.GetDomain (); assembly_name = new AssemblyName (); assembly_name.Name = Path.GetFileNameWithoutExtension (file_name); mod_name = MODULE; assembly_builder = app_domain.DefineDynamicAssembly ( assembly_name, AssemblyBuilderAccess.RunAndSave, Dirname (file_name)); ConstructorInfo ctr_info = typeof (Microsoft.JScript.ReferenceAttribute).GetConstructor (new Type [] { typeof (string) }); assembly_builder.SetCustomAttribute (new CustomAttributeBuilder (ctr_info, new object [] {CORLIB})); module_builder = assembly_builder.DefineDynamicModule ( mod_name, Basename (assembly_name.Name + ".exe"), false); }
public static Type GetProxy(AppDomain domain, params Type[] interfaces) { lock (typeof(DynamicProxy)) { ProxyKey proxyKey = new ProxyKey(domain, interfaces); Type proxy = null; if (proxyCache.ContainsKey(proxyKey)) { proxy = (Type)proxyCache[proxyKey]; } if (proxy == null) { interfaces = SumUpInterfaces(interfaces); String dynamicAssemblyName; String dynamicModuleName; String dynamicProxyTypeName; String strNumber = countDymamicAssembly.ToString(NumberFormatInfo.InvariantInfo); dynamicAssemblyName = "$DynamicAssembly" + strNumber; dynamicModuleName = "$DynamicModule" + strNumber; dynamicProxyTypeName = "$Proxy" + strNumber; countDymamicAssembly++; AssemblyBuilder assemblyBuilder; AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = dynamicAssemblyName; #if !SILVERLIGHT assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, FlagCreateFile ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run); #else assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); #endif ModuleBuilder moduleBuilder; #if !SILVERLIGHT if (FlagCreateFile) { moduleBuilder = assemblyBuilder.DefineDynamicModule(dynamicModuleName, dynamicModuleName + ".dll"); } else { moduleBuilder = assemblyBuilder.DefineDynamicModule(dynamicModuleName); } #else moduleBuilder = assemblyBuilder.DefineDynamicModule(dynamicModuleName); #endif TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicProxyTypeName, TypeAttributes.Public, typeof(DynamicProxy), interfaces); //build .ctor ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.Standard, Types_InvocationHandler); ILGenerator gen = ctorBuilder.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Call, DynamicProxy_Ctor); gen.Emit(OpCodes.Ret); MakeMethods(typeBuilder, typeof(Object), true); foreach (Type interfac in interfaces) { MakeMethods(typeBuilder, interfac, false); } proxy = typeBuilder.CreateType(); proxyCache.Add(proxyKey, proxy); #if !SILVERLIGHT if (FlagCreateFile) { assemblyBuilder.Save(dynamicAssemblyName + ".dll"); } #endif } return proxy; } }
//Метод, переводящий семантическое дерево в сборку .NET public void ConvertFromTree(SemanticTree.IProgramNode p, string TargetFileName, string SourceFileName, CompilerOptions options, string[] ResourceFiles) { //SystemLibrary.SystemLibInitializer.RestoreStandardFunctions(); bool RunOnly = false; string fname = TargetFileName; comp_opt = options; ad = Thread.GetDomain(); //получаем домен приложения an = new AssemblyName(); //создаем имя сборки an.Version = new Version("1.0.0.0"); string dir = Directory.GetCurrentDirectory(); string source_name = fname;//p.Location.document.file_name; int pos = source_name.LastIndexOf(Path.DirectorySeparatorChar); if (pos != -1) //если имя файла указано с путем, то выделяем { dir = source_name.Substring(0, pos + 1); an.CodeBase = String.Concat("file:///", source_name.Substring(0, pos)); source_name = source_name.Substring(pos + 1); } string name = source_name.Substring(0, source_name.LastIndexOf('.')); if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) an.Name = name;// + ".exe"; else an.Name = name; //+ ".dll"; if (name == "PABCRtl" || name == "PABCRtl32") { an.Flags = AssemblyNameFlags.PublicKey; an.VersionCompatibility = System.Configuration.Assemblies.AssemblyVersionCompatibility.SameProcess; an.HashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm.None; FileStream publicKeyStream = File.Open(Path.Combine(Path.GetDirectoryName(TargetFileName), name == "PABCRtl" ? "PublicKey.snk" : "PublicKey32.snk"), FileMode.Open); byte[] publicKey = new byte[publicKeyStream.Length]; publicKeyStream.Read(publicKey, 0, (int)publicKeyStream.Length); // Provide the assembly with a public key. an.SetPublicKey(publicKey); publicKeyStream.Close(); } if (RunOnly) ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run, dir);//определяем сборку else ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save, dir);//определяем сборку //int nn = ad.GetAssemblies().Length; if (options.NeedDefineVersionInfo) { ab.DefineVersionInfoResource(options.Product, options.ProductVersion, options.Company, options.Copyright, options.TradeMark); } if (options.MainResourceFileName != null) { try { ab.DefineUnmanagedResource(options.MainResourceFileName); } catch { throw new TreeConverter.SourceFileError(options.MainResourceFileName); } } else if (options.MainResourceData != null) { try { ab.DefineUnmanagedResource(options.MainResourceData); } catch { throw new TreeConverter.SourceFileError(""); } } save_debug_info = comp_opt.dbg_attrs == DebugAttributes.Debug || comp_opt.dbg_attrs == DebugAttributes.ForDebbuging; add_special_debug_variables = comp_opt.dbg_attrs == DebugAttributes.ForDebbuging; //bool emit_sym = true; if (save_debug_info) //если модуль отладочный, то устанавливаем атрибут, запрещающий inline методов ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x01, 0x01, 0x00, 0x00 }); if (RunOnly) mb = ab.DefineDynamicModule(name, save_debug_info); else { if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) mb = ab.DefineDynamicModule(name + ".exe", an.Name + ".exe", save_debug_info); //определяем модуль (save_debug_info - флаг включать отладочную информацию) else mb = ab.DefineDynamicModule(name + ".dll", an.Name + ".dll", save_debug_info); } cur_unit = Path.GetFileNameWithoutExtension(SourceFileName); string entry_cur_unit = cur_unit; entry_type = mb.DefineType(cur_unit + ".Program", TypeAttributes.Public);//определяем синтетический статический класс основной программы cur_type = entry_type; //точка входа в приложение if (p.main_function != null) { ConvertFunctionHeader(p.main_function); entry_meth = helper.GetMethod(p.main_function).mi as MethodBuilder; cur_meth = entry_meth; il = cur_meth.GetILGenerator(); if (options.target != TargetType.Dll && options.dbg_attrs == DebugAttributes.ForDebbuging) AddSpecialInitDebugCode(); } ILGenerator tmp_il = il; MethodBuilder tmp_meth = cur_meth; //при отладке компилятора здесь иногда ничего нет! ICommonNamespaceNode[] cnns = p.namespaces; //создаем отладочные документы if (save_debug_info) { first_doc = mb.DefineDocument(SourceFileName, SymDocumentType.Text, SymLanguageType.Pascal, SymLanguageVendor.Microsoft); sym_docs.Add(SourceFileName, first_doc); for (int iii = 0; iii < cnns.Length; iii++) { string cnns_document_file_name = null; if (cnns[iii].Location != null) { cnns_document_file_name = cnns[iii].Location.document.file_name; doc = mb.DefineDocument(cnns_document_file_name, SymDocumentType.Text, SymLanguageType.Pascal, SymLanguageVendor.Microsoft); } else doc = first_doc; if (!sym_docs.ContainsKey(cnns_document_file_name)) sym_docs.Add(cnns_document_file_name, doc);//сохраняем его в таблице документов } first_doc = sym_docs[cnns[0].Location == null ? SourceFileName : cnns[0].Location.document.file_name]; if (p.main_function != null) { if (p.main_function.function_code is IStatementsListNode) EntryPointLocation = ((IStatementsListNode)p.main_function.function_code).LeftLogicalBracketLocation; else EntryPointLocation = p.main_function.function_code.Location; } else EntryPointLocation = null; } ICommonNamespaceNode entry_ns = null; //Переводим заголовки типов for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii].Location == null ? SourceFileName : cnns[iii].Location.document.file_name]; bool is_main_namespace = cnns[iii].namespace_name == "" && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && cnns[iii].namespace_name == ""; ICommonNamespaceNode cnn = cnns[iii]; cur_type = entry_type; if (!is_main_namespace) cur_unit = cnn.namespace_name; else cur_unit = entry_cur_unit; if (iii == cnns.Length - 1 && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && iii == cnns.Length - 1) entry_ns = cnn; ConvertTypeHeaders(cnn.types); } //Переводим псевдоинстанции generic-типов foreach (ICommonTypeNode ictn in p.generic_type_instances) { ConvertTypeHeaderInSpecialOrder(ictn); } Dictionary<ICommonNamespaceNode, TypeBuilder> NamespacesTypes = new Dictionary<ICommonNamespaceNode, TypeBuilder>(); for (int iii = 0; iii < cnns.Length; iii++) { bool is_main_namespace = cnns[iii].namespace_name == "" && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && cnns[iii].namespace_name == ""; if (!is_main_namespace) { //определяем синтетический класс для модуля cur_type = mb.DefineType(cnns[iii].namespace_name + "." + cnns[iii].namespace_name, TypeAttributes.Public); types.Add(cur_type); NamespaceTypesList.Add(cur_type); NamespacesTypes.Add(cnns[iii], cur_type); if (cnns[iii].IsMain) { TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$GlobAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public); cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 }); attr_class.CreateType(); } else { TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$ClassUnitAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public); cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 }); attr_class.CreateType(); } } else { NamespacesTypes.Add(cnns[iii], entry_type); } } if (comp_opt.target == TargetType.Dll) { for (int iii = 0; iii < cnns.Length; iii++) { string tmp = cur_unit; if (cnns[iii].namespace_name != "") cur_unit = cnns[iii].namespace_name; else cur_unit = entry_cur_unit; foreach (ITemplateClass tc in cnns[iii].templates) { CreateTemplateClass(tc); } cur_unit = tmp; } for (int iii = 0; iii < cnns.Length; iii++) { string tmp = cur_unit; if (cnns[iii].namespace_name != "") cur_unit = cnns[iii].namespace_name; else cur_unit = entry_cur_unit; foreach (ITypeSynonym ts in cnns[iii].type_synonims) { CreateTypeSynonim(ts); } cur_unit = tmp; } } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii].Location == null ? SourceFileName : cnns[iii].Location.document.file_name]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; ConvertTypeMemberHeaders(cnns[iii].types); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii].Location == null ? SourceFileName : cnns[iii].Location.document.file_name]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; ConvertFunctionHeaders(cnns[iii].functions); } if (p.InitializationCode != null) { tmp_il = il; if (entry_meth != null) { il = entry_meth.GetILGenerator(); ConvertStatement(p.InitializationCode); } il = tmp_il; } //Переводим псевдоинстанции generic-типов foreach (IGenericTypeInstance ictn in p.generic_type_instances) { ConvertGenericInstanceTypeMembers(ictn); } //Переводим псевдоинстанции функций foreach (IGenericFunctionInstance igfi in p.generic_function_instances) { ConvertGenericFunctionInstance(igfi); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii].Location == null ? SourceFileName : cnns[iii].Location.document.file_name]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; //генерим инциализацию для полей foreach (SemanticTree.ICommonTypeNode ctn in cnns[iii].types) GenerateInitCodeForFields(ctn); } ConstructorBuilder unit_cci = null; //Переводим заголовки всего остального (процедур, переменных) for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii].Location == null ? SourceFileName : cnns[iii].Location.document.file_name]; bool is_main_namespace = iii == cnns.Length - 1 && comp_opt.target != TargetType.Dll; ICommonNamespaceNode cnn = cnns[iii]; string tmp_unit_name = cur_unit; if (!is_main_namespace) cur_unit = cnn.namespace_name; else cur_unit = entry_cur_unit; cur_type = NamespacesTypes[cnn]; //ConvertFunctionHeaders(cnn.functions); if (!is_main_namespace) { //определяем статический конструктор класса для модуля ConstructorBuilder cb = cur_type.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes); il = cb.GetILGenerator(); if (cnn.IsMain) unit_cci = cb; ModulesInitILGenerators.Add(cur_type, il); //переводим глобальные переменные модуля ConvertGlobalVariables(cnn.variables); //перводим константы ConvertNamespaceConstants(cnn.constants); ConvertNamespaceEvents(cnn.events); //il.Emit(OpCodes.Ret); } else { //Не нарвится мне порядок вызова. надо с этим разобраться init_variables_mb = helper.GetMethodBuilder(cnn.functions[cnn.functions.Length-1]);// cur_type.DefineMethod("$InitVariables", MethodAttributes.Public | MethodAttributes.Static); il = entry_meth.GetILGenerator(); ModulesInitILGenerators.Add(cur_type, il); il = init_variables_mb.GetILGenerator(); ConvertGlobalVariables(cnn.variables); il = entry_meth.GetILGenerator(); //перводим константы ConvertNamespaceConstants(cnn.constants); ConvertNamespaceEvents(cnn.events); //il.Emit(OpCodes.Ret); } cur_unit = tmp_unit_name; } if (p.InitializationCode != null) { tmp_il = il; if (entry_meth == null) { il = unit_cci.GetILGenerator(); ConvertStatement(p.InitializationCode); } il = tmp_il; } cur_type = entry_type; //is_in_unit = false; //переводим реализации for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii].Location == null ? SourceFileName : cnns[iii].Location.document.file_name]; bool is_main_namespace = iii == 0 && comp_opt.target != TargetType.Dll; ICommonNamespaceNode cnn = cnns[iii]; string tmp_unit_name = cur_unit; if (!is_main_namespace) cur_unit = cnn.namespace_name; //if (iii > 0) is_in_unit = true; cur_unit_type = NamespacesTypes[cnns[iii]]; cur_type = cur_unit_type; ConvertTypeImplementations(cnn.types); ConvertFunctionsBodies(cnn.functions); cur_unit = tmp_unit_name; } if (comp_opt.target != TargetType.Dll && p.main_function != null) { cur_unit_type = NamespacesTypes[cnns[0]]; cur_type = cur_unit_type; ConvertBody(p.main_function.function_code); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii].Location == null ? SourceFileName : cnns[iii].Location.document.file_name]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; //вставляем ret в int_meth foreach (SemanticTree.ICommonTypeNode ctn in cnns[iii].types) GenerateRetForInitMeth(ctn); ModulesInitILGenerators[cur_type].Emit(OpCodes.Ret); } for (int iii = 0; iii < cnns.Length; iii++) { MakeAttribute(cnns[iii]); } doc = first_doc; cur_type = entry_type; CloseTypes();//закрываем типы entry_type.CreateType(); switch (comp_opt.target) { case TargetType.Exe: ab.SetEntryPoint(entry_meth, PEFileKinds.ConsoleApplication); break; case TargetType.WinExe: if (!comp_opt.ForRunningWithEnvironment) ab.SetEntryPoint(entry_meth, PEFileKinds.WindowApplication); else ab.SetEntryPoint(entry_meth, PEFileKinds.ConsoleApplication); break; } /**/ try { //ne osobo vazhnaja vesh, sohranjaet v exe-shnik spisok ispolzuemyh prostranstv imen, dlja strahovki obernuli try catch if (comp_opt.dbg_attrs == DebugAttributes.ForDebbuging) { string[] namespaces = p.UsedNamespaces; TypeBuilder attr_class = mb.DefineType("$UsedNsAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); FieldBuilder fld_ns = attr_class.DefineField("ns", TypeFactory.StringType, FieldAttributes.Public); FieldBuilder fld_count = attr_class.DefineField("count", TypeFactory.Int32Type, FieldAttributes.Public); ConstructorBuilder attr_ci = attr_class.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[2] { TypeFactory.Int32Type, TypeFactory.StringType }); ILGenerator attr_il = attr_ci.GetILGenerator(); attr_il.Emit(OpCodes.Ldarg_0); attr_il.Emit(OpCodes.Ldarg_1); attr_il.Emit(OpCodes.Stfld, fld_count); attr_il.Emit(OpCodes.Ldarg_0); attr_il.Emit(OpCodes.Ldarg_2); attr_il.Emit(OpCodes.Stfld, fld_ns); attr_il.Emit(OpCodes.Ret); int len = 2 + 2 + 4 + 1; foreach (string ns in namespaces) { len += ns.Length + 1; } byte[] bytes = new byte[len]; bytes[0] = 1; bytes[1] = 0; using (BinaryWriter bw = new BinaryWriter(new MemoryStream())) { bw.Write(namespaces.Length); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (string ns in namespaces) { sb.Append(Convert.ToChar(ns.Length)); sb.Append(ns); //bw.Write(ns); } if (sb.Length > 127) { len += 1; bytes = new byte[len]; bytes[0] = 1; bytes[1] = 0; } bw.Write(sb.ToString()); bw.Seek(0, SeekOrigin.Begin); bw.BaseStream.Read(bytes, 2, len - 4); if (sb.Length > 127) { bytes[7] = (byte)(sb.Length & 0xFF); bytes[6] = (byte)(0x80 | ((sb.Length & 0xFF00) >> 8)); } } entry_type.SetCustomAttribute(attr_ci, bytes); attr_class.CreateType(); } } catch (Exception e) { } if (an.Name == "PABCRtl" || an.Name == "PABCRtl32") { CustomAttributeBuilder cab = new CustomAttributeBuilder(typeof(AssemblyKeyFileAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { an.Name == "PABCRtl" ? "PublicKey.snk" : "PublicKey32.snk" }); ab.SetCustomAttribute(cab); cab = new CustomAttributeBuilder(typeof(AssemblyDelaySignAttribute).GetConstructor(new Type[] { typeof(bool) }), new object[] { true }); ab.SetCustomAttribute(cab); cab = new CustomAttributeBuilder(typeof(TargetFrameworkAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { ".NETFramework,Version=v4.0" }); ab.SetCustomAttribute(cab); } ab.SetCustomAttribute(new CustomAttributeBuilder(typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }), new object[] { SecurityRuleSet.Level2 }, new PropertyInfo[] { typeof(SecurityRulesAttribute).GetProperty("SkipVerificationInFullTrust") }, new object[] { true })); if (entry_meth != null && comp_opt.target == TargetType.WinExe) { entry_meth.SetCustomAttribute(typeof(STAThreadAttribute).GetConstructor(Type.EmptyTypes), new byte[] { 0x01, 0x00, 0x00, 0x00 }); } List<FileStream> ResStreams = new List<FileStream>(); if (ResourceFiles != null) foreach (string resname in ResourceFiles) { FileStream stream = File.OpenRead(resname); ResStreams.Add(stream); mb.DefineManifestResource(Path.GetFileName(resname), stream, ResourceAttributes.Public); } ab.SetCustomAttribute(typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute).GetConstructor(new Type[1] { TypeFactory.Int32Type }), new byte[] { 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }); if (RunOnly) { object main_class = ab.CreateInstance(cur_unit + ".Program"); MethodInfo methodInfo = main_class.GetType().GetMethod("Main"); methodInfo.Invoke(main_class, null); } else { int tries = 0; bool not_done = true; do { try { if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) { if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x86) ab.Save(an.Name + ".exe", PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); //else if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x64) // ab.Save(an.Name + ".exe", PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); else ab.Save(an.Name + ".exe"); //сохраняем сборку } else { if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x86) ab.Save(an.Name + ".dll", PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); //else if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x64) // ab.Save(an.Name + ".dll", PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); else ab.Save(an.Name + ".dll"); } not_done = false; } catch (System.Runtime.InteropServices.COMException e) { throw new TreeConverter.SaveAssemblyError(e.Message); } catch (System.IO.IOException e) { if (tries < num_try_save) tries++; else throw new TreeConverter.SaveAssemblyError(e.Message); } } while (not_done); } foreach (FileStream fs in ResStreams) fs.Close(); } private void AddSpecialInitDebugCode() { //il.Emit(OpCodes.Call,typeof(Console).GetMethod("ReadLine")); //il.Emit(OpCodes.Pop); } private void ConvertNamespaceConstants(INamespaceConstantDefinitionNode[] Constants) { foreach (INamespaceConstantDefinitionNode Constant in Constants) ConvertConstantDefinitionNode(Constant, Constant.name, Constant.type, Constant.constant_value); } private void ConvertNamespaceEvents(ICommonNamespaceEventNode[] Events) { foreach (ICommonNamespaceEventNode Event in Events) Event.visit(this); } private void ConvertCommonFunctionConstantDefinitions(ICommonFunctionConstantDefinitionNode[] Constants) { foreach (ICommonFunctionConstantDefinitionNode Constant in Constants) //ConvertFunctionConstantDefinitionNode(Constant); ConvertConstantDefinitionNode(Constant, Constant.name, Constant.type, Constant.constant_value); } private void ConvertConstantDefinitionNode(IConstantDefinitionNode cnst, string name, ITypeNode type, IConstantNode constant_value) { if (constant_value is IArrayConstantNode) ConvertArrayConstantDef(cnst, name, type, constant_value); else if (constant_value is IRecordConstantNode || constant_value is ICompiledStaticMethodCallNodeAsConstant) ConvertConstantDefWithInitCall(cnst, name, type, constant_value); else if (constant_value is ICommonNamespaceFunctionCallNodeAsConstant || constant_value is IBasicFunctionCallNodeAsConstant || constant_value is ICommonConstructorCallAsConstant || constant_value is ICompiledStaticFieldReferenceNodeAsConstant) ConvertSetConstantDef(cnst, name, type, constant_value); else ConvertSimpleConstant(cnst, name, type, constant_value); } private void ConvertSetConstantDef(IConstantDefinitionNode cnst, string name, ITypeNode type, IConstantNode constant_value) { TypeInfo ti = helper.GetTypeReference(type); FieldAttributes attrs = FieldAttributes.Public | FieldAttributes.Static; if (comp_opt.target == TargetType.Dll) attrs |= FieldAttributes.InitOnly; FieldBuilder fb = cur_type.DefineField(name, ti.tp, attrs); //il.Emit(OpCodes.Newobj, ti.tp.GetConstructor(Type.EmptyTypes)); //il.Emit(OpCodes.Stsfld, fb); if (cnst != null) helper.AddConstant(cnst, fb); bool tmp = save_debug_info; save_debug_info = false; constant_value.visit(this); save_debug_info = tmp; il.Emit(OpCodes.Stsfld, fb); if (!ConvertedConstants.ContainsKey(constant_value)) ConvertedConstants.Add(constant_value, fb); } private void ConvertSimpleConstant(IConstantDefinitionNode cnst, string name, ITypeNode type, IConstantNode constant_value) { FieldBuilder fb = cur_type.DefineField(name, helper.GetTypeReference(type).tp, FieldAttributes.Static | FieldAttributes.Public | FieldAttributes.Literal); Type t = helper.GetTypeReference(type).tp; if (t.IsEnum) { if (!(t is EnumBuilder)) fb.SetConstant(Enum.ToObject(t, (constant_value as IEnumConstNode).constant_value)); else fb.SetConstant(constant_value.value); } else if (!(constant_value is INullConstantNode)) { if (constant_value.value.GetType() != t) { } else fb.SetConstant(constant_value.value); } } private void PushConstantValue(IConstantNode cnst) { if (cnst is IIntConstantNode) PushIntConst((cnst as IIntConstantNode).constant_value); else if (cnst is IDoubleConstantNode) PushDoubleConst((cnst as IDoubleConstantNode).constant_value); else if (cnst is IFloatConstantNode) PushFloatConst((cnst as IFloatConstantNode).constant_value); else if (cnst is ICharConstantNode) PushCharConst((cnst as ICharConstantNode).constant_value); else if (cnst is IStringConstantNode) PushStringConst((cnst as IStringConstantNode).constant_value); else if (cnst is IByteConstantNode) PushByteConst((cnst as IByteConstantNode).constant_value); else if (cnst is ILongConstantNode) PushLongConst((cnst as ILongConstantNode).constant_value); else if (cnst is IBoolConstantNode) PushBoolConst((cnst as IBoolConstantNode).constant_value); else if (cnst is ISByteConstantNode) PushSByteConst((cnst as ISByteConstantNode).constant_value); else if (cnst is IUShortConstantNode) PushUShortConst((cnst as IUShortConstantNode).constant_value); else if (cnst is IUIntConstantNode) PushUIntConst((cnst as IUIntConstantNode).constant_value); else if (cnst is IULongConstantNode) PushULongConst((cnst as IULongConstantNode).constant_value); else if (cnst is IShortConstantNode) PushShortConst((cnst as IShortConstantNode).constant_value); else if (cnst is IEnumConstNode) PushIntConst((cnst as IEnumConstNode).constant_value); else if (cnst is INullConstantNode) il.Emit(OpCodes.Ldnull); } private void ConvertConstantDefWithInitCall(IConstantDefinitionNode cnst, string name, ITypeNode type, IConstantNode constant_value) { TypeInfo ti = helper.GetTypeReference(type); FieldAttributes attrs = FieldAttributes.Public | FieldAttributes.Static; if (comp_opt.target == TargetType.Dll) attrs |= FieldAttributes.InitOnly; FieldBuilder fb = cur_type.DefineField(name, ti.tp, attrs); if (cnst != null) helper.AddConstant(cnst, fb); bool tmp = save_debug_info; save_debug_info = false; AddInitCall(il, fb, ti.init_meth, constant_value); save_debug_info = tmp; if (!ConvertedConstants.ContainsKey(constant_value)) ConvertedConstants.Add(constant_value, fb); } private void ConvertArrayConstantDef(IConstantDefinitionNode cnst, string name, ITypeNode type, IConstantNode constant_value) { //ConvertedConstants.ContainsKey(ArrayConstant) TypeInfo ti = helper.GetTypeReference(type); FieldAttributes attrs = FieldAttributes.Public | FieldAttributes.Static; if (comp_opt.target == TargetType.Dll) attrs |= FieldAttributes.InitOnly; FieldBuilder fb = cur_type.DefineField(name, ti.tp, attrs); if (cnst != null) helper.AddConstant(cnst, fb); CreateArrayGlobalVariable(il, fb, ti, constant_value as IArrayConstantNode, type); if (!ConvertedConstants.ContainsKey(constant_value)) ConvertedConstants.Add(constant_value, fb); } //это требование Reflection.Emit - все типы должны быть закрыты private void CloseTypes() { //(ssyy) TODO: подумать, в каком порядке создавать типы for (int i = 0; i < types.Count; i++) if (types[i].IsInterface) types[i].CreateType(); for (int i = 0; i < enums.Count; i++) enums[i].CreateType(); for (int i = 0; i < value_types.Count; i++) value_types[i].CreateType(); for (int i = 0; i < types.Count; i++) if (!types[i].IsInterface) types[i].CreateType(); } //перевод тела private void ConvertBody(IStatementNode body) { if (!(body is IStatementsListNode) && save_debug_info && body.Location != null) if (body.Location.begin_line_num == 0xFFFFFF) MarkSequencePoint(il, body.Location); body.visit(this); OptMakeExitLabel(); } private void OptMakeExitLabel() { if (ExitProcedureCall) { il.MarkLabel(ExitLabel); ExitProcedureCall = false; } } //перевод заголовков типов private void ConvertTypeHeaders(ICommonTypeNode[] types) { foreach (ICommonTypeNode t in types) { ConvertTypeHeaderInSpecialOrder(t); } } private void CreateTemplateClass(ITemplateClass t) { if (t.serialized_tree != null) { TypeBuilder tb = mb.DefineType(cur_unit + ".%" + t.name, TypeAttributes.Public, TypeFactory.ObjectType); types.Add(tb); CustomAttributeBuilder cust_bldr = new CustomAttributeBuilder(this.TemplateClassAttributeConstructor, new object[1] { t.serialized_tree }); tb.SetCustomAttribute(cust_bldr); } } private void CreateTypeSynonim(ITypeSynonym t) { TypeBuilder tb = mb.DefineType(cur_unit + ".%" + t.name, TypeAttributes.Public, TypeFactory.ObjectType); types.Add(tb); add_possible_type_attribute(tb, t); } private Type CreateTypedFileType(ICommonTypeNode t) { Type tt = helper.GetPascalTypeReference(t); if (tt != null) return tt; TypeBuilder tb = mb.DefineType(cur_unit + ".%" + t.name, TypeAttributes.Public, TypeFactory.ObjectType); types.Add(tb); helper.AddPascalTypeReference(t, tb); add_possible_type_attribute(tb, t); return tb; } private Type CreateTypedSetType(ICommonTypeNode t) { Type tt = helper.GetPascalTypeReference(t); if (tt != null) return tt; TypeBuilder tb = mb.DefineType(cur_unit + ".%" + t.name, TypeAttributes.Public, TypeFactory.ObjectType); types.Add(tb); helper.AddPascalTypeReference(t, tb); add_possible_type_attribute(tb, t); return tb; } private Type CreateShortStringType(ITypeNode t) { TypeBuilder tb = mb.DefineType(cur_unit + ".$string" + (uid++).ToString(), TypeAttributes.Public, TypeFactory.ObjectType); types.Add(tb); add_possible_type_attribute(tb, t); return tb; } //переводим заголовки типов в порядке начиная с базовых классов (т. е. у которых наследники - откомпилированные типы) private void ConvertTypeHeaderInSpecialOrder(ICommonTypeNode t) { if (t.type_special_kind == type_special_kind.diap_type) return; if (t.type_special_kind == type_special_kind.array_kind) return; if (t.depended_from_indefinite) return; if (t.type_special_kind == type_special_kind.typed_file && comp_opt.target == TargetType.Dll) { if (!t.name.Contains(" ")) { CreateTypedFileType(t); return; } } else if (t.type_special_kind == type_special_kind.set_type && comp_opt.target == TargetType.Dll) { if (!t.name.Contains(" ")) { CreateTypedSetType(t); return; } } if (helper.GetTypeReference(t) != null && !t.is_generic_parameter) return; if (t.is_generic_parameter) { //ConvertTypeHeaderInSpecialOrder(t.generic_container); AddTypeWithoutConvert(t); if (converting_generic_param != t) { return; } converting_generic_param = null; } IGenericTypeInstance gti = t as IGenericTypeInstance; if (gti != null) { if (gti.original_generic is ICommonTypeNode) { ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)gti.original_generic); } foreach (ITypeNode itn in gti.generic_parameters) { if (itn is ICommonTypeNode && !itn.is_generic_parameter) { ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)itn); } } } if (t.is_generic_type_definition) { AddTypeWithoutConvert(t); foreach (ICommonTypeNode par in t.generic_params) { converting_generic_param = par; ConvertTypeHeaderInSpecialOrder(par); } } else if ((t.type_special_kind == type_special_kind.none_kind || t.type_special_kind == type_special_kind.record) && !t.IsEnum && !t.is_generic_type_instance && !t.is_generic_parameter) { AddTypeWithoutConvert(t); } foreach (ITypeNode interf in t.ImplementingInterfaces) if (!(interf is ICompiledTypeNode)) ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)interf); if (t.base_type != null && !(t.base_type is ICompiledTypeNode)) { ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)t.base_type); } ConvertTypeHeader(t); } private void AddTypeWithoutConvert(ICommonTypeNode t) { if (helper.GetTypeReference(t) != null) return; TypeBuilder tb = mb.DefineType(cur_unit + "." + t.name, ConvertAttributes(t), null, new Type[0]); helper.AddType(t, tb); //(ssyy) обрабатываем generics if (t.is_generic_type_definition) { int count = t.generic_params.Count; string[] par_names = new string[count]; //Создаём массив имён параметров for (int i = 0; i < count; i++) { par_names[i] = t.generic_params[i].name; } //Определяем параметры в строящемся типе GenericTypeParameterBuilder[] net_pars = tb.DefineGenericParameters(par_names); for (int i = 0; i < count; i++) { //добавляем параметр во внутр. структуры helper.AddExistingType(t.generic_params[i], net_pars[i]); } } } //перевод релизаций типов private void ConvertTypeImplementations(ICommonTypeNode[] types) { foreach (ICommonTypeNode t in types) //если это не особый тип переводим реализацию наверно здесь много лишнего нужно оставить ISimpleArrayNode { if ( t.type_special_kind != type_special_kind.diap_type && !t.depended_from_indefinite) t.visit(this); } } private void ConvertTypeMemberHeaderAndRemoveFromList(ICommonTypeNode type, List<ICommonTypeNode> types) { if (!type.depended_from_indefinite) { if (type.type_special_kind == type_special_kind.array_wrapper && type.element_type.type_special_kind == type_special_kind.array_wrapper && type.element_type is ICommonTypeNode && types.IndexOf((ICommonTypeNode)(type.element_type)) > -1) { ConvertTypeMemberHeaderAndRemoveFromList((ICommonTypeNode)(type.element_type), types); } ConvertTypeMemberHeader(type); } types.Remove(type); } //перевод заголовков членов класса private void ConvertTypeMemberHeaders(ICommonTypeNode[] types) { //(ssyy) Переупорядочиваем, чтобы массивы создавались в правильном порядке List<ICommonTypeNode> ts = new List<ICommonTypeNode>(types); while (ts.Count > 0) { ConvertTypeMemberHeaderAndRemoveFromList(ts[0], ts); } foreach (ICommonTypeNode t in types) { foreach (ICommonMethodNode meth in t.methods) { if (meth.is_generic_function) { ConvertTypeInstancesMembersInFunction(meth); } } } } private Dictionary<TypeBuilder, TypeBuilder> added_types = new Dictionary<TypeBuilder, TypeBuilder>(); private void BuildCloseTypeOrder(ICommonTypeNode value, TypeBuilder tb) { foreach (ICommonClassFieldNode fld in value.fields) { ITypeNode ctn = fld.type; TypeInfo ti = helper.GetTypeReference(ctn); if (ctn is ICommonTypeNode && ti.tp.IsValueType && ti.tp is TypeBuilder) { BuildCloseTypeOrder((ICommonTypeNode)ctn, (TypeBuilder)ti.tp); } } if (!added_types.ContainsKey(tb)) { value_types.Add(tb); added_types[tb] = tb; } } private Type GetTypeOfGenericInstanceField(Type t, FieldInfo finfo) { if (finfo.FieldType.IsGenericParameter) { return t.GetGenericArguments()[finfo.FieldType.GenericParameterPosition]; } else { return finfo.FieldType; } } private void ConvertGenericInstanceTypeMembers(IGenericTypeInstance value) { if (helper.GetTypeReference(value) == null) { return; } ICompiledGenericTypeInstance compiled_inst = value as ICompiledGenericTypeInstance; if (compiled_inst != null) { ConvertCompiledGenericInstanceTypeMembers(compiled_inst); return; } ICommonGenericTypeInstance common_inst = value as ICommonGenericTypeInstance; if (common_inst != null) { ConvertCommonGenericInstanceTypeMembers(common_inst); return; } } //ssyy 04.02.2010. Вернул следующие 2 функции в исходное состояние. private void ConvertCompiledGenericInstanceTypeMembers(ICompiledGenericTypeInstance value) { Type t = helper.GetTypeReference(value).tp; bool is_delegated_type = t.BaseType == TypeFactory.MulticastDelegateType; foreach (IDefinitionNode dn in value.used_members.Keys) { ICompiledConstructorNode iccn = dn as ICompiledConstructorNode; if (iccn != null) { ConstructorInfo ci = TypeBuilder.GetConstructor(t, iccn.constructor_info); helper.AddConstructor(value.used_members[dn] as IFunctionNode, ci); continue; } ICompiledMethodNode icmn = dn as ICompiledMethodNode; if (icmn != null) { if (is_delegated_type && icmn.method_info.IsSpecialName) continue; MethodInfo mi = null; try { mi = TypeBuilder.GetMethod(t, icmn.method_info); } catch { if (icmn.method_info.DeclaringType.IsGenericType && !icmn.method_info.DeclaringType.IsGenericTypeDefinition) { Type gen_def_type = icmn.method_info.DeclaringType.GetGenericTypeDefinition(); foreach (MethodInfo mi2 in gen_def_type.GetMethods()) { if (mi2.MetadataToken == icmn.method_info.MetadataToken) { mi = mi2; break; } } mi = TypeBuilder.GetMethod(t, mi); } else mi = icmn.method_info; } helper.AddMethod(value.used_members[dn] as IFunctionNode, mi); continue; } ICompiledClassFieldNode icfn = dn as ICompiledClassFieldNode; if (icfn != null) { Type ftype = GetTypeOfGenericInstanceField(t, icfn.compiled_field); FieldInfo fi = TypeBuilder.GetField(t, icfn.compiled_field); helper.AddGenericField(value.used_members[dn] as ICommonClassFieldNode, fi, ftype); continue; } } } private void ConvertCommonGenericInstanceTypeMembers(ICommonGenericTypeInstance value) { Type t = helper.GetTypeReference(value).tp; foreach (IDefinitionNode dn in value.used_members.Keys) { ICommonMethodNode icmn = dn as ICommonMethodNode; if (icmn != null) { if (icmn.is_constructor) { MethInfo mi = helper.GetConstructor(icmn); if (mi != null) { ConstructorInfo cnstr = mi.cnstr; ConstructorInfo ci = TypeBuilder.GetConstructor(t, cnstr); helper.AddConstructor(value.used_members[dn] as IFunctionNode, ci); } continue; } else { MethodInfo meth = helper.GetMethod(icmn).mi; if (meth.GetType().FullName == "System.Reflection.Emit.MethodOnTypeBuilderInstantiation") meth = meth.GetGenericMethodDefinition(); MethodInfo mi = TypeBuilder.GetMethod(t, meth); helper.AddMethod(value.used_members[dn] as IFunctionNode, mi); continue; } } ICommonClassFieldNode icfn = dn as ICommonClassFieldNode; if (icfn != null) { FldInfo fldinfo = helper.GetField(icfn); if (!(fldinfo is GenericFldInfo)) { FieldInfo finfo = fldinfo.fi; Type ftype = GetTypeOfGenericInstanceField(t, finfo); FieldInfo fi = TypeBuilder.GetField(t, finfo); helper.AddGenericField(value.used_members[dn] as ICommonClassFieldNode, fi, ftype); } else { FieldInfo finfo = fldinfo.fi; FieldInfo fi = finfo; helper.AddGenericField(value.used_members[dn] as ICommonClassFieldNode, fi, (fldinfo as GenericFldInfo).field_type); } continue; } } } private object[] get_constants(IConstantNode[] cnsts) { object[] objs = new object[cnsts.Length]; for (int i = 0; i < objs.Length; i++) { objs[i] = cnsts[i].value; } return objs; } private PropertyInfo[] get_named_properties(IPropertyNode[] props) { PropertyInfo[] arr = new PropertyInfo[props.Length]; for (int i = 0; i < arr.Length; i++) { if (props[i] is ICompiledPropertyNode) arr[i] = (props[i] as ICompiledPropertyNode).property_info; else arr[i] = helper.GetProperty(props[i]).prop; } return arr; } private FieldInfo[] get_named_fields(IVAriableDefinitionNode[] fields) { FieldInfo[] arr = new FieldInfo[fields.Length]; for (int i = 0; i < arr.Length; i++) { if (fields[i] is ICompiledClassFieldNode) arr[i] = (fields[i] as ICompiledClassFieldNode).compiled_field; else arr[i] = helper.GetField(fields[i] as ICommonClassFieldNode).fi; } return arr; } private void MakeAttribute(ICommonNamespaceNode cnn) { IAttributeNode[] attrs = cnn.Attributes; for (int i = 0; i < attrs.Length; i++) { CustomAttributeBuilder cab = new CustomAttributeBuilder ((attrs[i].AttributeConstructor is ICompiledConstructorNode) ? (attrs[i].AttributeConstructor as ICompiledConstructorNode).constructor_info : helper.GetConstructor(attrs[i].AttributeConstructor).cnstr, get_constants(attrs[i].Arguments), get_named_properties(attrs[i].PropertyNames), get_constants(attrs[i].PropertyInitializers), get_named_fields(attrs[i].FieldNames), get_constants(attrs[i].FieldInitializers)); ab.SetCustomAttribute(cab); } } private void MakeAttribute(ICommonTypeNode ctn) { Type t = helper.GetTypeReference(ctn).tp; IAttributeNode[] attrs = ctn.Attributes; for (int i = 0; i < attrs.Length; i++) { //if (attrs[i].AttributeType == SystemLibrary.SystemLibrary.comimport_type) // continue; CustomAttributeBuilder cab = new CustomAttributeBuilder ((attrs[i].AttributeConstructor is ICompiledConstructorNode) ? (attrs[i].AttributeConstructor as ICompiledConstructorNode).constructor_info : helper.GetConstructor(attrs[i].AttributeConstructor).cnstr, get_constants(attrs[i].Arguments), get_named_properties(attrs[i].PropertyNames), get_constants(attrs[i].PropertyInitializers), get_named_fields(attrs[i].FieldNames), get_constants(attrs[i].FieldInitializers)); if (t is TypeBuilder) (t as TypeBuilder).SetCustomAttribute(cab); else if (t is EnumBuilder) (t as EnumBuilder).SetCustomAttribute(cab); } } private void MakeAttribute(ICommonPropertyNode prop) { PropertyBuilder pb = (PropertyBuilder)helper.GetProperty(prop).prop; IAttributeNode[] attrs = prop.Attributes; for (int i = 0; i < attrs.Length; i++) { CustomAttributeBuilder cab = new CustomAttributeBuilder ((attrs[i].AttributeConstructor is ICompiledConstructorNode) ? (attrs[i].AttributeConstructor as ICompiledConstructorNode).constructor_info : helper.GetConstructor(attrs[i].AttributeConstructor).cnstr, get_constants(attrs[i].Arguments), get_named_properties(attrs[i].PropertyNames), get_constants(attrs[i].PropertyInitializers), get_named_fields(attrs[i].FieldNames), get_constants(attrs[i].FieldInitializers)); pb.SetCustomAttribute(cab); } } private void MakeAttribute(ICommonClassFieldNode fld) { FieldBuilder fb = (FieldBuilder)helper.GetField(fld).fi; IAttributeNode[] attrs = fld.Attributes; for (int i = 0; i < attrs.Length; i++) { CustomAttributeBuilder cab = new CustomAttributeBuilder ((attrs[i].AttributeConstructor is ICompiledConstructorNode) ? (attrs[i].AttributeConstructor as ICompiledConstructorNode).constructor_info : helper.GetConstructor(attrs[i].AttributeConstructor).cnstr, get_constants(attrs[i].Arguments), get_named_properties(attrs[i].PropertyNames), get_constants(attrs[i].PropertyInitializers), get_named_fields(attrs[i].FieldNames), get_constants(attrs[i].FieldInitializers)); fb.SetCustomAttribute(cab); } } private void MakeAttribute(ICommonFunctionNode func) { MethodBuilder mb = helper.GetMethod(func).mi as MethodBuilder; IAttributeNode[] attrs = func.Attributes; for (int i = 0; i < attrs.Length; i++) { CustomAttributeBuilder cab = new CustomAttributeBuilder ((attrs[i].AttributeConstructor is ICompiledConstructorNode) ? (attrs[i].AttributeConstructor as ICompiledConstructorNode).constructor_info : helper.GetConstructor(attrs[i].AttributeConstructor).cnstr, get_constants(attrs[i].Arguments), get_named_properties(attrs[i].PropertyNames), get_constants(attrs[i].PropertyInitializers), get_named_fields(attrs[i].FieldNames), get_constants(attrs[i].FieldInitializers)); mb.SetCustomAttribute(cab); } foreach (IParameterNode pn in func.parameters) { ParamInfo pi = helper.GetParameter(pn); if (pi == null) continue; ParameterBuilder pb = pi.pb; attrs = pn.Attributes; for (int i = 0; i < attrs.Length; i++) { CustomAttributeBuilder cab = new CustomAttributeBuilder ((attrs[i].AttributeConstructor is ICompiledConstructorNode) ? (attrs[i].AttributeConstructor as ICompiledConstructorNode).constructor_info : helper.GetConstructor(attrs[i].AttributeConstructor).cnstr, get_constants(attrs[i].Arguments), get_named_properties(attrs[i].PropertyNames), get_constants(attrs[i].PropertyInitializers), get_named_fields(attrs[i].FieldNames), get_constants(attrs[i].FieldInitializers)); pb.SetCustomAttribute(cab); } } } //определяем заголовки членов класса private void ConvertTypeMemberHeader(ICommonTypeNode value) { //если это оболочка над массивом переводим ее особым образом if (value.type_special_kind == type_special_kind.diap_type || value.type_special_kind == type_special_kind.array_kind) return; if (value.fields.Length == 1 && value.fields[0].type is ISimpleArrayNode) { ConvertArrayWrapperType(value); return; } if (value is ISimpleArrayNode) return; //этот тип уже был переведен, поэтому находим его TypeInfo ti = helper.GetTypeReference(value); //ivan if (ti.tp.IsEnum || !(ti.tp is TypeBuilder)) return; TypeBuilder tb = (TypeBuilder)ti.tp; if (tb.IsValueType) BuildCloseTypeOrder(value, tb); //сохраняем контекст TypeInfo tmp_ti = cur_ti; cur_ti = ti; TypeBuilder tmp = cur_type; cur_type = tb; //(ssyy) Если это интерфейс, то пропускаем следующую хрень if (!value.IsInterface) { //определяем метод $Init$ для выделения памяти, если метод еще не определен (в структурах он опред-ся раньше) MethodBuilder clone_mb = null; MethodBuilder ass_mb = null; if (ti.init_meth != null && tb.IsValueType) { clone_mb = ti.clone_meth as MethodBuilder; ass_mb = ti.assign_meth as MethodBuilder; } foreach (ICommonClassFieldNode fld in value.fields) fld.visit(this); foreach (ICommonMethodNode meth in value.methods) ConvertMethodHeader(meth); foreach (ICommonPropertyNode prop in value.properties) prop.visit(this); foreach (IClassConstantDefinitionNode constant in value.constants) constant.visit(this); foreach (ICommonEventNode evnt in value.events) evnt.visit(this); //(ssyy) 21.05.2008 /*foreach (ICommonMethodNode meth in value.methods) { if (meth.is_generic_function) { ConvertTypeInstancesMembersInFunction(meth); } }*/ //добавляем ритерны в специальные методы //ti.init_meth.GetILGenerator().Emit(OpCodes.Ret); //if (hndl_mb != null) hndl_mb.GetILGenerator().Emit(OpCodes.Ret); if (clone_mb != null) { clone_mb.GetILGenerator().Emit(OpCodes.Ldloc_0); clone_mb.GetILGenerator().Emit(OpCodes.Ret); } if (ass_mb != null) { ass_mb.GetILGenerator().Emit(OpCodes.Ret); } if (ti.fix_meth != null) { ti.fix_meth.GetILGenerator().Emit(OpCodes.Ret); } }
void Initialize(Universe universe, string assemblyName, AssemblyBuilderAccess access, CompilerOptions options, ITypeMapper typeMapper = null) { if (universe == null) { throw new ArgumentNullException(nameof(universe)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } _compilerOptions = options; if (typeMapper == null) #if FEAT_IKVM { typeMapper = new TypeMapper(universe); } #else { typeMapper = new TypeMapper(); } #endif ExpressionFactory = new ExpressionFactory(typeMapper); StaticFactory = new StaticFactory(typeMapper); bool save = (access & AssemblyBuilderAccess.Save) != 0; string path = options.OutputPath; if (path == null && save) { throw new ArgumentNullException("options.OutputPath"); } Universe = universe; TypeMapper = typeMapper; _access = access; if (Helpers.IsNullOrEmpty(assemblyName)) { if (save) { throw new ArgumentNullException(nameof(assemblyName)); } assemblyName = Guid.NewGuid().ToString(); } string moduleName = path == null ? assemblyName : assemblyName + Path.GetExtension(path); _fileName = path; AssemblyName an = new AssemblyName(); an.Name = assemblyName; AssemblyBuilder = path != null ? Universe.DefineDynamicAssembly(an, access, Path.GetDirectoryName(path)) : Universe.DefineDynamicAssembly(an, access); #if FEAT_IKVM if (!Helpers.IsNullOrEmpty(options.KeyFile)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(File.OpenRead(options.KeyFile))); } else if (!Helpers.IsNullOrEmpty(options.KeyContainer)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(options.KeyContainer)); } else if (!Helpers.IsNullOrEmpty(options.PublicKey)) { AssemblyBuilder.__SetAssemblyPublicKey(FromHex(options.PublicKey)); } if (!Helpers.IsNullOrEmpty(options.ImageRuntimeVersion) && options.MetaDataVersion != 0) { AssemblyBuilder.__SetImageRuntimeVersion(options.ImageRuntimeVersion, options.MetaDataVersion); } ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, path, options.SymbolInfo); #else ModuleBuilder = save ? AssemblyBuilder.DefineDynamicModule(moduleName, Path.GetFileName(path)) : AssemblyBuilder.DefineDynamicModule(moduleName); #endif }
static AssemblyBuilder BuildAssembly(AssemblyName assemblyName, AppDomain appDomain) { var attributeBuilders = new[] { new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[0]) }; var assembly = appDomain.DefineDynamicAssembly ( assemblyName, AssemblyBuilderAccess.Run, attributeBuilders ); return assembly; }