private static AssemblyDefinition CreateTestAssembly() { var name = new AssemblyNameDefinition("TestArithmeticOperatorTurtleAdd", new Version(1, 0)); var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll); var type = new TypeDefinition("TestArithmeticOperatorTurtleAdd", "TestClass", TypeAttributes.Class | TypeAttributes.Public); var intType = assembly.MainModule.Import(typeof(int)); var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType); var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType); var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType); method.Parameters.Add(leftParam); method.Parameters.Add(rightParam); var resultVariable = new VariableDefinition(intType); method.Body.Variables.Add(resultVariable); var processor = method.Body.GetILProcessor(); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_1)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_2)); method.Body.Instructions.Add(processor.Create(OpCodes.Add)); method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldloc, resultVariable)); method.Body.Instructions.Add(processor.Create(OpCodes.Ret)); type.Methods.Add(method); assembly.MainModule.Types.Add(type); return assembly; }
public Emitter(Compiler compiler) { Compiler = compiler; // create assembly object var name = new AssemblyNameDefinition("MirelleCompiled", new Version(1, 0, 0, 0)); Assembly = AssemblyDefinition.CreateAssembly(name, "MirelleCompiled", ModuleKind.Console); var attr = typeof(STAThreadAttribute).GetConstructor(new Type[] { } ); // register global method GlobalBody = new MethodDefinition("main", MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig, Assembly.MainModule.TypeSystem.Void); GlobalBody.CustomAttributes.Add(new CustomAttribute(AssemblyImport(attr))); RootNode.GlobalMethod = new MethodNode("main", new SignatureNode("void"), true, false, GlobalBody); RootNode.GlobalMethod.Scope = new Utils.Scope(GlobalBody); // register global type GlobalType = new TypeDefinition("MirelleCompiled", ".program", TypeAttributes.AutoClass | TypeAttributes.Public | TypeAttributes.SpecialName | TypeAttributes.BeforeFieldInit, Assembly.MainModule.TypeSystem.Object); Assembly.MainModule.Types.Add(GlobalType); GlobalType.Methods.Add(GlobalBody); Assembly.EntryPoint = GlobalBody; // register marker interfaces MirelleTypeInterface = AssemblyImport(typeof(MirelleStdlib.IMirelleType)); MirelleEnumInterface = AssemblyImport(typeof(MirelleStdlib.IMirelleEnum)); }
private static AssemblyDefinition CreateTestAssembly(OpCode opCode, bool invert) { var name = new AssemblyNameDefinition("TestConditionalsBoundaryTurtle", new Version(1, 0)); var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll); var type = new TypeDefinition("TestConditionalsBoundaryTurtle", "TestClass", TypeAttributes.Class | TypeAttributes.Public); var intType = assembly.MainModule.Import(typeof(int)); var boolType = assembly.MainModule.Import(typeof(bool)); var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType); var param = new ParameterDefinition("input", ParameterAttributes.In, intType); method.Parameters.Add(param); var resultVariable = new VariableDefinition(boolType); method.Body.Variables.Add(resultVariable); var processor = method.Body.GetILProcessor(); Instruction loadReturnValueInstruction = processor.Create(OpCodes.Ldloc, resultVariable); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, param)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0)); method.Body.Instructions.Add(processor.Create(opCode)); if (invert) { method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0)); method.Body.Instructions.Add(processor.Create(OpCodes.Ceq)); } method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable)); method.Body.Instructions.Add(loadReturnValueInstruction); method.Body.Instructions.Add(processor.Create(OpCodes.Ret)); type.Methods.Add(method); assembly.MainModule.Types.Add(type); return assembly; }
private static AssemblyDefinition CreateTestAssembly() { var name = new AssemblyNameDefinition("TestBranchConditionTurtle", new Version(1, 0)); var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll); var type = new TypeDefinition("TestBranchConditionTurtle", "TestClass", TypeAttributes.Class | TypeAttributes.Public); var intType = assembly.MainModule.Import(typeof(int)); var boolType = assembly.MainModule.Import(typeof(bool)); var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType); var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType); var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType); method.Parameters.Add(leftParam); method.Parameters.Add(rightParam); var resultVariable = new VariableDefinition(boolType); method.Body.Variables.Add(resultVariable); var processor = method.Body.GetILProcessor(); Instruction loadReturnValueInstruction = processor.Create(OpCodes.Ldloc, resultVariable); Instruction storeTrueInReturnValueInstruction = processor.Create(OpCodes.Ldc_I4, -1); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, leftParam)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, rightParam)); method.Body.Instructions.Add(processor.Create(OpCodes.Ceq)); method.Body.Instructions.Add(processor.Create(OpCodes.Brtrue_S, storeTrueInReturnValueInstruction)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0)); method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable)); method.Body.Instructions.Add(processor.Create(OpCodes.Br_S, loadReturnValueInstruction)); method.Body.Instructions.Add(storeTrueInReturnValueInstruction); method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable)); method.Body.Instructions.Add(loadReturnValueInstruction); method.Body.Instructions.Add(processor.Create(OpCodes.Ret)); type.Methods.Add(method); assembly.MainModule.Types.Add(type); return assembly; }
public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind) { return(AssemblyDefinition.CreateAssembly(assemblyName, moduleName, new ModuleParameters() { Kind = kind })); }
public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind) { ModuleParameters parameters = new ModuleParameters { Kind = kind }; return(CreateAssembly(assemblyName, moduleName, parameters)); }
internal AssemblyDefinition(AssemblyNameDefinition name) { if (name == null) throw new ArgumentNullException ("name"); m_asmName = name; m_modules = new ModuleDefinitionCollection (this); }
private void CreateAssemblyDefinition(String sAssemblyName, ModuleKind akAssemblyKind) { assemblyName = sAssemblyName; assemblyKind = akAssemblyKind; //assemblyDefinition = AssemblyDefinition.CreateAssembly(sAssemblyName, TargetRuntime.NET_2_0, akAssemblyKind); var assemblyNameDefinition = new AssemblyNameDefinition(sAssemblyName, new Version(0, 0, 0, 0)); assemblyDefinition = AssemblyDefinition.CreateAssembly(assemblyNameDefinition, sAssemblyName, akAssemblyKind); mainModule = assemblyDefinition.MainModule; }
public static void WriteModuleTo(ModuleDefinition module, Stream stream, WriterParameters parameters) { AssemblyNameDefinition name; if ((int)(module.Attributes & ModuleAttributes.ILOnly) == 0) { throw new NotSupportedException("Writing mixed-mode assemblies is not supported"); } if (module.HasImage && module.ReadingMode == ReadingMode.Deferred) { ImmediateModuleReader.ReadModule(module); } module.MetadataSystem.Clear(); if (module.assembly != null) { name = module.assembly.Name; } else { name = null; } AssemblyNameDefinition publicKey = name; string fullyQualifiedName = stream.GetFullyQualifiedName(); ISymbolWriterProvider symbolWriterProvider = parameters.SymbolWriterProvider; if (symbolWriterProvider == null && parameters.WriteSymbols) { symbolWriterProvider = SymbolProvider.GetPlatformWriterProvider(); } ISymbolWriter symbolWriter = ModuleWriter.GetSymbolWriter(module, fullyQualifiedName, symbolWriterProvider); if (parameters.StrongNameKeyPair != null && publicKey != null) { publicKey.PublicKey = parameters.StrongNameKeyPair.PublicKey; ModuleDefinition attributes = module; attributes.Attributes = attributes.Attributes | ModuleAttributes.StrongNameSigned; } MetadataBuilder metadataBuilder = new MetadataBuilder(module, fullyQualifiedName, symbolWriterProvider, symbolWriter); ModuleWriter.BuildMetadata(module, metadataBuilder); if (module.symbol_reader != null) { module.symbol_reader.Dispose(); } ImageWriter imageWriter = ImageWriter.CreateWriter(module, metadataBuilder, stream); imageWriter.WriteImage(); if (parameters.StrongNameKeyPair != null) { CryptoService.StrongName(stream, imageWriter, parameters.StrongNameKeyPair); } if (symbolWriter != null) { symbolWriter.Dispose(); } }
internal AssemblyDefinition(AssemblyNameDefinition name) { if (name == null) { throw new ArgumentNullException("name"); } m_asmName = name; m_modules = new ModuleDefinitionCollection(this); }
public static AssemblyDefinition DefineAssembly(string assemblyName, string moduleName, TargetRuntime rt, AssemblyKind kind) { AssemblyNameDefinition asmName = new AssemblyNameDefinition (); asmName.Name = assemblyName; AssemblyDefinition asm = new AssemblyDefinition (asmName); asm.Runtime = rt; asm.Kind = kind; ModuleDefinition main = new ModuleDefinition (moduleName, asm, true); asm.Modules.Add (main); return asm; }
public void SetUp() { AssemblyNameDefinition name = new AssemblyNameDefinition($"_{Guid.NewGuid()}", new Version(1, 0)); AssemblyDefinition assembly = AssemblyDefinition.CreateAssembly(name, name.Name, ModuleKind.Dll); TestModule = ModuleDefinition.CreateModule(name.Name, ModuleKind.Dll); assembly.Modules.Add(TestModule); foreach (var asm in this.GetType().Assembly.GetReferencedAssemblies()) assembly.MainModule.AssemblyReferences.Add(new AssemblyNameDefinition(asm.FullName, asm.Version)); TestType = new TypeDefinition("", $"_{Guid.NewGuid()}", TypeAttributes.Class | TypeAttributes.Public, TestModule.Import(typeof(object))); TestModule.Types.Add(TestType); AddEmptyConstructor(); }
public static AssemblyDefinition DefineAssembly(string assemblyName, string moduleName, TargetRuntime rt, AssemblyKind kind) { AssemblyNameDefinition asmName = new AssemblyNameDefinition(); asmName.Name = assemblyName; AssemblyDefinition asm = new AssemblyDefinition(asmName); asm.Runtime = rt; asm.Kind = kind; ModuleDefinition main = new ModuleDefinition(moduleName, asm, true); asm.Modules.Add(main); return(asm); }
public static string GetPublicTokenKeyString(this AssemblyNameDefinition definition) { var builder = new StringBuilder(); if (definition.PublicKeyToken != null && definition.PublicKeyToken.Length > 0) { foreach (var b in definition.PublicKeyToken) { builder.Append(Utils.PKeyTokenHex[b / 16 & Utils.PKeyTokenMask]); builder.Append(Utils.PKeyTokenHex[b & Utils.PKeyTokenMask]); } } return((builder.Length > 0) ? builder.ToString() : "null"); }
public override void VisitAssemblyNameDefinition(AssemblyNameDefinition name) { AssemblyTable atable = m_tableReader.GetAssemblyTable(); AssemblyRow arow = atable [0]; name.Name = ReadString(arow.Name); name.Flags = arow.Flags; name.PublicKey = ReadBlob(arow.PublicKey); name.Culture = ReadString(arow.Culture); name.Version = new Version( arow.MajorVersion, arow.MinorVersion, arow.BuildNumber, arow.RevisionNumber); name.HashAlgorithm = arow.HashAlgId; name.MetadataToken = new MetadataToken(TokenType.Assembly, 1); }
public void CanAddNewMethodToType() { var assemblyName = new AssemblyNameDefinition("TempAssembly", new Version(1, 0)); var assembly = AssemblyDefinition.CreateAssembly(assemblyName, "TempModule", ModuleKind.Dll); var typeDefinition = new TypeDefinition("TempNamespace", "TempType", TypeAttributes.Public); typeDefinition .NewMethod("TempMethod", MethodAttributes.Public, typeof(string), assembly) .Nop() .Ldstr("Ola") .Ret(); var methodDefinition = typeDefinition.Methods.First(x => x.Name == "TempMethod"); methodDefinition.Body.Instructions.Count.Should().Be.EqualTo(3); }
private void ReadAssembly(MetadataReader reader) { AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition(); if (assemblyNameDefinition == null) { module.kind = ModuleKind.NetModule; } else { AssemblyDefinition assemblyDefinition = new AssemblyDefinition(); assemblyDefinition.Name = assemblyNameDefinition; module.assembly = assemblyDefinition; assemblyDefinition.main_module = module; } }
private void ReadAssembly(MetadataReader reader) { AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition(); if (assemblyNameDefinition == null) { this.module.kind = ModuleKind.NetModule; return; } AssemblyDefinition assemblyDefinition = new AssemblyDefinition() { Name = assemblyNameDefinition }; this.module.assembly = assemblyDefinition; assemblyDefinition.main_module = this.module; }
private void ReadAssembly(MetadataReader reader) { AssemblyNameDefinition definition = reader.ReadAssemblyNameDefinition(); if (definition == null) { this.module.kind = ModuleKind.NetModule; } else { AssemblyDefinition definition2 = new AssemblyDefinition { Name = definition }; this.module.assembly = definition2; definition2.main_module = this.module; } }
public static void WriteModuleTo(ModuleDefinition module, Stream stream, WriterParameters parameters) { if ((module.Attributes & ModuleAttributes.ILOnly) == 0) { throw new NotSupportedException("Writing mixed-mode assemblies is not supported"); } if (module.HasImage && (module.ReadingMode == ReadingMode.Deferred)) { ImmediateModuleReader.ReadModule(module); } module.MetadataSystem.Clear(); AssemblyNameDefinition name = module.assembly?.Name; string fullyQualifiedName = stream.GetFullyQualifiedName(); ISymbolWriterProvider symbolWriterProvider = parameters.SymbolWriterProvider; if ((symbolWriterProvider == null) && parameters.WriteSymbols) { symbolWriterProvider = SymbolProvider.GetPlatformWriterProvider(); } ISymbolWriter writer = GetSymbolWriter(module, fullyQualifiedName, symbolWriterProvider); if ((parameters.StrongNameKeyPair != null) && (name != null)) { name.PublicKey = parameters.StrongNameKeyPair.PublicKey; module.Attributes |= ModuleAttributes.StrongNameSigned; } MetadataBuilder metadata = new MetadataBuilder(module, fullyQualifiedName, symbolWriterProvider, writer); BuildMetadata(module, metadata); if (module.symbol_reader != null) { module.symbol_reader.Dispose(); } ImageWriter writer2 = ImageWriter.CreateWriter(module, metadata, stream); writer2.WriteImage(); if (parameters.StrongNameKeyPair != null) { CryptoService.StrongName(stream, writer2, parameters.StrongNameKeyPair); } if (writer != null) { writer.Dispose(); } }
private static AssemblyDefinition CreateTestAssembly() { var name = new AssemblyNameDefinition("TestBranchConditionTurtle", new Version(1, 0)); var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll); var type = new TypeDefinition("TestBranchConditionTurtle", "TestClass", Mono.Cecil.TypeAttributes.Class | Mono.Cecil.TypeAttributes.Public); var intType = assembly.MainModule.Import(typeof(int)); var boolType = assembly.MainModule.Import(typeof(bool)); var method = new MethodDefinition("TestMethod", Mono.Cecil.MethodAttributes.Public, intType); var dispose = new MethodDefinition("Dispose", Mono.Cecil.MethodAttributes.Public, boolType); var variable1 = new VariableDefinition(intType); var variable2 = new VariableDefinition(intType); var resultVariable = new VariableDefinition(intType); method.Body.Variables.Add(variable1); method.Body.Variables.Add(variable2); method.Body.Variables.Add(resultVariable); var processor = method.Body.GetILProcessor(); var finalNop = processor.Create(OpCodes.Nop); method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0)); method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, variable2)); method.Body.Instructions.Add(processor.Create(OpCodes.Nop)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 7)); _mutatedInstruction = processor.Create(OpCodes.Stloc, variable1); method.Body.Instructions.Add(_mutatedInstruction); method.Body.Instructions.Add(processor.Create(OpCodes.Nop)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 8)); method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, variable2)); method.Body.Instructions.Add(processor.Create(OpCodes.Leave, finalNop)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_0)); method.Body.Instructions.Add(processor.Create(OpCodes.Call, dispose)); method.Body.Instructions.Add(processor.Create(OpCodes.Nop)); method.Body.Instructions.Add(processor.Create(OpCodes.Endfinally)); method.Body.Instructions.Add(finalNop); method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, -1)); method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldloc, resultVariable)); method.Body.Instructions.Add(processor.Create(OpCodes.Ret)); type.Methods.Add(method); type.Methods.Add(dispose); assembly.MainModule.Types.Add(type); return assembly; }
private static void Write(ModuleDefinition module, Disposable <Stream> stream, WriterParameters parameters) { if ((module.Attributes & ModuleAttributes.ILOnly) == (ModuleAttributes)0) { throw new NotSupportedException("Writing mixed-mode assemblies is not supported"); } if (module.HasImage && module.ReadingMode == ReadingMode.Deferred) { ImmediateModuleReader immediateModuleReader = new ImmediateModuleReader(module.Image); immediateModuleReader.ReadModule(module, false); immediateModuleReader.ReadSymbols(module); } module.MetadataSystem.Clear(); if (module.symbol_reader != null) { module.symbol_reader.Dispose(); } AssemblyNameDefinition assemblyNameDefinition = (module.assembly != null) ? module.assembly.Name : null; string fileName = stream.value.GetFileName(); uint timestamp = parameters.Timestamp ?? module.timestamp; ISymbolWriterProvider symbolWriterProvider = parameters.SymbolWriterProvider; if (symbolWriterProvider == null && parameters.WriteSymbols) { symbolWriterProvider = new DefaultSymbolWriterProvider(); } if (parameters.StrongNameKeyPair != null && assemblyNameDefinition != null) { assemblyNameDefinition.PublicKey = parameters.StrongNameKeyPair.PublicKey; module.Attributes |= ModuleAttributes.StrongNameSigned; } using (ISymbolWriter symbol_writer = GetSymbolWriter(module, fileName, symbolWriterProvider, parameters)) { MetadataBuilder metadata = new MetadataBuilder(module, fileName, timestamp, symbolWriterProvider, symbol_writer); BuildMetadata(module, metadata); ImageWriter imageWriter = ImageWriter.CreateWriter(module, metadata, stream); stream.value.SetLength(0L); imageWriter.WriteImage(); if (parameters.StrongNameKeyPair != null) { CryptoService.StrongName(stream.value, imageWriter, parameters.StrongNameKeyPair); } } }
public void Init(string fileName = "MathFuncLib.dll") { var name = new AssemblyNameDefinition(Path.GetFileNameWithoutExtension(fileName), new Version(1, 0, 0, 0)); Assembly = AssemblyDefinition.CreateAssembly(name, fileName, ModuleKind.Dll); ImportMath(Assembly); InvokeFuncRef = Assembly.MainModule.Import(typeof(Func<double, double>).GetMethod("Invoke")); DoubleType = Assembly.MainModule.TypeSystem.Double; Class = new TypeDefinition(NamespaceName, ClassName, TypeAttributes.Public | TypeAttributes.BeforeFieldInit | TypeAttributes.Serializable | TypeAttributes.AnsiClass, Assembly.MainModule.TypeSystem.Object); var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; var method = new MethodDefinition(".ctor", methodAttributes, Assembly.MainModule.TypeSystem.Void); method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, Assembly.MainModule.Import(typeof(object).GetConstructor(new Type[0])))); method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); Class.Methods.Add(method); }
public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } Mixin.CheckParameters(parameters); if (parameters.Kind == ModuleKind.NetModule) { throw new ArgumentException("kind"); } AssemblyDefinition assembly = ModuleDefinition.CreateModule(moduleName, parameters).Assembly; assembly.Name = assemblyName; return(assembly); }
public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } if (kind == ModuleKind.NetModule) { throw new ArgumentException("kind"); } var assembly = ModuleDefinition.CreateModule(moduleName, kind).Assembly; assembly.Name = assemblyName; return(assembly); }
public override void VisitAssemblyNameDefinition(AssemblyNameDefinition name) { AssemblyTable asmTable = m_tableWriter.GetAssemblyTable(); if (name.PublicKey != null && name.PublicKey.Length > 0) { name.Flags |= AssemblyFlags.PublicKey; } AssemblyRow asmRow = m_rowWriter.CreateAssemblyRow( name.HashAlgorithm, (ushort)name.Version.Major, (ushort)name.Version.Minor, (ushort)name.Version.Build, (ushort)name.Version.Revision, name.Flags, m_mdWriter.AddBlob(name.PublicKey), m_mdWriter.AddString(name.Name), m_mdWriter.AddString(name.Culture)); asmTable.Rows.Add(asmRow); }
internal AssemblyDefinition(AssemblyNameDefinition name, StructureReader reader) : this(name) { m_reader = reader; }
/// <summary> /// Replaces the public key of the current assembly by the key from the specified name. /// </summary> /// <param name="modelName">The name of the assembly containing the public key which should be copied to this assembly.</param> private void ReplacePublicKey(AssemblyNameDefinition modelName) { Contract.Requires(modelName != null); var name = this.underlyingAssembly.Value.Name; name.HasPublicKey = modelName.HasPublicKey; name.PublicKey = modelName.PublicKey; name.PublicKeyToken = modelName.PublicKeyToken; }
private void GenerateModuleAssembly() { #region GetVersion Version ver = BusinessBuilder.GetVersion(AdmiralEnvironment.UserDefineBusinessFile); if (ver != null) { ver = new Version(ver.Major + 1, ver.Minor, ver.Build, ver.Revision); } else { ver = new Version(1, 0, 0, 0); } #endregion var assemblyName = "AdmiralDynamicDC"; var newFileName = AdmiralEnvironment.UserDefineBusinessTempFile.FullName; #region 定义程序集 var asmName = new AssemblyNameDefinition(assemblyName, ver); //[assembly: AssemblyFileVersionAttribute("1.0.0.12")] var assembly = AssemblyDefinition.CreateAssembly( asmName, "MainModule", ModuleKind.Dll ); //AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save, AdmiralEnvironment.UserDefineBusinessDirectoryInfo.FullName); #region 定义模块 var module = assembly.MainModule; #endregion #endregion #region 设置文件版本 var asmFileVerCtor = typeof(SR.AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); var asmFileVerCtorRef = assembly.MainModule.ImportReference(asmFileVerCtor); var ca = new Mono.Cecil.CustomAttribute(asmFileVerCtorRef); ca.ConstructorArguments.Add(new CustomAttributeArgument( assembly.MainModule.ImportReference(typeof(string)), ver.ToString())); assembly.CustomAttributes.Add(ca); #endregion #region XafModule var xafModule = new TypeDefinition("", "RuntimeModule", TypeAttributes.Public | TypeAttributes.Class, assembly.MainModule.ImportReference(typeof(RuntimeModuleBase))); //module.DefineType("RuntimeModule", TypeAttributes.Public | TypeAttributes.Class, typeof(RuntimeModuleBase)); var ctor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, module.ImportReference(typeof(void)) ); //.method public hidebysig specialname rtspecialname instance void .ctor() cil managed //xafModule.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis, Type.EmptyTypes); var baseCtor = typeof(RuntimeModuleBase).GetConstructor(Type.EmptyTypes); var il = ctor.Body.Instructions; //.maxstack 8 //L_0000: ldarg.0 //L_0001: call instance void Admiral.ERP.Module.RuntimeModuleBase::.ctor() //L_0006: ret il.Add(Instruction.Create(OpCodes.Ldarg_0)); il.Add(Instruction.Create(OpCodes.Call, module.ImportReference(baseCtor))); il.Add(Instruction.Create(OpCodes.Ret)); xafModule.Methods.Add(ctor); module.Types.Add(xafModule); #endregion #region 创建业务对象 var ObjectSpace = this.Application.CreateObjectSpace(); var allTypes = ObjectSpace.GetObjects<BusinessObjectBase>(); var userDefinedBos = allTypes.OfType<BusinessObject>().Where(x => x.IsRuntimeDefine).ToList(); //ObjectSpace.GetObjects<BusinessObject>(new BinaryOperator("IsRuntimeDefine", true)).OrderBy(x => x.CreateIndex).ToArray(); var dllTypes = allTypes.Except(userDefinedBos); //ObjectSpace.GetObjects<BusinessObject>(new BinaryOperator("IsRuntimeDefine", false)); module.InitializeTypeReferences(dllTypes); //第一步只生成类型定义,是因为可能有交叉使用类型,如,基类是未定义的类型,则无法使用 #region 定义类型生成的代码,包含属性修饰:-->[NonPersistent]pubic class { } foreach (var bo in userDefinedBos) { var typeAtt = TypeAttributes.Class | TypeAttributes.Public; if (bo.IsAbstract) { typeAtt |= TypeAttributes.Abstract; } else if (!bo.CanInherits) { typeAtt |= TypeAttributes.Sealed; } var type = new TypeDefinition(bo.Category.FullName, bo.名称, typeAtt); module.Types.Add(type); if (!bo.IsPersistent) { type.AddNonPersistentDc(); } if (bo.IsCloneable.HasValue) { type.ModelDefault("IsCloneable", bo.IsCloneable.Value.ToString().ToLower() ); } if (bo.IsCreatableItem.HasValue) { type.ModelDefault("IsCreatableItem", bo.IsCreatableItem.Value.ToString().ToLower()); } if (bo.IsVisibileInReports.HasValue) { type.VisibileInReport(bo.IsVisibileInReports.Value); } type.AddToTypeReferences(bo); } #endregion #region 生成剩下的内容 foreach (var bo in userDefinedBos) { var type = bo.GetTypeDefintion(); if (type == null) throw new Exception("错误!"); #region 处理基类 var boBaseType = bo.Base.GetTypeReference() ?? module.ImportReference(typeof(SimpleObject)); MethodReference boBaseCtor; if (boBaseType.HasGenericParameters) { type.BaseType = boBaseType.MakeGenericType(bo.GenericParameters.Select(gp => gp.ParameterValue.GetTypeReference()).ToArray()); //var tb = boBaseType.Resolve().MakeGenericType(bo.GenericParameters.Select(gp => gp.ParameterValue.FindType(typeReferences)).ToArray()); boBaseCtor = //(tb as TypeDefinition).Methods.Single(x => x.Name == ".ctor" && x.Parameters.First().ParameterType.FullName == typeof(Session).FullName); module.ImportReference( type.BaseType.Resolve() .Methods.Single( x => x.Name == ".ctor" && x.Parameters.First().ParameterType.FullName == typeof(Session).FullName) ); boBaseCtor = boBaseCtor.MakeGeneric(bo.GenericParameters.Select(gp => gp.ParameterValue.GetTypeReference()).ToArray()); } else { type.BaseType = boBaseType; boBaseCtor = module.ImportReference( boBaseType.Resolve().Methods.Single(x => x.Name == ".ctor" && x.Parameters.Count == 1 && x.Parameters.Single().ParameterType.FullName == typeof(Session).FullName) ); } if (boBaseCtor != null) { var boctor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, //CallingConventions.Standard | CallingConventions.HasThis, module.ImportReference(typeof(void)) ); // type.DefineConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard | CallingConventions.HasThis, new Type[] { typeof(Session) }); var p = new ParameterDefinition("session", ParameterAttributes.None, module.ImportReference(typeof(Session))); boctor.Parameters.Add(p); var boil = boctor.Body.GetILProcessor(); //.GetILGenerator(); boil.Emit(OpCodes.Ldarg_0); boil.Emit(OpCodes.Ldarg_1); boil.Emit(OpCodes.Call, boBaseCtor); boil.Emit(OpCodes.Nop); boil.Emit(OpCodes.Nop); boil.Emit(OpCodes.Ret); //L_0000: ldarg.0 //L_0001: ldarg.1 //L_0002: call instance void IMatrix.ERP.Module.BusinessObjects.订单`1 <class IMatrix.ERP.Module.BusinessObjects.PMS.采购订单明细>::.ctor(class [DevExpress.Xpo.v15.2] //DevExpress.Xpo.Session) //L_0007: nop //L_0008: nop //L_0009: ret //.method public hidebysig specialname rtspecialname //instance void .ctor(class ['DevExpress.Xpo.v15.2']DevExpress.Xpo.Session session) cil managed //{ //// 代码大小 10 (0xa) //.maxstack 8 //IL_0000: ldarg.0 //IL_0001: ldarg.1 //IL_0002: call instance void [IMatrix.ERP.Module]IMatrix.ERP.Module.BusinessObjects.'订单`1'::.ctor<class '业务'.'采购计划明细'>(class ['DevExpress.Xpo.v15.2']DevExpress.Xpo.Session) //IL_0007: nop //IL_0008: nop //IL_0009: ret //} // end of method '采购计划'::.ctor type.Methods.Add(boctor); } #endregion #region 填加属性 foreach (var p in bo.Properties) { BuildPropertyCore(p, type); } #endregion #region 填加集合属性 foreach (var item in bo.CollectionProperties) { BuildCollectionProperty(item, type); } #endregion } #endregion #endregion #region 保存生成的程序集 assembly.Write(newFileName); #endregion #region 删除模块信息,让系统执行更新表结构动作 var moduleInfo = ObjectSpace.FindObject<ModuleInfo>(new BinaryOperator("Name", "RuntimeModule")); if (moduleInfo != null) { ObjectSpace.Delete(moduleInfo); ObjectSpace.CommitChanges(); } var restart = Application as IRestartApplication; if (restart != null) { restart.RestartApplication(); } #endregion }
static string GetIva(AssemblyNameDefinition name) { if (name.PublicKey != null) return name.Name + "," + BitConverter.ToString(name.PublicKey).Replace("-", "").ToLower(); else return name.Name; }
public override void VisitAssemblyNameDefinition (AssemblyNameDefinition name) { AssemblyTable asmTable = m_tableWriter.GetAssemblyTable (); if (name.PublicKey != null && name.PublicKey.Length > 0) name.Flags |= AssemblyFlags.PublicKey; AssemblyRow asmRow = m_rowWriter.CreateAssemblyRow ( name.HashAlgorithm, (ushort) name.Version.Major, (ushort) name.Version.Minor, (ushort) name.Version.Build, (ushort) name.Version.Revision, name.Flags, m_mdWriter.AddBlob (name.PublicKey), m_mdWriter.AddString (name.Name), m_mdWriter.AddString (name.Culture)); asmTable.Rows.Add (asmRow); }
public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters) { if (assemblyName == null) throw new ArgumentNullException ("assemblyName"); if (moduleName == null) throw new ArgumentNullException ("moduleName"); Mixin.CheckParameters (parameters); if (parameters.Kind == ModuleKind.NetModule) throw new ArgumentException ("kind"); var assembly = ModuleDefinition.CreateModule (moduleName, parameters).Assembly; assembly.Name = assemblyName; return assembly; }
//public AssemblyDefinition CopyAssembly(AssemblyDefinition sourceAssembly) //{ // if(sourceAssembly == null) // throw new ArgumentNullException("sourceAssembly"); // AssemblyDefinition copy = CloneAssemblyDefinition(sourceAssembly, "copy_" + sourceAssembly.Name.Name); // return Merge(new List<AssemblyDefinition> { sourceAssembly }, sourceAssembly, copy); //} private static AssemblyDefinition CloneAssemblyDefinition(AssemblyDefinition mainAssembly, String cloneAssemblyName) { AssemblyNameDefinition cloneName = new AssemblyNameDefinition(cloneAssemblyName, mainAssembly.Name.Version) { Attributes = mainAssembly.Name.Attributes, Culture = mainAssembly.Name.Culture, HashAlgorithm = mainAssembly.Name.HashAlgorithm, IsRetargetable = mainAssembly.Name.IsRetargetable, IsSideBySideCompatible = mainAssembly.Name.IsSideBySideCompatible, PublicKey = mainAssembly.Name.PublicKey, }; AssemblyDefinition clone = AssemblyDefinition.CreateAssembly(cloneName, mainAssembly.MainModule.Name, new ModuleParameters() { Kind = mainAssembly.MainModule.Kind, Architecture = mainAssembly.MainModule.Architecture, Runtime = mainAssembly.MainModule.Runtime, AssemblyResolver = mainAssembly.MainModule.AssemblyResolver }); return clone; }
private AssemblyNameDefinition Clone(AssemblyNameDefinition assemblyName) { AssemblyNameDefinition asmName = new AssemblyNameDefinition(assemblyName.Name, assemblyName.Version); asmName.Attributes = assemblyName.Attributes; asmName.Culture = assemblyName.Culture; asmName.Hash = assemblyName.Hash; asmName.HashAlgorithm = assemblyName.HashAlgorithm; asmName.PublicKey = assemblyName.PublicKey; asmName.PublicKeyToken = assemblyName.PublicKeyToken; return asmName; }
public override void VisitAssemblyNameDefinition (AssemblyNameDefinition name) { AssemblyTable atable = m_tableReader.GetAssemblyTable (); AssemblyRow arow = atable [0]; name.Name = ReadString (arow.Name); name.Flags = arow.Flags; name.PublicKey = ReadBlob (arow.PublicKey); name.Culture = ReadString (arow.Culture); name.Version = new Version ( arow.MajorVersion, arow.MinorVersion, arow.BuildNumber, arow.RevisionNumber); name.HashAlgorithm = arow.HashAlgId; name.MetadataToken = new MetadataToken (TokenType.Assembly, 1); }
public MethodInfo Create(OpValue[] prog) { const string OutNamespace = "BF"; const string OutTypeName = "CompiledProgram"; const string OutMethodName = "Main"; var name = new AssemblyNameDefinition(OutNamespace, new Version(1, 0, 0, 0)); var asm = AssemblyDefinition.CreateAssembly(name, OutNamespace + ".dll", ModuleKind.Dll); asm.MainModule.Import(typeof(int)); var voidret = asm.MainModule.Import(typeof(void)); var method = new MethodDefinition(OutMethodName, MethodAttributes.Static | MethodAttributes.Public, voidret); var arrayVar = new VariableDefinition("array", asm.MainModule.Import(typeof(int[]))); var indexVar = new VariableDefinition("idx", asm.MainModule.Import(typeof(int))); method.Body.Variables.Add(arrayVar); method.Body.Variables.Add(indexVar); var ip = method.Body.GetILProcessor(); ip.Emit(OpCodes.Ldc_I4_0); ip.Emit(OpCodes.Stloc, indexVar); ip.Emit(OpCodes.Ldc_I4, 300000); ip.Emit(OpCodes.Newarr, asm.MainModule.Import(typeof(int))); ip.Emit(OpCodes.Stloc, arrayVar); Dictionary<int, Instruction> braces = new Dictionary<int, Instruction>(); for (int i = 0; i < prog.Length; i++) { Emit(ip, asm.MainModule, arrayVar, indexVar, braces, prog, i); } ip.Emit(OpCodes.Ret); var type = new TypeDefinition(OutNamespace, OutTypeName, TypeAttributes.AutoClass | TypeAttributes.Public | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit, asm.MainModule.Import(typeof(object))); asm.MainModule.Types.Add(type); type.Methods.Add(method); asm.EntryPoint = method; byte[] rawAsm; using (var ms = new MemoryStream()) { asm.Write(ms); rawAsm = ms.ToArray(); } var reflected = Assembly.Load(rawAsm); return reflected.GetType(OutNamespace + "." + OutTypeName) .GetMethod(OutMethodName); }
public virtual void VisitAssemblyNameDefinition(AssemblyNameDefinition name) { }
public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind) { return CreateAssembly (assemblyName, moduleName, new ModuleParameters { Kind = kind }); }
public virtual void VisitAssemblyNameDefinition (AssemblyNameDefinition name) { }
private void UpdateReferences(AssemblyDefinition assemblyDefinition, AssemblyNameReference oldDefinition, AssemblyNameDefinition newDefinition) { var nameReference = assemblyDefinition.Modules.SelectMany (m => m.AssemblyReferences) .Select ((reference, i) => new { Index = i, Reference = reference }) .Single (tuple => tuple.Reference.MatchesDefinition (oldDefinition) || object.ReferenceEquals (tuple.Reference, newDefinition)); assemblyDefinition.MainModule.AssemblyReferences[nameReference.Index].PublicKey = newDefinition.PublicKey; assemblyDefinition.MainModule.AssemblyReferences[nameReference.Index].HasPublicKey = newDefinition.HasPublicKey; assemblyDefinition.MainModule.AssemblyReferences[nameReference.Index].PublicKeyToken = newDefinition.PublicKeyToken; assemblyDefinition.MainModule.AssemblyReferences[nameReference.Index].Version = newDefinition.Version; assemblyDefinition.MainModule.AssemblyReferences[nameReference.Index].Hash = newDefinition.Hash; assemblyDefinition.MainModule.AssemblyReferences[nameReference.Index].HashAlgorithm = newDefinition.HashAlgorithm; }
static void FixResourceReferences(AssemblyDefinition assemblyDefinition, IEnumerable<AssemblyDefinition> dependencies) { Info("Fixing resource references."); var searchAndReplace = new List<Tuple<byte[], byte[]>>(); foreach (var d in dependencies) { string newName = new AssemblyNameDefinition(d.Name.Name, d.Name.Version) { PublicKeyToken = publicKeyToken }.FullName; if (0 == publicKeyToken.Length) { newName += new string(' ', (8 * 2) - "null".Length); } string oldName = d.FullName; if (0 == d.Name.PublicKeyToken.Length) { oldName += new string(' ', (8 * 2) - "null".Length); } if (newName.Length != oldName.Length || newName == oldName) { continue; } searchAndReplace.Add( Tuple.Create(Encoding.UTF8.GetBytes(oldName), Encoding.UTF8.GetBytes(newName))); } if (0 == searchAndReplace.Count) { return; } foreach (var resource in assemblyDefinition.MainModule.Resources.ToList()) { var embeddedResource = resource as EmbeddedResource; if (embeddedResource == null || !embeddedResource.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) { continue; } using (var resourceOutput = new MemoryStream()) { using (var resourceInput = embeddedResource.GetResourceStream()) { BinaryUtility.Replace(new BinaryReader(resourceInput), new BinaryWriter(resourceOutput), searchAndReplace); assemblyDefinition.MainModule.Resources.Remove(resource); assemblyDefinition.MainModule.Resources.Add(new EmbeddedResource(embeddedResource.Name, resource.Attributes, resourceOutput.ToArray())); } } } }