/// <summary> /// Get the builded method. /// </summary> /// <returns>Builded method</returns> /// <seealso cref="AddMethod(string, Type[], Type)"/> public IResponse GetMethod() { TypeNotFinalizedBuildResponse response = methods.Pop(); response.Status = BuildedFunctionStatus.FunctionFinalizedTypeNotFinalized; var created = response.Emiter.CreateMethod(); if (methods.Count == 0) { AlreadyBuildedMethods = new Dictionary <Type, IResponse>(); if (typeBuilder != null) { Type currentType = typeBuilder.CreateType(); Debug.Assert(assemblyBuilder != null); #if !RUN_ONLY assemblyBuilder.Save(assemblyName.Name + ".dll"); #endif return(new TypeFinalizedBuildResponse() { Method = currentType.GetMethod(created.Name, created.GetParameters().Select(x => x.ParameterType).ToArray()) }); } } return(response); }
// Главная функция кодогенератора. Получает на вход синтаксическое дерево, обходит его и в хое его обхода с // помощью библиотеки System.Reflection строит исполняемый файл на MSIL, который потом можно запускать вне компилятора (однако, на компьютере должна быть установлена .Net Framwork) // Путь к файлу задаётся в интерфейсе компилятора public bool Proceed(Node Tree, RichTextBox RTB, string FileName) { _Tree = Tree; _RTB = RTB; InitFileName(FileName); try { Reflect.AssemblyName Name = new Reflect.AssemblyName(FileName); AsmBuilder = System.AppDomain.CurrentDomain.DefineDynamicAssembly(Name, Emit.AssemblyBuilderAccess.Save); ModBuilder = AsmBuilder.DefineDynamicModule(FileName); TypeTable = new Collections.Dictionary <string, Emit.TypeBuilder>(); CreatedTypeTable = new Collections.Dictionary <string, System.Type>(); SymbolTable = new Collections.List <Collections.Dictionary <string, Emit.LocalBuilder> >(); BeforeCompile(Tree); CreateCode(Tree); AsmBuilder.Save(FileName); this.SymbolTable = null; this.AssemblerGenerator = null; this.TypeTable = null; File.Move(FileName, FileName + ".exe"); File.Delete(FileName); return(true); } catch (System.Exception Exc) { _RTB.Text = Exc.Message; return(false); } }
public CodeGenerator(Expression pExpression, String pModuleName, ref LogHandler rLogHandler) { _symbolTable = new Dictionary <String, Emit.LocalBuilder>(); _assemblyName = new Reflect.AssemblyName(Path.GetFileNameWithoutExtension(pModuleName)); _statement = pExpression; //Init Assembly _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, Emit.AssemblyBuilderAccess.Save); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(pModuleName); _typeBuilder = _moduleBuilder.DefineType("PascalCompilerType"); _methodBuilder = _typeBuilder.DefineMethod ( "Main", Reflect.MethodAttributes.Static, typeof(void), Type.EmptyTypes ); _ilGenerator = _methodBuilder.GetILGenerator(); //Actual Work GenerateStatement(_statement, null); _ilGenerator.Emit(Emit.OpCodes.Ret); //Finalizing Work _typeBuilder.CreateType(); _moduleBuilder.CreateGlobalFunctions(); _assemblyBuilder.SetEntryPoint(_methodBuilder); _assemblyBuilder.Save(pModuleName); }
private static void SaveAssembly(string fullPath, AssemblyBuilder assemblyBuilder) { // assemblyBuilder.Save doesn't want to save with full path, so saving to current directory and then // moving file to final, weird string fileName = Path.GetFileName(fullPath); if (File.Exists(fileName)) { File.Delete(fullPath); } assemblyBuilder.Save(fileName); if (fileName != fullPath) { string targetDirectory = Path.GetDirectoryName(fullPath); Debug.Assert(targetDirectory != null, "targetDirectory != null"); Directory.CreateDirectory(targetDirectory); Debug.Assert(fileName != null, "fileName != null"); if (!File.Exists(fullPath)) { File.Move(fileName, fullPath); } } }
public CodeGen(Stmt stmt, string moduleName) { if (IO.Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } Reflect.AssemblyName name = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(moduleName)); Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save); Emit.ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); Emit.TypeBuilder typeBuilder = modb.DefineType("Foo"); Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); // CodeGenerator this.il = methb.GetILGenerator(); this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>(); // Go Compile! this.GenStmt(stmt); il.Emit(Emit.OpCodes.Ret); typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb); asmb.Save(moduleName); this.symbolTable = null; this.il = null; }
void Save(AssemblyBuilder builder, string filename) { switch (Parameters.Platform) { case "x86": builder.Save(filename, PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); break; case "x64": builder.Save(filename, PortableExecutableKinds.PE32Plus, ImageFileMachine.AMD64); break; case "itanium": builder.Save(filename, PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); break; default: //AnyCPU builder.Save(filename); break; } }
public CodeGen(ParseTreeNode stmt, string moduleName) { if (Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } AssemblyName name = new AssemblyName(Path.GetFileNameWithoutExtension(moduleName)); asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save); ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); //mainProgram = modb.DefineType("Program"); //var mainArgs = new List<Tuple<string, Type>>(); //var mainProgramDef = new FunctionDefinition //( // mainProgram.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes), // new List<FunctionDefinition.Argument>() //); SymbolTable symbolTable = new SymbolTable(modb.DefineType("__Program")); symbolTable.AddFunctionHeader("__Main", MethodAttributes.Static, null, new FunctionDefinition.Argument[]{}); //symbolTable.functionTable.AddHeader("Main", mainProgramDef); stmt = PreGenerate(stmt, symbolTable); stmt = ImportList(stmt, symbolTable); // CodeGenerator var il = symbolTable.functionTable["__Main"].GetILGenerator(); // Go Compile! this.GenStmt(stmt, il, symbolTable); //il.Emit(OpCodes.Ldstr, "Press any key to exit the program..."); //il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(string) })); //il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("ReadKey", new Type[] { })); il.Emit(OpCodes.Ret); //mainProgram.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(symbolTable.functionTable["__Main"].methodDefinition); symbolTable.typeTable.types[0].typeBuilder.CreateType(); asmb.Save(moduleName); foreach (var symbol in symbolTable.Locals) { Console.WriteLine("{0}: {1}", symbol.Key, symbol.Value); } symbolTable = null; il = null; }
/** * Saves the constructed assembly to a file */ public void SaveAssembly() { add_resources_to_assembly(); // if there are some nemerle specific metadata encoded in attributes if (contains_nemerle_specifics) { var attr = Manager.AttributeCompiler.MakeEmittedAttribute( SystemTypeCache.Reflection_AssemblyConfigurationAttribute, "ContainsNemerleTypes"); this._assembly_builder.SetCustomAttribute(attr); } // set the entry point if (_need_entry_point) { if (Option.IsSome(_entry_point, out var entry_point_method_info)) { _assembly_builder.SetEntryPoint(entry_point_method_info, (Manager.Options.TargetIsWinexe) ? Emit.PEFileKinds.WindowApplication : Emit.PEFileKinds.ConsoleApplication); } else { Message.Error("no suitable entry point (Main function) found"); } } // save the assembly try { var (portableExecutableKind, imageFileMachine) = make_platform_flags(Manager.Options.Platform); _assembly_builder.Save(Path.GetFileName(_OutputFileName), portableExecutableKind, imageFileMachine); //when (_debug_emit != null) _debug_emit.Close (); } catch (System.UnauthorizedAccessException e) { Message.Error($"could not write to output file `$(this._OutputFileName)' -- `$(e.Message)'"); } catch (IOException e) { Message.Error($"could not write to output file `$(this._OutputFileName)' -- `$(e.Message)'"); } catch (System.Runtime.InteropServices.COMException e) { Message.Error($"Problems saving assembly: $(e.Message)"); } catch (System.ApplicationException e) { Message.Error(e.Message); } }
private void finalizar(string nombreEjecutable) { //Asigno una pausa para indicar que finalizo la ejecucion del codigo objetivo generado anadirPausa(); //Creo el assembler .net y defino las ultimas opciones de configuracion il.Emit(Emit.OpCodes.Ret); Type pp = typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb, Reflect.Emit.PEFileKinds.ConsoleApplication); asmb.Save(IO.Path.GetFileName(nombreEjecutable)); //Ahora procedo a limpiar la tabla de direcciones para su proximo uso. TablaDireccionesSimbolos.Clear(); this.il = null; }
public AssemblyGen(TypeDeclaration methodDec, string moduleName, string dllProbeDirectory) { if (IO.Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } this.dllProbeDirectory = dllProbeDirectory; typeList = new List <TypeGen>(); Reflect.AssemblyName name = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(moduleName)); Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save); Emit.ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); GenerateType(methodDec, modb, dllProbeDirectory); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(GetEntryPoint()); asmb.Save(moduleName); }
public static Type BuildPropertyObject(System.Collections.Generic.IEnumerable <System.Collections.Generic.KeyValuePair <string, Type> > obj) { string nameOfDLL = "magic.dll"; string nameOfAssembly = "magic_Assembly"; string nameOfModule = "magic_Module"; string nameOfType = "magic_Type"; System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName { Name = nameOfAssembly }; System.Reflection.Emit.AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave); System.Reflection.Emit.ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(nameOfModule, nameOfDLL); System.Reflection.Emit.TypeBuilder typeBuilder = moduleBuilder.DefineType(nameOfType, System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class); foreach (var prop in obj) { string Name = prop.Key; Type DataType = prop.Value; System.Reflection.Emit.FieldBuilder field = typeBuilder.DefineField("_" + Name, DataType, System.Reflection.FieldAttributes.Private); System.Reflection.Emit.PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(Name, System.Reflection.PropertyAttributes.SpecialName, DataType, null); System.Reflection.MethodAttributes methodAttributes = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName; System.Reflection.Emit.MethodBuilder methodBuilderGetter = typeBuilder.DefineMethod("get_" + Name, methodAttributes, DataType, new Type[] { }); System.Reflection.Emit.MethodBuilder methodBuilderSetter = typeBuilder.DefineMethod("set_" + Name, methodAttributes, typeof(void), new Type[] { DataType }); System.Reflection.Emit.ILGenerator ilGeneratorGetter = methodBuilderGetter.GetILGenerator(); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldfld, field); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ret); System.Reflection.Emit.ILGenerator ilGeneratorSetter = methodBuilderSetter.GetILGenerator(); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_1); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Stfld, field); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ret); propertyBuilder.SetGetMethod(methodBuilderGetter); propertyBuilder.SetSetMethod(methodBuilderSetter); } // Yes! you must do this, it should not be needed but it is! Type dynamicType = typeBuilder.CreateType(); // Save to file assemblyBuilder.Save(nameOfDLL); return(dynamicType); }
public CodeGen(stmt stmt, string moduleName, int count) { if (IO.Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } stmts = stmt; Reflect.AssemblyName name = new Reflect.AssemblyName("FAJF"); //name of the assembly Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save); Emit.ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); Emit.TypeBuilder typeBuilder = modb.DefineType("resister"); //name of the class Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); // CodeGenerator this.il = methb.GetILGenerator(); this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>(); counting = 0; counter = count; counters = 0; // Go Compile! this.GenStmt(stmt); il.Emit(Emit.OpCodes.Ret); typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb); asmb.Save(moduleName); // this.il.EmitWriteLine("press any key to continue"); this.symbolTable = null; this.il = null; System.Diagnostics.Process.Start(moduleName); }
/* * Method: WriteWrapperToDisk * * Writes the generated wrapper out to disk. Should only be called for permanent wrappers. */ private void WriteWrapperToDisk(AssemblyBuilder assemblyBuilder, string wrapperPath) { try { FileInfo wrapperFile = new FileInfo(wrapperPath); if (wrapperFile.Exists) { wrapperFile.Delete(); } switch (_targetProcessorArchitecture) { case UtilitiesProcessorArchitecture.X86: assemblyBuilder.Save ( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit, ImageFileMachine.I386 ); break; case UtilitiesProcessorArchitecture.AMD64: assemblyBuilder.Save ( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, ImageFileMachine.AMD64 ); break; case UtilitiesProcessorArchitecture.IA64: assemblyBuilder.Save ( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64 ); break; case UtilitiesProcessorArchitecture.ARM: assemblyBuilder.Save ( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit, ImageFileMachine.ARM ); break; case UtilitiesProcessorArchitecture.MSIL: default: // If no target processor architecture was passed, we assume MSIL; calling Save // with no parameters should be equivalent to saving as ILOnly. assemblyBuilder.Save(wrapperFile.Name); break; } // AssemblyBuilder doesn't always throw when it's supposed to write stuff to a non-writable // network path. Make sure that the assembly actually got written to where we wanted it to. File.GetLastWriteTime(wrapperPath); } catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(e)) throw; if (!Silent) { Log.LogWarningWithCodeFromResources("ResolveComReference.ErrorCreatingWrapperAssembly", ItemName, e.Message); } throw new ComReferenceResolutionException(e); } }
private void SaveAssembly( string fullyQualifiedModuleName, AssemblyBuilder assemblyBuilder, TypeBuilder typeBuilder) { Type NireType = typeBuilder.CreateType(); NireType.GetMethod("Main").Invoke(null, new string[] {null}); // set the entry point for the application and save it assemblyBuilder.SetEntryPoint(this.methodbuilder, PEFileKinds.ConsoleApplication); assemblyBuilder.Save(fullyQualifiedModuleName); }
[Test] // DefineVersionInfoResource (String, String, String, String, String) public void TestDefineVersionInfoResource2_Culture_NotSupported () { AssemblyName aname = new AssemblyName (); aname.CultureInfo = new CultureInfo ("nl-BE"); aname.Name = "lib"; aname.Version = new Version (3, 5, 7); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly ( aname, AssemblyBuilderAccess.RunAndSave, tempDir); // AssemblyCulture Type attrType = typeof (AssemblyCultureAttribute); ConstructorInfo ci = attrType.GetConstructor (new Type [] { typeof (String) }); CustomAttributeBuilder cab = new CustomAttributeBuilder ( ci, new object [1] { "doesnotexist" }); ab.SetCustomAttribute (cab); ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E"); try { ab.Save ("lib.dll"); Assert.Fail ("#A1"); } catch (CultureNotFoundException ex) { } ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.RunAndSave, tempDir); // AssemblyCulture attrType = typeof (AssemblyCultureAttribute); ci = attrType.GetConstructor (new Type [] { typeof (String) }); cab = new CustomAttributeBuilder (ci, new object [1] { "neutral" }); ab.SetCustomAttribute (cab); ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E"); try { ab.Save ("lib.dll"); Assert.Fail ("#B1"); } catch (CultureNotFoundException ex) { } }
private AssemblyBuilder CreateExecutable(string name) { ILGenerator il; name = name.Replace('\\', '/'); string exename = name.Contains('/') ? name.Substring(name.LastIndexOf('/') + 1) : name; string pathname = name.Contains('/') ? name.Remove(name.LastIndexOf('/')) : null; string asmname = exename.Contains('.') ? exename.Remove(exename.LastIndexOf('.')) : exename; // // We are generating a dynamic assembly here. // // Get type information from the runtime assembly var asm_runtime = Assembly.Load("GameCreator.Runtime"); var asm_gamei = Assembly.Load("GameCreator.Runtime.Game.Interpreted"); var asm_game = Assembly.Load("GameCreator.Runtime.Game"); Type t_gamei = asm_gamei.GetType("GameCreator.Runtime.Game.Interpreted.InterpretedGame"); Type t_game = asm_game.GetType("GameCreator.Runtime.Game.Game"); Type t_ext = typeof(ResourceExtensions); Type t_obj = typeof(Framework.Object); Type t_room = typeof(Room); Type t_event = typeof(Event); Type t_lib = typeof(Framework.ActionLibrary); Type t_context = typeof(LibraryContext); Type t_rcontext = typeof(ResourceContext); // Define our dynamic assembly System.Reflection.Emit.AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(asmname), AssemblyBuilderAccess.RunAndSave, pathname); ModuleBuilder mod = asm.DefineDynamicModule(exename, exename); // Define our Program type TypeBuilder program = mod.DefineType(string.Format("{0}.Program", asmname)); System.Resources.IResourceWriter resw = mod.DefineResource(string.Format("{0}.Program.resources", asmname), string.Empty); FieldBuilder resourceManager = program.DefineField("resourceManager", typeof(System.Resources.ResourceManager), FieldAttributes.Static); MethodBuilder GetResourceManager = program.DefineMethod("GetResourceManager", MethodAttributes.Static, typeof(System.Resources.ResourceManager), Type.EmptyTypes); il = GetResourceManager.GetILGenerator(); System.Reflection.Emit.Label grm_l_1 = il.DefineLabel(); il.Emit(OpCodes.Ldsfld, resourceManager); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Brtrue_S, grm_l_1); il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ldstr, string.Format("{0}.Program", asmname)); il.Emit(OpCodes.Ldtoken, program); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public)); il.Emit(OpCodes.Callvirt, typeof(Type).GetProperty("Assembly").GetGetMethod()); il.Emit(OpCodes.Newobj, typeof(System.Resources.ResourceManager).GetConstructor(new Type[] { typeof(string), typeof(Assembly) })); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Stsfld, resourceManager); il.MarkLabel(grm_l_1); il.Emit(OpCodes.Ret); //program.SetCustomAttribute(new CustomAttributeBuilder(typeof(STAThreadAttribute).GetConstructor(new Type[] { }), new object[] { })); // our static Main() function // { // GameCreator.Runtime.Object obj; // GameCreator.Runtime.Event ev; // GameCreator.Runtime.ActionLibrary lib; // GameCreator.Runtime.Game.Init(); // ... // lib = GameCreator.ActionLibrary.Define(id); // lib.DefineAction(actionid, kind, execution, question, func, code, args); // ... // GameCreator.Runtime.Script.Define("name", index, "code"); // ... // obj = GameCreator.Runtime.Object.Define("name", index); // ev = obj.DefineEvent(event, num); // ev.DefineAction(libid, actionid, args, appliesto, relative, not); // ... // GameCreator.Runtime.Room.Define("name", index).CreationCode = "code"; // ... // GameCreator.Runtime.Game.Name = "name"; // GameCreator.Runtime.Game.Run(); // (return) // } // GameCreator.Runtime.Object obj; // GameCreator.Runtime.Event ev; // GameCreator.Runtime.ActionLibrary lib; MethodBuilder initLibraries = program.DefineMethod("InitLibraries", MethodAttributes.Static); il = initLibraries.GetILGenerator(); foreach (ActionLibrary lib in Program.Library) { // lib = GameCreator.ActionLibrary.Define(id); il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null); il.Emit(OpCodes.Ldc_I4, lib.LibraryID); il.EmitCall(OpCodes.Call, t_context.GetMethod("GetActionLibrary", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int) }, null), null); foreach (ActionDefinition ad in lib.Actions) { // lib.DefineAction(actionid, kind, execution, question, func, code, args); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldc_I4, ad.ActionID); il.Emit(OpCodes.Ldc_I4, (int)ad.Kind); il.Emit(OpCodes.Ldc_I4, (int)ad.ExecutionType); il.Emit(ad.IsQuestion ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ldstr, ad.FunctionName); il.Emit(OpCodes.Ldstr, ad.Code); // ... , new ActionArgumentType[] { x, y, z }, il.Emit(OpCodes.Ldc_I4, ad.ArgumentCount); il.Emit(OpCodes.Newarr, typeof(ActionArgumentType)); for (int i = 0; i < ad.ArgumentCount; i++) { il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldc_I4, (int)ad.Arguments[i].Type); il.Emit(OpCodes.Stelem_I4); } // il.EmitCall(OpCodes.Call, t_lib.GetMethod("DefineAction", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(ActionKind), typeof(ActionExecutionType), typeof(bool), typeof(string), typeof(string), typeof(ActionArgumentType[]) }, null), null); } il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ret); MethodBuilder defineSprites = program.DefineMethod("DefineSprites", MethodAttributes.Static); il = defineSprites.GetILGenerator(); foreach (SpriteResourceView res in Program.Sprites.Values) { // Define the resource int i = 0; foreach (Bitmap b in res.Animation.Frames) { resw.AddResource(string.Format("spr_{0}_{1}", res.ResourceID, i++), b); } // GameCreator.Runtime.Sprite.Define("name", index, subimages); il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Sprites", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.Emit(OpCodes.Ldstr, res.Name); il.Emit(OpCodes.Ldc_I4, res.ResourceID); il.Emit(OpCodes.Ldc_I4, res.Animation.FrameCount); il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Sprite>), typeof(string), typeof(int), typeof(int) }, null), null); il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ret); MethodBuilder defineScripts = program.DefineMethod("DefineScripts", MethodAttributes.Static); il = defineScripts.GetILGenerator(); foreach (ScriptResourceView res in Program.Scripts.Values) { // GameCreator.Runtime.Script.Define("name", index, "code"); il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Sprites", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.Emit(OpCodes.Ldstr, res.Name); il.Emit(OpCodes.Ldc_I4, res.ResourceID); il.Emit(OpCodes.Ldstr, res.Code); il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Script>), typeof(string), typeof(int), typeof(string) }, null), null); il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ret); MethodBuilder defineObjects = program.DefineMethod("DefineObjects", MethodAttributes.Static); il = defineObjects.GetILGenerator(); foreach (ObjectResourceView res in Program.Objects.Values) { // obj = GameCreator.Runtime.Object.Define("name", index); il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Objects", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.Emit(OpCodes.Ldstr, res.Name); il.Emit(OpCodes.Ldc_I4, res.ResourceID); il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Framework.Object>), typeof(string), typeof(int) }, null), null); foreach (ObjectEvent ev in res.Events) { // ev = obj.DefineEvent(event, num); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldc_I4, (int)ev.EventType); il.Emit(OpCodes.Ldc_I4, (int)ev.EventNumber); il.EmitCall(OpCodes.Call, t_obj.GetMethod("DefineEvent", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(int) }, null), null); foreach (ActionDeclaration ad in ev.Actions) { // ev.DefineAction(libid, actionid, args, appliesto, relative, not); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldc_I4, ad.Kind.Library.LibraryID); il.Emit(OpCodes.Ldc_I4, ad.Kind.ActionID); // ... , new string[] { "arg", "arg", "arg" }, il.Emit(OpCodes.Ldc_I4, ad.Kind.ArgumentCount); il.Emit(OpCodes.Newarr, typeof(string)); for (int i = 0; i < ad.Kind.ArgumentCount; i++) { il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldstr, ad.Arguments[i]); il.Emit(OpCodes.Stelem_Ref); } // il.Emit(OpCodes.Ldc_I4, ad.AppliesTo); il.Emit(ad.Relative ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); il.Emit(ad.Not ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); il.EmitCall(OpCodes.Call, t_event.GetMethod("DefineAction", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(int), typeof(string[]), typeof(int), typeof(bool), typeof(bool) }, null), null); } il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Dup); // obj.SpriteIndex = ind; il.Emit(OpCodes.Ldc_I4, res.Sprite); il.EmitCall(OpCodes.Call, t_obj.GetProperty("SpriteIndex").GetSetMethod(), null); //obj.Depth = d; il.Emit(OpCodes.Ldc_R8, res.Depth); il.EmitCall(OpCodes.Call, t_obj.GetProperty("Depth").GetSetMethod(), null); } il.Emit(OpCodes.Ret); MethodBuilder defineRooms = program.DefineMethod("DefineRooms", MethodAttributes.Static); il = defineRooms.GetILGenerator(); // Start defining rooms. // We perform a 'preorder iterative traversal' of the 'Rooms' TreeNode to ensure the rooms are defined in the correct order. // We can probably eliminate the stack by using the 'Parent' property of the nodes instead. Stack <TreeNode> nodes = new Stack <TreeNode>(); nodes.Push(Rooms.Node); while (nodes.Count != 0) { TreeNode tn = nodes.Pop(); if (tn.Tag.GetType() == typeof(RoomResourceView)) { RoomResourceView res = (RoomResourceView)(tn.Tag); // GameCreator.Runtime.Room.Define("name", index).CreationCode = "code"; il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Rooms", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null); il.Emit(OpCodes.Ldstr, res.Name); il.Emit(OpCodes.Ldc_I4, res.ResourceID); il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Room>), typeof(string), typeof(int) }, null), null); il.Emit(OpCodes.Ldstr, res.CreationCode); il.EmitCall(OpCodes.Call, t_room.GetProperty("CreationCode").GetSetMethod(), null); } tn = tn.LastNode; while (tn != null) { nodes.Push(tn); tn = tn.PrevNode; } } il.Emit(OpCodes.Ret); MethodBuilder main = program.DefineMethod("Main", MethodAttributes.Static); main.SetCustomAttribute(new CustomAttributeBuilder(typeof(STAThreadAttribute).GetConstructor(System.Type.EmptyTypes), new object[] { })); il = main.GetILGenerator(); // GameCreator.Runtime.Game.Interpreted.InterpretedGame.Initialize(); il.EmitCall(OpCodes.Call, t_gamei.GetMethod("Initialize"), null); // InitLibraries(); il.EmitCall(OpCodes.Call, initLibraries, null); // DefineScripts(); il.EmitCall(OpCodes.Call, defineScripts, null); // DefineSprites(); il.EmitCall(OpCodes.Call, defineSprites, null); // DefineObjects(); il.EmitCall(OpCodes.Call, defineObjects, null); // DefineRooms(); il.EmitCall(OpCodes.Call, defineRooms, null); // GameCreator.Runtime.Game.Name = "name"; //il.Emit(OpCodes.Ldstr, asmname); //il.EmitCall(OpCodes.Call, t_game.GetProperty("Name").GetSetMethod(), null); // GameCreator.Runtime.Game.ResourceManager = GetResourceManager(); il.EmitCall(OpCodes.Call, GetResourceManager, null); il.EmitCall(OpCodes.Call, t_game.GetProperty("ResourceManager").GetSetMethod(), null); // GameCreator.Runtime.Game.Interpreted.InterpretedGame.Run(); il.EmitCall(OpCodes.Call, t_gamei.GetMethod("Run"), null); // return statement, required il.Emit(OpCodes.Ret); program.CreateType(); asm.SetEntryPoint(main, PEFileKinds.WindowApplication); // Use 32 bit (i386) since GTK# requires it and we plan on using it later asm.Save(exename, PortableExecutableKinds.ILOnly, ImageFileMachine.I386); return(asm); }
private static void Save(AssemblyBuilder assembly, ProxyContext context) { if ((context.Access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save) { assembly.Save(assembly.GetName().Name + ".dll"); if (context.Verify) { AssemblyVerification.Verify(assembly); } } }
private void GenerateAssemblyFile( AssemblyBuilder assemblyBuilder ) { var context = new SerializationContext(); context.EmitterFlavor = EmitterFlavor.FieldBased; context.GeneratorOption = SerializationMethodGeneratorOption.CanDump; context.SerializationMethod = this._method; // AssemblyBuilder cannot be debugged because no PDB files (and 'dummy' source files to step). DefaultSerializationMethodGeneratorManager.SetUpAssemblyBuilderAttributes( assemblyBuilder, false ); var generatorManager = SerializationMethodGeneratorManager.Get( assemblyBuilder ); foreach( var targetType in this._targetTypes ) { ( Activator.CreateInstance( typeof( Builder<> ).MakeGenericType( targetType) ) as Builder ).GenerateSerializerTo( context, generatorManager ); } assemblyBuilder.Save( this._assemblyName.Name + ".dll" ); }
/// <summary> /// Internal Assmebly runtime creation /// </summary> private void CreateRTAssemblyAndModule() { AssemblyName assemblyName = new AssemblyName(this.XmlAssemblyData.FileName); Version outVersion; if (Version.TryParse(this.XmlAssemblyData.Version, out outVersion) == false) throw new InvalidDataException("unable to parse the Assembly Version data"); assemblyName.Version = outVersion; RTAssemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); // For a single-module assembly, the module name is usually // the assembly name plus an extension. ModuleBuilder moduleBuilder = RTAssemblyBuilder.DefineDynamicModule(this.XmlAssemblyData.FileName + ".dll"); // foreach namespace create type foreach(XmlModelNamespaceRoot xmlNamespace in this.XmlAssemblyData.Namespaces) { CreateRTNamespaceType(moduleBuilder, xmlNamespace); } RTAssemblyBuilder.Save(this.XmlAssemblyData.FileName + ".dll"); }
public void ManifestModule () { AssemblyName aname = new AssemblyName ("ManifestModule1"); ab = domain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.RunAndSave, tempDir); Assert.IsNotNull (ab.ManifestModule, "#A1"); Assert.AreEqual (1, ab.GetModules ().Length, "#A2"); Assert.AreEqual (typeof (ModuleBuilder), ab.ManifestModule.GetType (), "#A3"); ModuleBuilder mb1 = (ModuleBuilder) ab.ManifestModule; Assert.AreSame (mb1, ab.GetModules () [0], "#B1"); Assert.IsFalse (mb1.IsResource (), "#B2"); Assert.AreSame (mb1, ab.ManifestModule, "#B3"); ab.Save ("ManifestModule.dll"); ModuleBuilder mb2 = (ModuleBuilder) ab.ManifestModule; Assert.AreSame (mb2, ab.GetModules () [0], "#C1"); Assert.IsFalse (mb2.IsResource (), "#C2"); Assert.AreSame (mb2, ab.ManifestModule, "#C3"); Assert.AreSame (mb1, mb2, "#C4"); }
[Test] // SetCustomAttribute (CustomAttributeBuilder) public void TestSetCustomAttribute1 () { Assembly a; AssemblyName an; AssemblyName check; Attribute attr; string filename; an = new AssemblyName (); an.Name = "TestSetCustomAttributeA"; ab = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, tempDir); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyVersionAttribute). GetConstructor (new Type [] { typeof (string) }), new object [] { "1.2.3.4"})); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyCultureAttribute). GetConstructor (new Type [] { typeof (string) }), new object [] { "bar"})); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyAlgorithmIdAttribute). GetConstructor (new Type [] { typeof (AssemblyHashAlgorithm) }), new object [] { AssemblyHashAlgorithm.MD5 })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyFlagsAttribute). GetConstructor (new Type [] { typeof (uint) }), new object [] { (uint)0xff })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute). GetConstructor (new Type [] { typeof (bool) }), new object [] { true })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (FooAttribute). GetConstructor (Type.EmptyTypes), new object [0])); ab.Save ("TestSetCustomAttributeA.dll"); filename = Path.Combine (tempDir, "TestSetCustomAttributeA.dll"); check = AssemblyName.GetAssemblyName (filename); Assert.AreEqual (CultureInfo.InvariantCulture, check.CultureInfo, "#A1"); #if NET_2_0 Assert.AreEqual (AssemblyNameFlags.None, check.Flags, "#A2"); #else Assert.AreEqual (AssemblyNameFlags.PublicKey, check.Flags, "#A2"); #endif Assert.AreEqual ("TestSetCustomAttributeA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", check.FullName, "#A3"); #if NET_2_0 Assert.IsNull (check.GetPublicKey (), "#A4"); #else Assert.AreEqual (new byte [0], check.GetPublicKey (), "#A4"); #endif #if NET_2_0 Assert.AreEqual (new byte [0], check.GetPublicKeyToken (), "#A5"); #else Assert.IsNull (check.GetPublicKeyToken (), "#A5"); #endif Assert.AreEqual (AssemblyHashAlgorithm.SHA1, check.HashAlgorithm, "#A6"); Assert.IsNull (check.KeyPair, "#A7"); Assert.AreEqual ("TestSetCustomAttributeA", check.Name, "#A8"); #if NET_2_0 //Assert.AreEqual (ProcessorArchitecture.MSIL, check.ProcessorArchitecture, "#A9"); #endif Assert.AreEqual (new Version (0, 0, 0, 0), check.Version, "#A10"); Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, check.VersionCompatibility, "#A11"); using (FileStream fs = File.OpenRead (filename)) { byte [] buffer = new byte [fs.Length]; fs.Read (buffer, 0, buffer.Length); a = Assembly.Load (buffer); } attr = Attribute.GetCustomAttribute (a, typeof (AssemblyVersionAttribute)); Assert.IsNotNull (attr, "#A12a"); Assert.AreEqual ("1.2.3.4", ((AssemblyVersionAttribute) attr).Version, "#A12b"); attr = Attribute.GetCustomAttribute (a, typeof (AssemblyCultureAttribute)); Assert.IsNotNull (attr, "#A13a"); Assert.AreEqual ("bar", ((AssemblyCultureAttribute) attr).Culture, "#A13b"); attr = Attribute.GetCustomAttribute (a, typeof (AssemblyAlgorithmIdAttribute)); Assert.IsNotNull (attr, "#A14a"); Assert.AreEqual ((uint) AssemblyHashAlgorithm.MD5, ((AssemblyAlgorithmIdAttribute) attr).AlgorithmId, "#A14b"); attr = Attribute.GetCustomAttribute (a, typeof (AssemblyFlagsAttribute)); Assert.IsNotNull (attr, "#A15a"); Assert.AreEqual ((uint) 0xff, ((AssemblyFlagsAttribute) attr).Flags, "#A15b"); attr = Attribute.GetCustomAttribute (a, typeof (FooAttribute)); Assert.IsNotNull (attr, "#A16"); an = new AssemblyName (); an.CultureInfo = new CultureInfo ("nl-BE"); an.Flags = AssemblyNameFlags.Retargetable; an.Name = "TestSetCustomAttributeB"; #if NET_2_0 an.ProcessorArchitecture = ProcessorArchitecture.IA64; #endif an.Version = new Version (1, 3, 5, 7); an.VersionCompatibility = AssemblyVersionCompatibility.SameDomain; ab = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, tempDir); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyVersionAttribute). GetConstructor (new Type [] { typeof (string) }), new object [] { "1.2.3.4" })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyCultureAttribute). GetConstructor (new Type [] { typeof (string) }), new object [] { "en-US" })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyAlgorithmIdAttribute). GetConstructor (new Type [] { typeof (AssemblyHashAlgorithm) }), new object [] { AssemblyHashAlgorithm.MD5 })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyFlagsAttribute). GetConstructor (new Type [] { typeof (uint) }), new object [] { (uint) 0x0100 })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute). GetConstructor (new Type [] { typeof (bool) }), new object [] { true })); ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (FooAttribute). GetConstructor (Type.EmptyTypes), new object [0])); ab.Save ("TestSetCustomAttributeB.dll"); filename = Path.Combine (tempDir, "TestSetCustomAttributeB.dll"); check = AssemblyName.GetAssemblyName (filename); Assert.AreEqual ("nl-BE", check.CultureInfo.Name, "#B1"); #if NET_2_0 Assert.AreEqual (AssemblyNameFlags.Retargetable, check.Flags, "#B2"); #else Assert.AreEqual (AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, check.Flags, "#B2"); #endif Assert.AreEqual ("TestSetCustomAttributeB, Version=1.3.5.7, Culture=nl-BE, PublicKeyToken=null, Retargetable=Yes", check.FullName, "#B3"); #if NET_2_0 Assert.IsNull (check.GetPublicKey (), "#B4"); #else Assert.AreEqual (new byte [0], check.GetPublicKey (), "#B4"); #endif #if NET_2_0 Assert.AreEqual (new byte [0], check.GetPublicKeyToken (), "#B5"); #else Assert.IsNull (check.GetPublicKeyToken (), "#B5"); #endif Assert.AreEqual (AssemblyHashAlgorithm.SHA1, check.HashAlgorithm, "#B6"); Assert.IsNull (check.KeyPair, "#B7"); Assert.AreEqual ("TestSetCustomAttributeB", check.Name, "#B8"); #if NET_2_0 //Assert.AreEqual (ProcessorArchitecture.MSIL, check.ProcessorArchitecture, "#B9"); #endif Assert.AreEqual (new Version (1, 3, 5, 7), check.Version, "#B10"); Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, check.VersionCompatibility, "#B11"); using (FileStream fs = File.OpenRead (filename)) { byte [] buffer = new byte [fs.Length]; fs.Read (buffer, 0, buffer.Length); a = Assembly.Load (buffer); } attr = Attribute.GetCustomAttribute (a, typeof (AssemblyVersionAttribute)); Assert.IsNotNull (attr, "#B12a"); Assert.AreEqual ("1.2.3.4", ((AssemblyVersionAttribute) attr).Version, "#B12b"); attr = Attribute.GetCustomAttribute (a, typeof (AssemblyCultureAttribute)); Assert.IsNotNull (attr, "#B13a"); Assert.AreEqual ("en-US", ((AssemblyCultureAttribute) attr).Culture, "#B13b"); attr = Attribute.GetCustomAttribute (a, typeof (AssemblyAlgorithmIdAttribute)); Assert.IsNotNull (attr, "#B14a"); Assert.AreEqual ((uint) AssemblyHashAlgorithm.MD5, ((AssemblyAlgorithmIdAttribute) attr).AlgorithmId, "#B14b"); attr = Attribute.GetCustomAttribute (a, typeof (AssemblyFlagsAttribute)); Assert.IsNotNull (attr, "#B15a"); Assert.AreEqual ((uint) 0x0100, ((AssemblyFlagsAttribute) attr).Flags, "#B15b"); attr = Attribute.GetCustomAttribute (a, typeof (FooAttribute)); Assert.IsNotNull (attr, "#B16"); }
private void WriteWrapperToDisk(AssemblyBuilder assemblyBuilder, string wrapperPath) { try { FileInfo info = new FileInfo(wrapperPath); if (info.Exists) { info.Delete(); } string targetProcessorArchitecture = this.targetProcessorArchitecture; if (targetProcessorArchitecture == null) { goto Label_0091; } if (!(targetProcessorArchitecture == "x86")) { if (targetProcessorArchitecture == "AMD64") { goto Label_0069; } if (targetProcessorArchitecture == "IA64") { goto Label_007D; } if (targetProcessorArchitecture == "MSIL") { } goto Label_0091; } assemblyBuilder.Save(info.Name, PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly, ImageFileMachine.I386); goto Label_009D; Label_0069: assemblyBuilder.Save(info.Name, PortableExecutableKinds.PE32Plus | PortableExecutableKinds.ILOnly, ImageFileMachine.AMD64); goto Label_009D; Label_007D: assemblyBuilder.Save(info.Name, PortableExecutableKinds.PE32Plus | PortableExecutableKinds.ILOnly, ImageFileMachine.IA64); goto Label_009D; Label_0091: assemblyBuilder.Save(info.Name); Label_009D: File.GetLastWriteTime(wrapperPath); } catch (Exception exception) { if (Microsoft.Build.Shared.ExceptionHandling.NotExpectedException(exception)) { throw; } base.Log.LogWarningWithCodeFromResources("ResolveComReference.ErrorCreatingWrapperAssembly", new object[] { this.ItemName, exception.Message }); throw new ComReferenceResolutionException(exception); } }
public static void SaveAssembly(AssemblyBuilder assemblyBuilder) { assemblyBuilder.Save(AssemblyFileName); }
internal CodegenUnit(AssemblyName asmName) { var fileName = asmName.Name + ".dll"; var pdbName = asmName + ".pdb"; // so that we can run multiple tests at once and not lose the info if (UnitTest.CurrentTest != null) { fileName = asmName + ", " + UnitTest.PersistentId + ".dll"; pdbName = asmName + ".pdb"; } #if TRACE try { _asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); _mod = _asm.DefineDynamicModule(fileName, true); // Mark generated code as debuggable. // See http://blogs.msdn.com/jmstall/archive/2005/02/03/366429.aspx for explanation. var daCtor = typeof(DebuggableAttribute).GetConstructor(new []{typeof(DebuggableAttribute.DebuggingModes)}); var daBuilder = new CustomAttributeBuilder(daCtor, new object[] { DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.Default }); _asm.SetCustomAttribute(daBuilder); // Mark generated code as non-user code. // See http://stackoverflow.com/questions/1423733/how-to-tell-if-a-net-assembly-is-dynamic for explanation. var cgCtor = typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes); var cgBuilder = new CustomAttributeBuilder(cgCtor, new object []{}); _asm.SetCustomAttribute(cgBuilder); var hasAlreadyBeenDumped = false; Action dumpAssembly = () => { if (!hasAlreadyBeenDumped && _asm != null) { try { // todo. before dumping make sure that all types are completed or else the dump will simply crash // this is a complex task, but it needs to be resolved for generic case _asm.Save(fileName); } catch (Exception ex) { var trace = String.Format("Codegen unit '{0}' has failed to dump the asm:{1}{2}", asmName.FullName, Environment.NewLine, ex); Log.WriteLine(trace); SafetyTools.SafeDo(() => { File.WriteAllText(fileName, trace); File.Delete(pdbName); }); } finally { hasAlreadyBeenDumped = true; } } }; _dumpAssembly = dumpAssembly; // do not use DomainUnload here because it never gets fired for default domain // however, we need not to neglect because R#'s unit-test runner never exits process AppDomain.CurrentDomain.DomainUnload += (o, e) => dumpAssembly(); AppDomain.CurrentDomain.ProcessExit += (o, e) => dumpAssembly(); AppDomain.CurrentDomain.UnhandledException += (o, e) => dumpAssembly(); } catch (Exception ex) { var trace = String.Format("Codegen unit '{0}' has failed to initialize:{1}{2}", asmName.FullName, Environment.NewLine, ex); Log.WriteLine(trace); SafetyTools.SafeDo(() => { File.WriteAllText(fileName, trace); File.Delete(pdbName); }); throw; } #else _asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); _asm.SetCustomAttribute(new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), new object[] { })); _mod = _asm.DefineDynamicModule(fileName, false); #endif }
public void GenerateExe() { string AssemblyName = "TestAssembly"; string ClassName = "TestClass"; string ExeName = ClassName + ".exe"; // 获得应用程序域,用于创建程序集。 domain = Thread.GetDomain(); // 创建程序集名称。 name = new AssemblyName(); name.Name = AssemblyName; // 创建程序集。 asmbuilder = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave); // 创建模块。 modbuilder = asmbuilder.DefineDynamicModule(ExeName); // 创建类型。 typbuilder = modbuilder.DefineType(ClassName); // 创建全局变量(类的静态变量) fld = typbuilder.DefineField("haha", typeof(int), FieldAttributes.Static); // 创建静态方法Add:public static int Add(int,int) addBuilder = typbuilder.DefineMethod("Add", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) }); // 创建静态方法Add:public static int Fact(int) factBuilder = typbuilder.DefineMethod("Fact", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int) }); // 创建静态方法Main:public static void Main(string[]) mainBuilder = typbuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { typeof(string[]) }); // Add方法的代码生成器 iladd = addBuilder.GetILGenerator(); // 产生Add方法的代码 GenerateCodeForAdd(); // Fact方法的代码生成器 ilfact = factBuilder.GetILGenerator(); // 产生Fact方法的代码 GenerateCodeForFact(); // Main方法的代码生成器 ilmain = mainBuilder.GetILGenerator(); // 产生Main方法的代码。 GenerateCodeForMain(); // 类里所有东西都已经定义好了,现在要创建这个类。 typbuilder.CreateType(); // 设置入口点。 asmbuilder.SetEntryPoint((modbuilder.GetType(ClassName)).GetMethod("Main")); // 保存到EXE文件。 asmbuilder.Save(ExeName); }
public void Save(AssemblyBuilder assemblyBuilder) { #if DEBUG_PROXY_OUTPUT assemblyBuilder.Save("generatedAssembly.dll"); #endif }
private void InitializeCompiler() { lock (_barrier) { if (_asm == null) { try { #if TRACE _asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(Vault.GetAssemblyName()), AssemblyBuilderAccess.RunAndSave); _mod = _asm.DefineDynamicModule(Vault.GetAssemblyName() + ".dll", true); // do not use DomainUnload here because it never gets fired for default domain AppDomain.CurrentDomain.ProcessExit += (o, e) => { try { if (_asm != null) { _asm.Save(_asm.GetName().Name + ".dll"); } } catch(Exception ex) { MTLog.Say("Asm dumper has faced an unexpected exception: " + ex); } }; #else _asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(Vault.GetClassName()), AssemblyBuilderAccess.Run); _mod = _asm.DefineDynamicModule(Vault.GetClassName() + ".dll", false); #endif _asm.SetCustomAttribute(new CustomAttributeBuilder( typeof(GuidAttribute).GetConstructors().Single(), Vault.Id.ToString().MkArray())); } catch (Exception ex) { MTLog.Say("Compiler initialization failed: " + ex); _isPermanentlyBroken = true; } } } GetCompiledAsync(); }
private string SaveAssemblyBuilder(System.Runtime.InteropServices.ComTypes.ITypeLib typeLib, AssemblyBuilder asmBldr, string rcwName) { string assem = null; FileInfo info = new FileInfo(rcwName); string name = info.Name; if (info.Exists) { if (!this.options.overwriteRCW) { goto Label_00D2; } if ((this.typeLibName != null) && string.Equals(this.typeLibName, info.FullName, StringComparison.OrdinalIgnoreCase)) { throw new Exception(System.Design.SR.GetString("AXCannotOverwriteFile", new object[] { info.FullName })); } if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { throw new Exception(System.Design.SR.GetString("AXReadOnlyFile", new object[] { info.FullName })); } try { info.Delete(); asmBldr.Save(name); goto Label_00D2; } catch (Exception) { throw new Exception(System.Design.SR.GetString("AXCannotOverwriteFile", new object[] { info.FullName })); } } asmBldr.Save(name); Label_00D2: assem = info.FullName; this.AddReferencedAssembly(assem); this.AddTypeLibAttr(typeLib); this.AddGeneratedAssembly(assem); return assem; }
[Test] // DefineVersionInfoResource (String, String, String, String, String) public void TestDefineVersionInfoResource2_Culture_NotSupported () { AssemblyName aname = new AssemblyName (); aname.CultureInfo = new CultureInfo ("nl-BE"); aname.Name = "lib"; aname.Version = new Version (3, 5, 7); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly ( aname, AssemblyBuilderAccess.RunAndSave, tempDir); // AssemblyCulture Type attrType = typeof (AssemblyCultureAttribute); ConstructorInfo ci = attrType.GetConstructor (new Type [] { typeof (String) }); CustomAttributeBuilder cab = new CustomAttributeBuilder ( ci, new object [1] { "doesnotexist" }); ab.SetCustomAttribute (cab); ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E"); try { ab.Save ("lib.dll"); Assert.Fail ("#A1"); } catch (ArgumentException ex) { // Culture name doesnotexist is not supported Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); Assert.IsTrue (ex.Message.IndexOf ("doesnotexist") != -1, "#A5"); Assert.AreEqual ("name", ex.ParamName, "#A6"); } ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.RunAndSave, tempDir); // AssemblyCulture attrType = typeof (AssemblyCultureAttribute); ci = attrType.GetConstructor (new Type [] { typeof (String) }); cab = new CustomAttributeBuilder (ci, new object [1] { "neutral" }); ab.SetCustomAttribute (cab); ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E"); try { ab.Save ("lib.dll"); Assert.Fail ("#B1"); } catch (ArgumentException ex) { // Culture name neutral is not supported Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); Assert.IsTrue (ex.Message.IndexOf ("neutral") != -1, "#B5"); Assert.AreEqual ("name", ex.ParamName, "#B6"); } }
public static void SaveILCodeI386Required32BitPortable(AssemblyBuilder assemblyBuilder, string assemblyFileName) { assemblyBuilder.Save(assemblyFileName, PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly, ImageFileMachine.I386); }
public static void Main() { // An assembly consists of one or more modules, each of which // contains zero or more types. This code creates a single-module // assembly, the most common case. The module contains one type, // named "MyDynamicType", that has a private field, a property // that gets and sets the private field, constructors that // initialize the private field, and a method that multiplies // a user-supplied number by the private field value and returns // the result. In C# the type might look like this: /* * public class MyDynamicType * { * private int m_number; * * public MyDynamicType() : this(42) {} * public MyDynamicType(int initNumber) * { * m_number = initNumber; * } * * public int Number * { * get { return m_number; } * set { m_number = value; } * } * * public int MyMethod(int multiplier) * { * return m_number * multiplier; * } * } */ AssemblyName aName = new AssemblyName("DynamicAssemblyExample"); System.Reflection.Emit.AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly( aName, AssemblyBuilderAccess.RunAndSave); // For a single-module assembly, the module name is usually // the assembly name plus an extension. ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll"); TypeBuilder tb = mb.DefineType( "MyDynamicType", TypeAttributes.Public); // Add a private field of type int (Int32). FieldBuilder fbNumber = tb.DefineField( "m_number", typeof(int), FieldAttributes.Private); // Define a constructor that takes an integer argument and // stores it in the private field. Type[] parameterTypes = { typeof(int) }; ConstructorBuilder ctor1 = tb.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, parameterTypes); ILGenerator ctor1IL = ctor1.GetILGenerator(); // For a constructor, argument zero is a reference to the new // instance. Push it on the stack before calling the base // class constructor. Specify the default constructor of the // base class (System.Object) by passing an empty array of // types (Type.EmptyTypes) to GetConstructor. ctor1IL.Emit(OpCodes.Ldarg_0); ctor1IL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); // Push the instance on the stack before pushing the argument // that is to be assigned to the private field m_number. ctor1IL.Emit(OpCodes.Ldarg_0); ctor1IL.Emit(OpCodes.Ldarg_1); ctor1IL.Emit(OpCodes.Stfld, fbNumber); ctor1IL.Emit(OpCodes.Ret); // Define a default constructor that supplies a default value // for the private field. For parameter types, pass the empty // array of types or pass null. ConstructorBuilder ctor0 = tb.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); ILGenerator ctor0IL = ctor0.GetILGenerator(); // For a constructor, argument zero is a reference to the new // instance. Push it on the stack before pushing the default // value on the stack, then call constructor ctor1. ctor0IL.Emit(OpCodes.Ldarg_0); ctor0IL.Emit(OpCodes.Ldc_I4_S, 42); ctor0IL.Emit(OpCodes.Call, ctor1); ctor0IL.Emit(OpCodes.Ret); // Define a property named Number that gets and sets the private // field. // // The last argument of DefineProperty is null, because the // property has no parameters. (If you don't specify null, you must // specify an array of Type objects. For a parameterless property, // use the built-in array with no elements: Type.EmptyTypes) PropertyBuilder pbNumber = tb.DefineProperty( "Number", PropertyAttributes.HasDefault, typeof(int), null); // The property "set" and property "get" methods require a special // set of attributes. MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig; // Define the "get" accessor method for Number. The method returns // an integer and has no arguments. (Note that null could be // used instead of Types.EmptyTypes) MethodBuilder mbNumberGetAccessor = tb.DefineMethod( "get_Number", getSetAttr, typeof(int), Type.EmptyTypes); ILGenerator numberGetIL = mbNumberGetAccessor.GetILGenerator(); // For an instance property, argument zero is the instance. Load the // instance, then load the private field and return, leaving the // field value on the stack. numberGetIL.Emit(OpCodes.Ldarg_0); numberGetIL.Emit(OpCodes.Ldfld, fbNumber); numberGetIL.Emit(OpCodes.Ret); // Define the "set" accessor method for Number, which has no return // type and takes one argument of type int (Int32). MethodBuilder mbNumberSetAccessor = tb.DefineMethod( "set_Number", getSetAttr, null, new Type[] { typeof(int) }); ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator(); // Load the instance and then the numeric argument, then store the // argument in the field. numberSetIL.Emit(OpCodes.Ldarg_0); numberSetIL.Emit(OpCodes.Ldarg_1); numberSetIL.Emit(OpCodes.Stfld, fbNumber); numberSetIL.Emit(OpCodes.Ret); // Last, map the "get" and "set" accessor methods to the // PropertyBuilder. The property is now complete. pbNumber.SetGetMethod(mbNumberGetAccessor); pbNumber.SetSetMethod(mbNumberSetAccessor); // Define a method that accepts an integer argument and returns // the product of that integer and the private field m_number. This // time, the array of parameter types is created on the fly. MethodBuilder meth = tb.DefineMethod( "MyMethod", MethodAttributes.Public, typeof(int), new Type[] { typeof(int) }); ILGenerator methIL = meth.GetILGenerator(); // To retrieve the private instance field, load the instance it // belongs to (argument zero). After loading the field, load the // argument one and then multiply. Return from the method with // the return value (the product of the two numbers) on the // execution stack. methIL.Emit(OpCodes.Ldarg_0); methIL.Emit(OpCodes.Ldfld, fbNumber); methIL.Emit(OpCodes.Ldarg_1); methIL.Emit(OpCodes.Mul); methIL.Emit(OpCodes.Ret); // Finish the type. Type t = tb.CreateType(); // The following line saves the single-module assembly. This // requires AssemblyBuilderAccess to include Save. You can now // type "ildasm MyDynamicAsm.dll" at the command prompt, and // examine the assembly. You can also write a program that has // a reference to the assembly, and use the MyDynamicType type. // ab.Save(aName.Name + ".dll"); // Because AssemblyBuilderAccess includes Run, the code can be // executed immediately. Start by getting reflection objects for // the method and the property. MethodInfo mi = t.GetMethod("MyMethod"); PropertyInfo pi = t.GetProperty("Number"); // Create an instance of MyDynamicType using the default // constructor. object o1 = Activator.CreateInstance(t); // Display the value of the property, then change it to 127 and // display it again. Use null to indicate that the property // has no index. Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null)); pi.SetValue(o1, 127, null); Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null)); // Call MyMethod, passing 22, and display the return value, 22 // times 127. Arguments must be passed as an array, even when // there is only one. object[] arguments = { 22 }; Console.WriteLine("o1.MyMethod(22): {0}", mi.Invoke(o1, arguments)); // Create an instance of MyDynamicType using the constructor // that specifies m_Number. The constructor is identified by // matching the types in the argument array. In this case, // the argument array is created on the fly. Display the // property value. object o2 = Activator.CreateInstance(t, new object[] { 5280 }); Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, null)); }
private List<IGeneratedType> LoadFromDisk(AssemblyBuilder assemblyBuilder, List<IGeneratedType> generatedTypes) { assemblyBuilder.Save(this.assemblyName); var assembly = Assembly.LoadFrom(this.assemblyName); var conversion = assembly.GetTypes().ToDictionary(x => x.FullName, x => x); var generatedConvertedTypes = new List<IGeneratedType>(generatedTypes.Count); foreach (var generatedType in generatedTypes) { var fromDiskType = new GeneratedType( generatedType.Name, conversion[generatedType.Name], generatedType.TypeDescription); generatedConvertedTypes.Add(fromDiskType); } return generatedConvertedTypes; }