// Constructor. Called from AppDomain.DefineDynamicAssembly. internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, String directory, bool isSynchronized) { this.access = access; this.directory = (directory == null) ? "." : directory; this.isSynchronized = isSynchronized; this.saved = false; this.entryPoint = null; this.detachList = new ArrayList(); fileKind = PEFileKinds.Dll; Version version = name.Version; lock(typeof(AssemblyBuilder)) { if(version != null) { this.privateData = ClrAssemblyCreate (name.Name, version.Major, version.Minor, version.Build, version.Revision, access, out writer); } else { this.privateData = ClrAssemblyCreate (name.Name, 0, 0, 0, 0, access, out writer); } } if(this.privateData == IntPtr.Zero) { // The runtime engine disallowed dynamic assemblies. throw new SecurityException (_("Emit_NoDynamicAssemblies")); } }
private static void Compile(String code, String name, PEFileKinds fileKind) { var assembly = new YacqAssembly(name, fileKind); var type = assembly.DefineType(":Program"); try { try { var method = type.DefineMethod( "Main", MethodAttributes.Static, typeof(void), Type.EmptyTypes, Expression.Lambda <Action>(Parse( new SymbolTable() { { "*assembly*", Expression.Constant(assembly) }, }, code )) ); type.Create(); assembly.Save(method); } catch (Exception ex) { Fail(ex, Phase.Emit); } } catch (Exception ex) { Fail(ex, Phase.Parse); } }
/// <include file='doc\AssemblyBuilder.uex' path='docs/doc[@for="AssemblyBuilder.SetEntryPoint1"]/*' /> public void SetEntryPoint( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit); try { Enter(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint"); if (entryMethod == null) { throw new ArgumentNullException("entryMethod"); } // Module tmpModule = entryMethod.InternalReflectedClass(true).Module; if (!(tmpModule is ModuleBuilder && this.Equals(tmpModule.Assembly))) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly")); } m_assemblyData.m_entryPointModule = (ModuleBuilder)tmpModule; m_assemblyData.m_entryPointMethod = entryMethod; m_assemblyData.m_peFileKind = fileKind; m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethod); } finally { Exit(); } }
// Constructor. Called from AppDomain.DefineDynamicAssembly. internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, String directory, bool isSynchronized) { this.access = access; this.directory = (directory == null) ? "." : directory; this.isSynchronized = isSynchronized; this.saved = false; this.entryPoint = null; this.detachList = new ArrayList(); fileKind = PEFileKinds.Dll; Version version = name.Version; lock (typeof(AssemblyBuilder)) { if (version != null) { this.privateData = ClrAssemblyCreate (name.Name, version.Major, version.Minor, version.Build, version.Revision, access, out writer); } else { this.privateData = ClrAssemblyCreate (name.Name, 0, 0, 0, 0, access, out writer); } } if (this.privateData == IntPtr.Zero) { // The runtime engine disallowed dynamic assemblies. throw new SecurityException (_("Emit_NoDynamicAssemblies")); } }
internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ResourceSection resources, int entryPointToken, Stream stream) { if (stream == null) { string fileName = moduleBuilder.FullyQualifiedName; bool mono = System.Type.GetType("Mono.Runtime") != null; if (mono) { try { // Mono mmaps the file, so unlink the previous version since it may be in use File.Delete(fileName); } catch { } } using (FileStream fs = new FileStream(fileName, FileMode.Create)) { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs); } // if we're running on Mono, mark the module as executable by using a Mono private API extension if (mono) { File.SetAttributes(fileName, (FileAttributes)(unchecked((int)0x80000000))); } } else { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream); } }
internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ResourceSection resources, int entryPointToken, Stream stream) { if (stream == null) { string fileName = moduleBuilder.FullyQualifiedName; bool mono = System.Type.GetType("Mono.Runtime") != null; if (mono) { try { // Mono mmaps the file, so unlink the previous version since it may be in use File.Delete(fileName); } catch { } } using (FileStream fs = new FileStream(fileName, FileMode.Create)) { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs); } // if we're running on Mono, mark the module as executable by using a Mono private API extension if (mono) { File.SetAttributes(fileName, (FileAttributes)(unchecked ((int)0x80000000))); } } else { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream); } }
public void SetEntryPoint( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { lock (SyncRoot) { SetEntryPointNoLock(entryMethod, fileKind); } }
internal AssemblyBuilderData(InternalAssemblyBuilder assembly, string strAssemblyName, AssemblyBuilderAccess access, string dir) { this.m_assembly = assembly; this.m_strAssemblyName = strAssemblyName; this.m_access = access; this.m_moduleBuilderList = new List <ModuleBuilder>(); this.m_resWriterList = new List <ResWriterData>(); this.m_strDir = dir != null || access == AssemblyBuilderAccess.Run ? dir : Environment.CurrentDirectory; this.m_peFileKind = PEFileKinds.Dll; }
public void Initialize(string[] filenames, string outputAssembly, bool includeDebug, StringCollection references, PEFileKinds targetKind) { files = filenames; outAsm = outputAssembly; if (outAsm == null) { outAsm = "assembly.dll"; } debugInfo = includeDebug; refs = references; peKind = targetKind; }
private static void Main(string[] args) { if (args.IsEmpty()) { Console.WriteLine("TokensBuilder.NET (c) 2020-2020\n" + "Author: snaulX\n" + "GitHub repository: https://github.com/mino-lang/TokensBuilder.NET \n" + "For get help use command -h\n"); } else if (args[0] == "-h") { if (args.Length == 1) { Console.WriteLine("TokensBuilder (name of tokens file[s] written how one cmd argument) [commands]\n" + "Commands:\n" + "\t-type (kind of building application)\tSet type of building application. Types:\n" + $"\t\t{string.Join("\n\t\t", Enum.GetValues(typeof(PEFileKinds)))}\n" + "\t-o (name of output file)\tSet name of output file (application name).\n" + "\t-name (name of main class)\tSet name of main auto-generated class." + " Will work only if tokens header is Script or Class\n"); } } else { PEFileKinds kind = PEFileKinds.ConsoleApplication; string appName = ""; int index = Array.IndexOf(args, "-type"); if (index > 1) { kind = (PEFileKinds)Enum.Parse(typeof(PEFileKinds), args[index + 1]); } index = Array.IndexOf(args, "-o"); if (index > 1) { appName = args[index + 1]; } index = Array.IndexOf(args, "-name"); if (index > 1) { Config.MainClassName = args[index + 1]; } foreach (string fileName in args[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) { gen = new Generator(); gen.reader.SetPath(fileName); Config.appName = appName.IsEmpty() ? System.IO.Path.GetFileNameWithoutExtension(fileName) : appName; Config.outputType = kind; Context.CreateAssembly(true); gen.Generate(); } Context.Finish(); } }
public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) { if (entryMethod == null) { throw new ArgumentNullException("entryMethod"); } if (entryMethod.DeclaringType.Assembly != this) { throw new InvalidOperationException (_("Invalid_EntryNotInAssembly")); } entryPoint = entryMethod; this.fileKind = fileKind; }
public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) { if (entryMethod == null) { throw new ArgumentNullException("entryMethod"); } if (entryMethod.DeclaringType.Assembly != this) { throw new InvalidOperationException("Entry method is not defined in the same assembly."); } entry_point = entryMethod; pekind = fileKind; }
internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ResourceSection resources, int entryPointToken, Stream stream) { if (stream == null) { using (FileStream fs = new FileStream(moduleBuilder.FullyQualifiedName, FileMode.Create)) { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs); } } else { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream); } }
public CompilerOptions(){ this.autoRef = true; this.PEFileKind = PEFileKinds.ConsoleApplication; this.fFast = true; this.fPrint = true; this.nWarningLevel = 4; this.SourceFileNames = new ArrayList(); this.ImportFileNames = new ArrayList(); this.ManagedResourceFileNames = new Hashtable(10); this.ManagedResources = new Hashtable(10); this.Defines = new Hashtable(); string libpath = System.Environment.GetEnvironmentVariable("LIB"); if (libpath != null) this.libpath = libpath; else this.libpath = ""; }
public void SetEntryPoint( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit); if (m_assemblyData.m_isSynchronized) { lock (m_assemblyData) { SetEntryPointNoLock(entryMethod, fileKind); } } else { SetEntryPointNoLock(entryMethod, fileKind); } }
/// <summary> /// Initializes a new instance of the <see cref="YacqAssembly"/> class. /// </summary> /// <param name="name">Name of dynamic assembly which contains generated types.</param> /// <param name="fileKind">The type of the assembly executable being built.</param> public YacqAssembly(String name, PEFileKinds fileKind = PEFileKinds.Dll) { this._assembly = new Lazy<AssemblyBuilder>( () => AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName(name), #if SILVERLIGHT AssemblyBuilderAccess.Run #else AssemblyBuilderAccess.RunAndSave #endif ), true ); this._module = new Lazy<ModuleBuilder>( () => this.Assembly.DefineDynamicModule(name + (fileKind == PEFileKinds.Dll ? ".dll" : ".exe")), true ); this._fileKind = fileKind; this._types = new Dictionary<String, YacqType>(); }
internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ResourceSection resources, int entryPointToken, Stream stream) { if (stream == null) { using (FileStream fs = new FileStream(moduleBuilder.FullyQualifiedName, FileMode.Create)) { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs); } // if we're running on Mono, mark the module as executable by using a Mono private API extension if (System.Type.GetType("Mono.Runtime") != null) { File.SetAttributes(moduleBuilder.FullyQualifiedName, (FileAttributes)(unchecked((int)0x80000000))); } } else { WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream); } }
/// <summary> /// Creates and initializes an CodeGenerator instance. /// </summary> /// <param name="parser">A Parser</param> /// <param name="outputPath">The path of the output file</param> /// <param name="isDLL">A value indicating whether the output should be a DLL or not.</param> public CodeGenerator(CompilerContext context, string outputPath, bool isDLL) { this.context = context; this.outputPath = outputPath; outputFilename = Path.GetFileName(this.outputPath); this.isDLL = isDLL; if (isDLL) { PEFileKind = PEFileKinds.Dll; this.outputPath += ".dll"; } else { PEFileKind = PEFileKinds.ConsoleApplication; this.outputPath += ".exe"; } Initialize(); }
private void SetEntryPointNoLock( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { if (entryMethod == null) { throw new ArgumentNullException(nameof(entryMethod)); } Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint"); Module tmpModule = entryMethod.Module; if (tmpModule == null || !InternalAssembly.Equals(tmpModule.Assembly)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly")); } m_assemblyData.m_entryPointMethod = entryMethod; m_assemblyData.m_peFileKind = fileKind; }
private void SetEntryPointNoLock( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint"); if (entryMethod == null) { throw new ArgumentNullException("entryMethod"); } // // Module tmpModule = entryMethod.Module; if (!(tmpModule is ModuleBuilder && this.Equals(tmpModule.Assembly))) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly")); } m_assemblyData.m_entryPointModule = (ModuleBuilder)tmpModule; m_assemblyData.m_entryPointMethod = entryMethod; m_assemblyData.m_peFileKind = fileKind; m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethod); }
internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ByteBuffer versionInfoData, byte[] unmanagedResources, int entryPointToken) { moduleBuilder.FixupMethodBodyTokens(); moduleBuilder.ModuleTable.Add(0, moduleBuilder.Strings.Add(moduleBuilder.moduleName), moduleBuilder.Guids.Add(moduleBuilder.ModuleVersionId), 0, 0); if (moduleBuilder.UserStrings.IsEmpty) { // for compat with Ref.Emit, if there aren't any user strings, we add one moduleBuilder.UserStrings.Add(" "); } using (FileStream fs = new FileStream(moduleBuilder.FullyQualifiedName, FileMode.Create)) { PEWriter writer = new PEWriter(fs); switch (imageFileMachine) { case ImageFileMachine.I386: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_32BIT_MACHINE; break; case ImageFileMachine.AMD64: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE; writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0; writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC; writer.Headers.OptionalHeader.SizeOfStackReserve = 0x400000; writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000; writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000; break; case ImageFileMachine.IA64: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE; writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0; writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC; writer.Headers.OptionalHeader.SizeOfStackReserve = 0x400000; writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000; writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000; break; default: throw new ArgumentOutOfRangeException("imageFileMachine"); } if (fileKind == PEFileKinds.Dll) { writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_DLL; } switch (fileKind) { case PEFileKinds.WindowApplication: writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_GUI; break; default: writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_CUI; break; } writer.Headers.OptionalHeader.DllCharacteristics = IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NO_SEH | IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NX_COMPAT | IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE; CliHeader cliHeader = new CliHeader(); cliHeader.Cb = 0x48; cliHeader.MajorRuntimeVersion = 2; cliHeader.MinorRuntimeVersion = moduleBuilder.MDStreamVersion < 0x20000 ? (ushort)0 : (ushort)5; if ((portableExecutableKind & PortableExecutableKinds.ILOnly) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_ILONLY; } if ((portableExecutableKind & PortableExecutableKinds.Required32Bit) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_32BITREQUIRED; } if (keyPair != null) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_STRONGNAMESIGNED; } if (moduleBuilder.IsPseudoToken(entryPointToken)) { entryPointToken = moduleBuilder.ResolvePseudoToken(entryPointToken); } cliHeader.EntryPointToken = (uint)entryPointToken; moduleBuilder.Strings.Freeze(); moduleBuilder.UserStrings.Freeze(); moduleBuilder.Guids.Freeze(); moduleBuilder.Blobs.Freeze(); MetadataWriter mw = new MetadataWriter(moduleBuilder, fs); moduleBuilder.Tables.Freeze(mw); TextSection code = new TextSection(writer, cliHeader, moduleBuilder, publicKey != null); ResourceSection resources = new ResourceSection(versionInfoData, unmanagedResources); // Import Directory writer.Headers.OptionalHeader.DataDirectory[1].VirtualAddress = code.ImportDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[1].Size = code.ImportDirectoryLength; // Import Address Table Directory writer.Headers.OptionalHeader.DataDirectory[12].VirtualAddress = code.ImportAddressTableRVA; writer.Headers.OptionalHeader.DataDirectory[12].Size = code.ImportAddressTableLength; // COM Descriptor Directory writer.Headers.OptionalHeader.DataDirectory[14].VirtualAddress = code.ComDescriptorRVA; writer.Headers.OptionalHeader.DataDirectory[14].Size = code.ComDescriptorLength; // Debug Directory if (code.DebugDirectoryLength != 0) { writer.Headers.OptionalHeader.DataDirectory[6].VirtualAddress = code.DebugDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[6].Size = code.DebugDirectoryLength; } writer.Headers.FileHeader.NumberOfSections = 2; if (moduleBuilder.initializedData.Length != 0) { writer.Headers.FileHeader.NumberOfSections++; } if (resources.Length != 0) { writer.Headers.FileHeader.NumberOfSections++; } SectionHeader text = new SectionHeader(); text.Name = ".text"; text.VirtualAddress = code.BaseRVA; text.VirtualSize = (uint)code.Length; text.PointerToRawData = code.PointerToRawData; text.SizeOfRawData = writer.ToFileAlignment((uint)code.Length); text.Characteristics = SectionHeader.IMAGE_SCN_CNT_CODE | SectionHeader.IMAGE_SCN_MEM_EXECUTE | SectionHeader.IMAGE_SCN_MEM_READ; SectionHeader sdata = new SectionHeader(); sdata.Name = ".sdata"; sdata.VirtualAddress = text.VirtualAddress + writer.ToSectionAlignment(text.VirtualSize); sdata.VirtualSize = (uint)moduleBuilder.initializedData.Length; sdata.PointerToRawData = text.PointerToRawData + text.SizeOfRawData; sdata.SizeOfRawData = writer.ToFileAlignment((uint)moduleBuilder.initializedData.Length); sdata.Characteristics = SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_MEM_WRITE; SectionHeader rsrc = new SectionHeader(); rsrc.Name = ".rsrc"; rsrc.VirtualAddress = sdata.VirtualAddress + writer.ToSectionAlignment(sdata.VirtualSize); rsrc.PointerToRawData = sdata.PointerToRawData + sdata.SizeOfRawData; rsrc.VirtualSize = (uint)resources.Length; rsrc.SizeOfRawData = writer.ToFileAlignment(rsrc.VirtualSize); rsrc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA; if (rsrc.SizeOfRawData != 0) { // Resource Directory writer.Headers.OptionalHeader.DataDirectory[2].VirtualAddress = rsrc.VirtualAddress; writer.Headers.OptionalHeader.DataDirectory[2].Size = rsrc.VirtualSize; } SectionHeader reloc = new SectionHeader(); reloc.Name = ".reloc"; reloc.VirtualAddress = rsrc.VirtualAddress + writer.ToSectionAlignment(rsrc.VirtualSize); reloc.VirtualSize = 12; reloc.PointerToRawData = rsrc.PointerToRawData + rsrc.SizeOfRawData; reloc.SizeOfRawData = writer.ToFileAlignment(reloc.VirtualSize); reloc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_DISCARDABLE; // Base Relocation Directory writer.Headers.OptionalHeader.DataDirectory[5].VirtualAddress = reloc.VirtualAddress; writer.Headers.OptionalHeader.DataDirectory[5].Size = reloc.VirtualSize; writer.Headers.OptionalHeader.SizeOfCode = text.SizeOfRawData; writer.Headers.OptionalHeader.SizeOfInitializedData = sdata.SizeOfRawData + rsrc.SizeOfRawData + reloc.SizeOfRawData; writer.Headers.OptionalHeader.SizeOfUninitializedData = 0; writer.Headers.OptionalHeader.SizeOfImage = reloc.VirtualAddress + writer.ToSectionAlignment(reloc.VirtualSize); writer.Headers.OptionalHeader.SizeOfHeaders = text.PointerToRawData; writer.Headers.OptionalHeader.BaseOfCode = code.BaseRVA; writer.Headers.OptionalHeader.BaseOfData = sdata.VirtualAddress; writer.Headers.OptionalHeader.ImageBase = (ulong)moduleBuilder.__ImageBase; if (imageFileMachine == ImageFileMachine.IA64) { // apparently for IA64 AddressOfEntryPoint points to the address of the entry point // (i.e. there is an additional layer of indirection), so we add the offset to the pointer writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA + 0x20; } else { writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA; } writer.WritePEHeaders(); writer.WriteSectionHeader(text); if (sdata.SizeOfRawData != 0) { writer.WriteSectionHeader(sdata); } if (rsrc.SizeOfRawData != 0) { writer.WriteSectionHeader(rsrc); } writer.WriteSectionHeader(reloc); fs.Seek(text.PointerToRawData, SeekOrigin.Begin); code.Write(mw, (int)sdata.VirtualAddress); fs.Seek(sdata.PointerToRawData, SeekOrigin.Begin); mw.Write(moduleBuilder.initializedData); if (rsrc.SizeOfRawData != 0) { fs.Seek(rsrc.PointerToRawData, SeekOrigin.Begin); resources.Write(mw, rsrc.VirtualAddress); } fs.Seek(reloc.PointerToRawData, SeekOrigin.Begin); // .reloc section uint relocAddress = code.StartupStubRVA; switch (imageFileMachine) { case ImageFileMachine.I386: case ImageFileMachine.AMD64: relocAddress += 2; break; case ImageFileMachine.IA64: relocAddress += 0x20; break; } uint pageRVA = relocAddress & ~0xFFFU; mw.Write(pageRVA); // PageRVA mw.Write(0x000C); // Block Size if (imageFileMachine == ImageFileMachine.I386) { mw.Write(0x3000 + relocAddress - pageRVA); // Type / Offset } else if (imageFileMachine == ImageFileMachine.AMD64) { mw.Write(0xA000 + relocAddress - pageRVA); // Type / Offset } else if (imageFileMachine == ImageFileMachine.IA64) { // on IA64 the StartupStubRVA is 16 byte aligned, so these two addresses won't cross a page boundary mw.Write((short)(0xA000 + relocAddress - pageRVA)); // Type / Offset mw.Write((short)(0xA000 + relocAddress - pageRVA + 8)); // Type / Offset } // file alignment mw.Write(new byte[writer.Headers.OptionalHeader.FileAlignment - reloc.VirtualSize]); // do the strong naming if (keyPair != null) { StrongName(fs, keyPair, writer.HeaderSize, text.PointerToRawData, code.StrongNameSignatureRVA - text.VirtualAddress + text.PointerToRawData, code.StrongNameSignatureLength); } } if (moduleBuilder.symbolWriter != null) { moduleBuilder.WriteSymbolTokenMap(); moduleBuilder.symbolWriter.Close(); } }
public void SetEntryPoint(MethodInfo mi, PEFileKinds kind) { _myAssembly.SetEntryPoint(mi, kind); }
internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ResourceSection resources, int entryPointToken) { WriteModule(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, null); }
protected override void SetCustomOption(String name, Object value){ try{ if (String.Compare(name, "CLSCompliant", true, CultureInfo.InvariantCulture) == 0) this.isCLSCompliant = (bool)value; else if (String.Compare(name, "fast", true, CultureInfo.InvariantCulture) == 0) this.doFast = (bool)value; else if (String.Compare(name, "output", true, CultureInfo.InvariantCulture) == 0){ if (value is String){ this.PEFileName = (String)value; this.doSaveAfterCompile = true; } }else if (String.Compare(name, "PEFileKind", true, CultureInfo.InvariantCulture) == 0) this.PEFileKind = (PEFileKinds)value; else if (String.Compare(name, "print", true, CultureInfo.InvariantCulture) == 0) this.doPrint = (bool)value; else if (String.Compare(name, "UseContextRelativeStatics", true, CultureInfo.InvariantCulture) == 0) this.doCRS = (bool)value; // the next two are needed because of the ICompiler interface. They should not fail even though they may not do anything else if (String.Compare(name, "optimize", true, CultureInfo.InvariantCulture) == 0) return; else if (String.Compare(name, "define", true, CultureInfo.InvariantCulture) == 0) return; else if (String.Compare(name, "defines", true, CultureInfo.InvariantCulture) == 0) this.Defines = (Hashtable)value; else if (String.Compare(name, "ee", true, CultureInfo.InvariantCulture) == 0) VsaEngine.executeForJSEE = (Boolean)value; else if (String.Compare(name, "version", true, CultureInfo.InvariantCulture) == 0) this.versionInfo = (Version)value; else if (String.Compare(name, "VersionSafe", true, CultureInfo.InvariantCulture) == 0) this.versionSafe = (Boolean)value; else if (String.Compare(name, "libpath", true, CultureInfo.InvariantCulture) == 0) this.libpath = (String)value; else if (String.Compare(name, "warnaserror", true, CultureInfo.InvariantCulture) == 0) this.doWarnAsError = (bool)value; else if (String.Compare(name, "WarningLevel", true, CultureInfo.InvariantCulture) == 0) this.nWarningLevel = (int)value; else if (String.Compare(name, "managedResources", true, CultureInfo.InvariantCulture) == 0) this.managedResources = (ICollection)value; else if (String.Compare(name, "alwaysGenerateIL", true, CultureInfo.InvariantCulture) == 0) this.alwaysGenerateIL = (bool)value; else if (String.Compare(name, "DebugDirectory", true, CultureInfo.InvariantCulture) == 0){ // use null to turn off SaveSourceState source generation if (value == null){ this.debugDirectory = null; return; } string dir = value as string; if (dir == null) throw new VsaException(VsaError.OptionInvalid); try{ dir = Path.GetFullPath(dir + Path.DirectorySeparatorChar); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); }catch(Exception e){ // we couldn't create the specified directory throw new VsaException(VsaError.OptionInvalid, "", e); } this.debugDirectory = dir; }else if (String.Compare(name, "AutoRef", true, CultureInfo.InvariantCulture) == 0) this.autoRef = (bool)value; else throw new VsaException(VsaError.OptionNotSupported); }catch(VsaException){ throw; }catch(Exception){ throw new VsaException(VsaError.OptionInvalid); } }
public void SetEntryPoint(MethodInfo mi, PEFileKinds kind) { myAssembly.SetEntryPoint(mi, PEFileKinds.ConsoleApplication); }
private void SetEntryPointNoLock( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { if (entryMethod == null) throw new ArgumentNullException("entryMethod"); Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint"); Module tmpModule = entryMethod.Module; if (tmpModule == null || !InternalAssembly.Equals(tmpModule.Assembly)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly")); m_assemblyData.m_entryPointMethod = entryMethod; m_assemblyData.m_peFileKind = fileKind; #if !FEATURE_CORECLR // Setting the entry point ModuleBuilder tmpMB = tmpModule as ModuleBuilder; if (tmpMB != null) m_assemblyData.m_entryPointModule = tmpMB; else m_assemblyData.m_entryPointModule = GetModuleBuilder((InternalModuleBuilder)tmpModule); MethodToken entryMethodToken = m_assemblyData.m_entryPointModule.GetMethodToken(entryMethod); m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethodToken); #endif //!FEATURE_CORECLR }
extern private static bool ClrSave(IntPtr assembly, IntPtr writer, String path, IntPtr entryMethod, PEFileKinds fileKind /*, TODO */);
public SourceProjectModel ParseProjectFile(CompileMessageCollection messageCollection, string[] lines, string folderPath, string projectFilePath)//, ZCompileFileInfo zfileInfo) { SourceProjectModel projectModel = new SourceProjectModel(); projectModel.NeedSave = true; projectModel.AddRefPackage("Z语言系统"); for (int i = 0; i < lines.Length; i++) { string code = lines[i]; if (string.IsNullOrEmpty(code)) { continue; } else if (code.StartsWith("//")) { continue; } else if (code.StartsWith("包名称:")) { string name = code.Substring(4); projectModel.ProjectPackageName = name; projectModel.BinaryFileNameNoEx = name; } else if (code.StartsWith("生成类型:")) { string lx = code.Substring(5); PEFileKinds fileKind = PEFileKinds.ConsoleApplication; if (lx == "开发包") { fileKind = PEFileKinds.Dll; } else if (lx == "控制台程序") { fileKind = PEFileKinds.ConsoleApplication; } else if (lx == "桌面程序") { fileKind = PEFileKinds.WindowApplication; } projectModel.BinaryFileKind = fileKind; } else if (code.StartsWith("编译:")) { string src = code.Substring(3); //string srcPath = Path.Combine(folderPath, src); SourceFileModel classModel = readFileModel(folderPath, src, projectModel.ProjectPackageName);// new SourceFileModel(new ZCompileFileInfo(false, srcPath, null, null)); projectModel.AddFile(classModel); } else if (code.StartsWith("设置启动:")) { string name = code.Substring(5); projectModel.EntryClassName = name; } else if (code.StartsWith("保存:")) { string name = code.Substring(3); projectModel.BinaryFileNameNoEx = name; } else { messageCollection.AddError( new CompileMessage(new CompileMessageSrcKey(projectFilePath), i + 1, 0, "项目指令'" + code + "'无效")); } } return(projectModel); }
private static void WriteModuleImpl(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ResourceSection resources, int entryPointToken, Stream stream) { moduleBuilder.ApplyUnmanagedExports(imageFileMachine); moduleBuilder.FixupMethodBodyTokens(); moduleBuilder.ModuleTable.Add(0, moduleBuilder.Strings.Add(moduleBuilder.moduleName), moduleBuilder.Guids.Add(moduleBuilder.ModuleVersionId), 0, 0); if (moduleBuilder.UserStrings.IsEmpty) { // for compat with Ref.Emit, if there aren't any user strings, we add one moduleBuilder.UserStrings.Add(" "); } if (resources != null) { resources.Finish(); } PEWriter writer = new PEWriter(stream); switch (imageFileMachine) { case ImageFileMachine.I386: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_32BIT_MACHINE; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x100000); break; case ImageFileMachine.ARM: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_32BIT_MACHINE; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x100000); break; case ImageFileMachine.AMD64: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE; writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0; writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x400000); writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000; writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000; break; case ImageFileMachine.IA64: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE; writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0; writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x400000); writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000; writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000; break; default: throw new ArgumentOutOfRangeException("imageFileMachine"); } if (fileKind == PEFileKinds.Dll) { writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_DLL; } switch (fileKind) { case PEFileKinds.WindowApplication: writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_GUI; break; default: writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_CUI; break; } writer.Headers.OptionalHeader.DllCharacteristics = IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NO_SEH | IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NX_COMPAT | IMAGE_OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE; CliHeader cliHeader = new CliHeader(); cliHeader.Cb = 0x48; cliHeader.MajorRuntimeVersion = 2; cliHeader.MinorRuntimeVersion = moduleBuilder.MDStreamVersion < 0x20000 ? (ushort)0 : (ushort)5; if ((portableExecutableKind & PortableExecutableKinds.ILOnly) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_ILONLY; } if ((portableExecutableKind & PortableExecutableKinds.Required32Bit) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_32BITREQUIRED; } if ((portableExecutableKind & PortableExecutableKinds.Preferred32Bit) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_32BITREQUIRED | CliHeader.COMIMAGE_FLAGS_32BITPREFERRED; } if (keyPair != null) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_STRONGNAMESIGNED; } if (moduleBuilder.IsPseudoToken(entryPointToken)) { entryPointToken = moduleBuilder.ResolvePseudoToken(entryPointToken); } cliHeader.EntryPointToken = (uint)entryPointToken; moduleBuilder.Strings.Freeze(); moduleBuilder.UserStrings.Freeze(); moduleBuilder.Guids.Freeze(); moduleBuilder.Blobs.Freeze(); MetadataWriter mw = new MetadataWriter(moduleBuilder, stream); moduleBuilder.Tables.Freeze(mw); TextSection code = new TextSection(writer, cliHeader, moduleBuilder, ComputeStrongNameSignatureLength(publicKey)); // Export Directory if (code.ExportDirectoryLength != 0) { writer.Headers.OptionalHeader.DataDirectory[0].VirtualAddress = code.ExportDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[0].Size = code.ExportDirectoryLength; } // Import Directory if (code.ImportDirectoryLength != 0) { writer.Headers.OptionalHeader.DataDirectory[1].VirtualAddress = code.ImportDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[1].Size = code.ImportDirectoryLength; } // Import Address Table Directory if (code.ImportAddressTableLength != 0) { writer.Headers.OptionalHeader.DataDirectory[12].VirtualAddress = code.ImportAddressTableRVA; writer.Headers.OptionalHeader.DataDirectory[12].Size = code.ImportAddressTableLength; } // COM Descriptor Directory writer.Headers.OptionalHeader.DataDirectory[14].VirtualAddress = code.ComDescriptorRVA; writer.Headers.OptionalHeader.DataDirectory[14].Size = code.ComDescriptorLength; // Debug Directory if (code.DebugDirectoryLength != 0) { writer.Headers.OptionalHeader.DataDirectory[6].VirtualAddress = code.DebugDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[6].Size = code.DebugDirectoryLength; } // we need to start by computing the number of sections, because code.PointerToRawData depends on that writer.Headers.FileHeader.NumberOfSections = 1; if (moduleBuilder.initializedData.Length != 0) { // .sdata writer.Headers.FileHeader.NumberOfSections++; } if (resources != null) { // .rsrc writer.Headers.FileHeader.NumberOfSections++; } if (imageFileMachine != ImageFileMachine.ARM) { // .reloc writer.Headers.FileHeader.NumberOfSections++; } SectionHeader text = new SectionHeader(); text.Name = ".text"; text.VirtualAddress = code.BaseRVA; text.VirtualSize = (uint)code.Length; text.PointerToRawData = code.PointerToRawData; text.SizeOfRawData = writer.ToFileAlignment((uint)code.Length); text.Characteristics = SectionHeader.IMAGE_SCN_CNT_CODE | SectionHeader.IMAGE_SCN_MEM_EXECUTE | SectionHeader.IMAGE_SCN_MEM_READ; SectionHeader sdata = new SectionHeader(); sdata.Name = ".sdata"; sdata.VirtualAddress = text.VirtualAddress + writer.ToSectionAlignment(text.VirtualSize); sdata.VirtualSize = (uint)moduleBuilder.initializedData.Length; sdata.PointerToRawData = text.PointerToRawData + text.SizeOfRawData; sdata.SizeOfRawData = writer.ToFileAlignment((uint)moduleBuilder.initializedData.Length); sdata.Characteristics = SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_MEM_WRITE; SectionHeader rsrc = new SectionHeader(); rsrc.Name = ".rsrc"; rsrc.VirtualAddress = sdata.VirtualAddress + writer.ToSectionAlignment(sdata.VirtualSize); rsrc.PointerToRawData = sdata.PointerToRawData + sdata.SizeOfRawData; rsrc.VirtualSize = resources == null ? 0 : (uint)resources.Length; rsrc.SizeOfRawData = writer.ToFileAlignment(rsrc.VirtualSize); rsrc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA; if (rsrc.SizeOfRawData != 0) { // Resource Directory writer.Headers.OptionalHeader.DataDirectory[2].VirtualAddress = rsrc.VirtualAddress; writer.Headers.OptionalHeader.DataDirectory[2].Size = rsrc.VirtualSize; } SectionHeader reloc = new SectionHeader(); reloc.Name = ".reloc"; reloc.VirtualAddress = rsrc.VirtualAddress + writer.ToSectionAlignment(rsrc.VirtualSize); if (imageFileMachine != ImageFileMachine.ARM) { reloc.VirtualSize = ((uint)moduleBuilder.unmanagedExports.Count + 1) * 12; } reloc.PointerToRawData = rsrc.PointerToRawData + rsrc.SizeOfRawData; reloc.SizeOfRawData = writer.ToFileAlignment(reloc.VirtualSize); reloc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_DISCARDABLE; if (reloc.SizeOfRawData != 0) { // Base Relocation Directory writer.Headers.OptionalHeader.DataDirectory[5].VirtualAddress = reloc.VirtualAddress; writer.Headers.OptionalHeader.DataDirectory[5].Size = reloc.VirtualSize; } writer.Headers.OptionalHeader.SizeOfCode = text.SizeOfRawData; writer.Headers.OptionalHeader.SizeOfInitializedData = sdata.SizeOfRawData + rsrc.SizeOfRawData + reloc.SizeOfRawData; writer.Headers.OptionalHeader.SizeOfUninitializedData = 0; writer.Headers.OptionalHeader.SizeOfImage = reloc.VirtualAddress + writer.ToSectionAlignment(reloc.VirtualSize); writer.Headers.OptionalHeader.SizeOfHeaders = text.PointerToRawData; writer.Headers.OptionalHeader.BaseOfCode = code.BaseRVA; writer.Headers.OptionalHeader.BaseOfData = sdata.VirtualAddress; writer.Headers.OptionalHeader.ImageBase = (ulong)moduleBuilder.__ImageBase; if (imageFileMachine == ImageFileMachine.IA64) { // apparently for IA64 AddressOfEntryPoint points to the address of the entry point // (i.e. there is an additional layer of indirection), so we add the offset to the pointer writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA + 0x20; } else if (imageFileMachine != ImageFileMachine.ARM) { writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA; } writer.WritePEHeaders(); writer.WriteSectionHeader(text); if (sdata.SizeOfRawData != 0) { writer.WriteSectionHeader(sdata); } if (rsrc.SizeOfRawData != 0) { writer.WriteSectionHeader(rsrc); } if (reloc.SizeOfRawData != 0) { writer.WriteSectionHeader(reloc); } stream.Seek(text.PointerToRawData, SeekOrigin.Begin); code.Write(mw, sdata.VirtualAddress); if (sdata.SizeOfRawData != 0) { stream.Seek(sdata.PointerToRawData, SeekOrigin.Begin); mw.Write(moduleBuilder.initializedData); } if (rsrc.SizeOfRawData != 0) { stream.Seek(rsrc.PointerToRawData, SeekOrigin.Begin); resources.Write(mw, rsrc.VirtualAddress); } if (reloc.SizeOfRawData != 0) { stream.Seek(reloc.PointerToRawData, SeekOrigin.Begin); code.WriteRelocations(mw); } // file alignment stream.SetLength(reloc.PointerToRawData + reloc.SizeOfRawData); // do the strong naming if (keyPair != null) { StrongName(stream, keyPair, writer.HeaderSize, text.PointerToRawData, code.StrongNameSignatureRVA - text.VirtualAddress + text.PointerToRawData, code.StrongNameSignatureLength); } if (moduleBuilder.symbolWriter != null) { moduleBuilder.WriteSymbolTokenMap(); moduleBuilder.symbolWriter.Close(); } }
private static void Compile(String code, String name, PEFileKinds fileKind) { var assembly = new YacqAssembly(name, fileKind); var type = assembly.DefineType(":Program"); try { try { var method = type.DefineMethod( "Main", MethodAttributes.Static, typeof(void), Type.EmptyTypes, Expression.Lambda<Action>(Parse( new SymbolTable() { {"*assembly*", Expression.Constant(assembly)}, }, code )) ); type.Create(); assembly.Save(method); } catch (Exception ex) { Fail(ex, Phase.Emit); } } catch (Exception ex) { Fail(ex, Phase.Parse); } }
private static void CreateAssembly(string assemblyName, string[] inputAssemblies, PEFileKinds fileKind) { var outputFileName = $"{assemblyName}.exe"; var builder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Save); var moduleBuilder = builder.DefineDynamicModule("main-module", outputFileName); var resourceNames = new List <string>(); var counter = 0; var fileStreams = new List <Stream>(); foreach (var filePath in inputAssemblies) { var fileName = Path.GetFileNameWithoutExtension(filePath); var resourceName = $"{fileName}_asm_{counter++:0000}"; resourceNames.Add(resourceName); var fileStream = File.OpenRead(filePath); fileStreams.Add(fileStream); moduleBuilder.DefineManifestResource(resourceName, fileStream, ResourceAttributes.Private); } var typeBuilder = moduleBuilder.DefineType("Program", TypeAttributes.Class | TypeAttributes.Public); var assembliesField = typeBuilder.DefineField("_assemblies", typeof(List <Assembly>), FieldAttributes.Private | FieldAttributes.Static); // Assemblies resolve method var assemblyResolve = GenerateAssemblyResolve(typeBuilder, assembliesField); // Main method var main = GenerateMain(typeBuilder, assembliesField, assemblyResolve, resourceNames); typeBuilder.CreateType(); builder.SetEntryPoint(main, fileKind); builder.Save(outputFileName); foreach (var stream in fileStreams) { stream.Dispose(); } }
private void SetEntryPointNoLock( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { if (entryMethod == null) throw new ArgumentNullException(nameof(entryMethod)); Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint"); Module tmpModule = entryMethod.Module; if (tmpModule == null || !InternalAssembly.Equals(tmpModule.Assembly)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly")); m_assemblyData.m_entryPointMethod = entryMethod; m_assemblyData.m_peFileKind = fileKind; }
protected override void SetCustomOption(string name, object value) { try { if (string.Compare(name, "CLSCompliant", StringComparison.OrdinalIgnoreCase) == 0) { this.isCLSCompliant = (bool) value; } else if (string.Compare(name, "fast", StringComparison.OrdinalIgnoreCase) == 0) { this.doFast = (bool) value; } else if (string.Compare(name, "output", StringComparison.OrdinalIgnoreCase) == 0) { if (value is string) { this.PEFileName = (string) value; this.doSaveAfterCompile = true; } } else if (string.Compare(name, "PEFileKind", StringComparison.OrdinalIgnoreCase) == 0) { this.PEFileKind = (PEFileKinds) value; } else if (string.Compare(name, "PortableExecutableKind", StringComparison.OrdinalIgnoreCase) == 0) { this.PEKindFlags = (PortableExecutableKinds) value; } else if (string.Compare(name, "ImageFileMachine", StringComparison.OrdinalIgnoreCase) == 0) { this.PEMachineArchitecture = (ImageFileMachine) value; } else if (string.Compare(name, "ReferenceLoaderAPI", StringComparison.OrdinalIgnoreCase) == 0) { string strA = (string) value; if (string.Compare(strA, "LoadFrom", StringComparison.OrdinalIgnoreCase) != 0) { if (string.Compare(strA, "LoadFile", StringComparison.OrdinalIgnoreCase) != 0) { if (string.Compare(strA, "ReflectionOnlyLoadFrom", StringComparison.OrdinalIgnoreCase) != 0) { throw new JSVsaException(JSVsaError.OptionInvalid); } this.ReferenceLoaderAPI = LoaderAPI.ReflectionOnlyLoadFrom; } else { this.ReferenceLoaderAPI = LoaderAPI.LoadFile; } } else { this.ReferenceLoaderAPI = LoaderAPI.LoadFrom; } } else if (string.Compare(name, "print", StringComparison.OrdinalIgnoreCase) == 0) { this.doPrint = (bool) value; } else if (string.Compare(name, "UseContextRelativeStatics", StringComparison.OrdinalIgnoreCase) == 0) { this.doCRS = (bool) value; } else if ((string.Compare(name, "optimize", StringComparison.OrdinalIgnoreCase) != 0) && (string.Compare(name, "define", StringComparison.OrdinalIgnoreCase) != 0)) { if (string.Compare(name, "defines", StringComparison.OrdinalIgnoreCase) == 0) { this.Defines = (Hashtable) value; } else if (string.Compare(name, "ee", StringComparison.OrdinalIgnoreCase) == 0) { executeForJSEE = (bool) value; } else if (string.Compare(name, "version", StringComparison.OrdinalIgnoreCase) == 0) { this.versionInfo = (Version) value; } else if (string.Compare(name, "VersionSafe", StringComparison.OrdinalIgnoreCase) == 0) { this.versionSafe = (bool) value; } else if (string.Compare(name, "libpath", StringComparison.OrdinalIgnoreCase) == 0) { this.libpath = (string) value; } else if (string.Compare(name, "warnaserror", StringComparison.OrdinalIgnoreCase) == 0) { this.doWarnAsError = (bool) value; } else if (string.Compare(name, "WarningLevel", StringComparison.OrdinalIgnoreCase) == 0) { this.nWarningLevel = (int) value; } else if (string.Compare(name, "win32resource", StringComparison.OrdinalIgnoreCase) == 0) { this.win32resource = (string) value; } else if (string.Compare(name, "managedResources", StringComparison.OrdinalIgnoreCase) == 0) { this.managedResources = (ICollection) value; } else if (string.Compare(name, "alwaysGenerateIL", StringComparison.OrdinalIgnoreCase) == 0) { this.alwaysGenerateIL = (bool) value; } else if (string.Compare(name, "DebugDirectory", StringComparison.OrdinalIgnoreCase) == 0) { if (value == null) { this.debugDirectory = null; } else { string path = value as string; if (path == null) { throw new JSVsaException(JSVsaError.OptionInvalid); } try { path = Path.GetFullPath(path + Path.DirectorySeparatorChar); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch (Exception exception) { throw new JSVsaException(JSVsaError.OptionInvalid, "", exception); } this.debugDirectory = path; } } else { if (string.Compare(name, "AutoRef", StringComparison.OrdinalIgnoreCase) != 0) { throw new JSVsaException(JSVsaError.OptionNotSupported); } this.autoRef = (bool) value; } } } catch (JSVsaException) { throw; } catch { throw new JSVsaException(JSVsaError.OptionInvalid); } }
public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) { this.entryPoint = entryMethod; this.fileKind = fileKind; }
//public ProjectCompileResult CompileProject(string projfile) //{ // ProjectCompileResult result = new ProjectCompileResult(); // string[] lines = File.ReadAllLines(projfile); // FileInfo projectFileInfo = new FileInfo(projfile); // string folder = projectFileInfo.Directory.FullName; // string binPath = Compile(lines, folder, result, projfile); // result.BinFilePath = binPath; // return result; //} public ZProjectModel ParseProjectFile(string[] lines, string folderPath) { //ProjectContext context = new ProjectContext(); ZProjectModel projectModel = new ZProjectModel(); projectModel.NeedSave = true; projectModel.AddRefPackage("Z语言系统"); //context.AddPackage("TKT系统"); //context.AddPackage("TKT绘图"); //context.AddPackage("TKT桌面控件"); //context.AddPackage("TKT文件系统"); //context.AddPackage("TKT互联网"); //context.AddPackage("TKT操作系统"); //context.AddPackage("TKT多媒体"); //projectModel.Analy(); for (int i = 0; i < lines.Length; i++) { string code = lines[i]; if (string.IsNullOrEmpty(code)) { continue; } else if (code.StartsWith("//")) { continue; } else if (code.StartsWith("包名称:")) { string name = code.Substring(4); projectModel.ProjectPackageName = name; projectModel.BinaryFileNameNoEx = name; } else if (code.StartsWith("生成类型:")) { string lx = code.Substring(5); PEFileKinds fileKind = PEFileKinds.ConsoleApplication; if (lx == "开发包") { fileKind = PEFileKinds.Dll; } else if (lx == "控制台程序") { fileKind = PEFileKinds.ConsoleApplication; } else if (lx == "桌面程序") { fileKind = PEFileKinds.WindowApplication; } projectModel.BinaryFileKind = fileKind; //GenerateProject(projectModel); } else if (code.StartsWith("编译:")) { string src = code.Substring(3); string srcPath = Path.Combine(folderPath, src); //var srcFileInfo = new FileInfo(srcPath); ZFileModel classModel = new ZFileModel(new ZCompileFileInfo(false, srcPath, null, null));// new ZFileModel(); //classModel.SourceFileInfo = srcFileInfo; projectModel.AddClass(classModel); } else if (code.StartsWith("设置启动:")) { string name = code.Substring(5); projectModel.EntryClassName = name; //Type type = projectModel.GetProjectType(name); //if (type == null) //{ // errorf(result, file, i + 1, 6, "类型'{0}'不存在", name); // continue; //} //MethodInfo main = type.GetMethod("启动"); //if (main == null) //{ // errorf(result, file, i + 1, 6, "类型'{0}'不存在'启动'过程", name); // continue; //} //if (!main.IsStatic) //{ // errorf(result, file, i + 1, 6, "'{0}'不是唯一类型,不能作为启动入口", name); // continue; //} //projectModel.EmitContext.AssemblyBuilder.SetEntryPoint(main, projectModel.PEKind); } else { throw new CompileException("无法识别项目编译指令:" + code); //errorf(result, file, i + 1, 1, "无法识别项目编译指令:'{0}'", code); //continue; //return null; } } return(projectModel); //if (result.HasError() == false) //{ // string binFileName = projectModel.BinFileName; // string binFilePath = Path.Combine(folderPath, binFileName); // //try // //{ // projectModel.EmitContext.AssemblyBuilder.Save(binFileName); // string str = System.AppDomain.CurrentDomain.BaseDirectory; // if (File.Exists(binFilePath)) // { // File.Delete(binFilePath); // } // File.Move(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, binFileName), binFilePath); // deletePDB(binFileName); // //} // //catch (Exception ex) // //{ // // //Console.WriteLine(ex.Message); // //} // return binFilePath; //} //return null; }
[System.Security.SecurityCritical] // auto-generated #endif public void SetEntryPoint( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { lock(SyncRoot) { SetEntryPointNoLock(entryMethod, fileKind); } }
internal CompilerGlobals(VsaEngine engine, String assemName, String assemblyFileName, PEFileKinds PEFileKind, bool save, bool run, bool debugOn, bool isCLSCompliant, Version version, Globals globals) { String moduleFileName = null; String directory = null; //Default has assembly stored in current directory if (assemblyFileName != null){ //The directory is an absolute path where the assembly is written try{ directory = Path.GetDirectoryName(Path.GetFullPath(assemblyFileName)); }catch(Exception e){ throw new VsaException(VsaError.AssemblyNameInvalid, assemblyFileName, e); }catch{ throw new JScriptException(JSError.NonClsException); } //For a single file assembly module filename is set to assembly filename moduleFileName = Path.GetFileName(assemblyFileName); //If simple name is not specified, get it by extracting the basename from assembly name if (null == assemName || String.Empty == assemName){ assemName = Path.GetFileName(assemblyFileName); if (Path.HasExtension(assemName)) assemName = assemName.Substring(0, assemName.Length - Path.GetExtension(assemName).Length); } } //Setup default simple assembly name and module name for the case where no assemblyFileName is specified. if (assemName == null || assemName == String.Empty) assemName = "JScriptAssembly"; if (moduleFileName == null) { if (PEFileKind == PEFileKinds.Dll) moduleFileName = "JScriptModule.dll"; else moduleFileName = "JScriptModule.exe"; } AssemblyName assemblyName = new AssemblyName(); assemblyName.CodeBase = assemblyFileName; if (globals.assemblyCulture != null) assemblyName.CultureInfo = globals.assemblyCulture; assemblyName.Flags = AssemblyNameFlags.None; if ((globals.assemblyFlags & AssemblyFlags.PublicKey) != 0) assemblyName.Flags = AssemblyNameFlags.PublicKey; switch ((AssemblyFlags)(globals.assemblyFlags & AssemblyFlags.CompatibilityMask)){ case AssemblyFlags.NonSideBySideAppDomain: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameDomain; break; case AssemblyFlags.NonSideBySideMachine: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameMachine; break; case AssemblyFlags.NonSideBySideProcess: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameProcess; break; default: assemblyName.VersionCompatibility = (AssemblyVersionCompatibility)0; break; } assemblyName.HashAlgorithm = globals.assemblyHashAlgorithm; if (globals.assemblyKeyFileName != null){ try { using (FileStream fs = new FileStream(globals.assemblyKeyFileName, FileMode.Open, FileAccess.Read)) { StrongNameKeyPair keyPair = new StrongNameKeyPair(fs); if (globals.assemblyDelaySign) if (fs.Length == 160) { Byte[] pkey = new Byte[160]; fs.Seek(0, SeekOrigin.Begin); int len = fs.Read(pkey, 0, 160); assemblyName.SetPublicKey(pkey); } else assemblyName.SetPublicKey(keyPair.PublicKey); else { // Fetch to force reflection to try and process the key file data and throw an exception byte[] publicKey = keyPair.PublicKey; assemblyName.KeyPair = keyPair; } } } catch { globals.assemblyKeyFileNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyFileName); } }else if (globals.assemblyKeyName != null){ try{ StrongNameKeyPair keyPair = new StrongNameKeyPair(globals.assemblyKeyName); byte[] publicKey = keyPair.PublicKey; // Force validation assemblyName.KeyPair = keyPair; }catch{ globals.assemblyKeyNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyName); } } assemblyName.Name = assemName; if (version != null) assemblyName.Version = version; else if (globals.assemblyVersion != null) assemblyName.Version = globals.assemblyVersion; AssemblyBuilderAccess access = save ? (run ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Save) : AssemblyBuilderAccess.Run; if (engine.ReferenceLoaderAPI == LoaderAPI.ReflectionOnlyLoadFrom) access = AssemblyBuilderAccess.ReflectionOnly; // Supply the evidence to assemblies built for VSA if (globals.engine.genStartupClass) this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, access, directory, globals.engine.Evidence); else this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, access, directory); if (save) this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", moduleFileName, debugOn); else this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", debugOn); if (isCLSCompliant) this.module.SetCustomAttribute(new CustomAttributeBuilder(CompilerGlobals.clsCompliantAttributeCtor, new Object[]{isCLSCompliant})); if (debugOn){ ConstructorInfo debuggableAttr = Typeob.DebuggableAttribute.GetConstructor(new Type[] {Typeob.Boolean, Typeob.Boolean}); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(debuggableAttr, new Object[] {(globals.assemblyFlags & AssemblyFlags.EnableJITcompileTracking) != 0, (globals.assemblyFlags & AssemblyFlags.DisableJITcompileOptimizer) != 0})); } this.compilationEvidence = globals.engine.Evidence; this.classwriter = null; }
public void SetEntryPoint(System.Reflection.MethodInfo entryMethod, PEFileKinds fileKind) {}
private static void WriteModuleImpl(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder, PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine, ResourceSection resources, int entryPointToken, Stream stream) { moduleBuilder.ApplyUnmanagedExports(imageFileMachine); moduleBuilder.FixupMethodBodyTokens(); moduleBuilder.ModuleTable.Add(0, moduleBuilder.Strings.Add(moduleBuilder.moduleName), moduleBuilder.Guids.Add(moduleBuilder.ModuleVersionId), 0, 0); if (moduleBuilder.UserStrings.IsEmpty) { // for compat with Ref.Emit, if there aren't any user strings, we add one moduleBuilder.UserStrings.Add(" "); } if (resources != null) { resources.Finish(); } PEWriter writer = new PEWriter(stream); writer.Headers.OptionalHeader.FileAlignment = (uint)moduleBuilder.__FileAlignment; switch (imageFileMachine) { case ImageFileMachine.I386: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_32BIT_MACHINE; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x100000); break; case ImageFileMachine.ARM: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_32BIT_MACHINE; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x100000); break; case ImageFileMachine.AMD64: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE; writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0; writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x400000); writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000; writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000; break; case ImageFileMachine.IA64: writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64; writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE; writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0; writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC; writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x400000); writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000; writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000; break; default: throw new ArgumentOutOfRangeException("imageFileMachine"); } if (fileKind == PEFileKinds.Dll) { writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_DLL; } switch (fileKind) { case PEFileKinds.WindowApplication: writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_GUI; break; default: writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_CUI; break; } writer.Headers.OptionalHeader.DllCharacteristics = (ushort)moduleBuilder.__DllCharacteristics; CliHeader cliHeader = new CliHeader(); cliHeader.Cb = 0x48; cliHeader.MajorRuntimeVersion = 2; cliHeader.MinorRuntimeVersion = moduleBuilder.MDStreamVersion < 0x20000 ? (ushort)0 : (ushort)5; if ((portableExecutableKind & PortableExecutableKinds.ILOnly) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_ILONLY; } if ((portableExecutableKind & PortableExecutableKinds.Required32Bit) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_32BITREQUIRED; } if ((portableExecutableKind & PortableExecutableKinds.Preferred32Bit) != 0) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_32BITREQUIRED | CliHeader.COMIMAGE_FLAGS_32BITPREFERRED; } if (keyPair != null) { cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_STRONGNAMESIGNED; } if (moduleBuilder.IsPseudoToken(entryPointToken)) { entryPointToken = moduleBuilder.ResolvePseudoToken(entryPointToken); } cliHeader.EntryPointToken = (uint)entryPointToken; moduleBuilder.Strings.Freeze(); moduleBuilder.UserStrings.Freeze(); moduleBuilder.Guids.Freeze(); moduleBuilder.Blobs.Freeze(); MetadataWriter mw = new MetadataWriter(moduleBuilder, stream); moduleBuilder.Tables.Freeze(mw); TextSection code = new TextSection(writer, cliHeader, moduleBuilder, ComputeStrongNameSignatureLength(publicKey)); // Export Directory if (code.ExportDirectoryLength != 0) { writer.Headers.OptionalHeader.DataDirectory[0].VirtualAddress = code.ExportDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[0].Size = code.ExportDirectoryLength; } // Import Directory if (code.ImportDirectoryLength != 0) { writer.Headers.OptionalHeader.DataDirectory[1].VirtualAddress = code.ImportDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[1].Size = code.ImportDirectoryLength; } // Import Address Table Directory if (code.ImportAddressTableLength != 0) { writer.Headers.OptionalHeader.DataDirectory[12].VirtualAddress = code.ImportAddressTableRVA; writer.Headers.OptionalHeader.DataDirectory[12].Size = code.ImportAddressTableLength; } // COM Descriptor Directory writer.Headers.OptionalHeader.DataDirectory[14].VirtualAddress = code.ComDescriptorRVA; writer.Headers.OptionalHeader.DataDirectory[14].Size = code.ComDescriptorLength; // Debug Directory if (code.DebugDirectoryLength != 0) { writer.Headers.OptionalHeader.DataDirectory[6].VirtualAddress = code.DebugDirectoryRVA; writer.Headers.OptionalHeader.DataDirectory[6].Size = code.DebugDirectoryLength; } // we need to start by computing the number of sections, because code.PointerToRawData depends on that writer.Headers.FileHeader.NumberOfSections = 1; if (moduleBuilder.initializedData.Length != 0) { // .sdata writer.Headers.FileHeader.NumberOfSections++; } if (resources != null) { // .rsrc writer.Headers.FileHeader.NumberOfSections++; } if (imageFileMachine != ImageFileMachine.ARM) { // .reloc writer.Headers.FileHeader.NumberOfSections++; } SectionHeader text = new SectionHeader(); text.Name = ".text"; text.VirtualAddress = code.BaseRVA; text.VirtualSize = (uint)code.Length; text.PointerToRawData = code.PointerToRawData; text.SizeOfRawData = writer.ToFileAlignment((uint)code.Length); text.Characteristics = SectionHeader.IMAGE_SCN_CNT_CODE | SectionHeader.IMAGE_SCN_MEM_EXECUTE | SectionHeader.IMAGE_SCN_MEM_READ; SectionHeader sdata = new SectionHeader(); sdata.Name = ".sdata"; sdata.VirtualAddress = text.VirtualAddress + writer.ToSectionAlignment(text.VirtualSize); sdata.VirtualSize = (uint)moduleBuilder.initializedData.Length; sdata.PointerToRawData = text.PointerToRawData + text.SizeOfRawData; sdata.SizeOfRawData = writer.ToFileAlignment((uint)moduleBuilder.initializedData.Length); sdata.Characteristics = SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_MEM_WRITE; SectionHeader rsrc = new SectionHeader(); rsrc.Name = ".rsrc"; rsrc.VirtualAddress = sdata.VirtualAddress + writer.ToSectionAlignment(sdata.VirtualSize); rsrc.PointerToRawData = sdata.PointerToRawData + sdata.SizeOfRawData; rsrc.VirtualSize = resources == null ? 0 : (uint)resources.Length; rsrc.SizeOfRawData = writer.ToFileAlignment(rsrc.VirtualSize); rsrc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA; if (rsrc.SizeOfRawData != 0) { // Resource Directory writer.Headers.OptionalHeader.DataDirectory[2].VirtualAddress = rsrc.VirtualAddress; writer.Headers.OptionalHeader.DataDirectory[2].Size = rsrc.VirtualSize; } SectionHeader reloc = new SectionHeader(); reloc.Name = ".reloc"; reloc.VirtualAddress = rsrc.VirtualAddress + writer.ToSectionAlignment(rsrc.VirtualSize); if (imageFileMachine != ImageFileMachine.ARM) { reloc.VirtualSize = ((uint)moduleBuilder.unmanagedExports.Count + 1) * 12; } reloc.PointerToRawData = rsrc.PointerToRawData + rsrc.SizeOfRawData; reloc.SizeOfRawData = writer.ToFileAlignment(reloc.VirtualSize); reloc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_DISCARDABLE; if (reloc.SizeOfRawData != 0) { // Base Relocation Directory writer.Headers.OptionalHeader.DataDirectory[5].VirtualAddress = reloc.VirtualAddress; writer.Headers.OptionalHeader.DataDirectory[5].Size = reloc.VirtualSize; } writer.Headers.OptionalHeader.SizeOfCode = text.SizeOfRawData; writer.Headers.OptionalHeader.SizeOfInitializedData = sdata.SizeOfRawData + rsrc.SizeOfRawData + reloc.SizeOfRawData; writer.Headers.OptionalHeader.SizeOfUninitializedData = 0; writer.Headers.OptionalHeader.SizeOfImage = reloc.VirtualAddress + writer.ToSectionAlignment(reloc.VirtualSize); writer.Headers.OptionalHeader.SizeOfHeaders = text.PointerToRawData; writer.Headers.OptionalHeader.BaseOfCode = code.BaseRVA; writer.Headers.OptionalHeader.BaseOfData = sdata.VirtualAddress; writer.Headers.OptionalHeader.ImageBase = (ulong)moduleBuilder.__ImageBase; if (imageFileMachine == ImageFileMachine.IA64) { // apparently for IA64 AddressOfEntryPoint points to the address of the entry point // (i.e. there is an additional layer of indirection), so we add the offset to the pointer writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA + 0x20; } else if (imageFileMachine != ImageFileMachine.ARM) { writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA; } writer.WritePEHeaders(); writer.WriteSectionHeader(text); if (sdata.SizeOfRawData != 0) { writer.WriteSectionHeader(sdata); } if (rsrc.SizeOfRawData != 0) { writer.WriteSectionHeader(rsrc); } if (reloc.SizeOfRawData != 0) { writer.WriteSectionHeader(reloc); } stream.Seek(text.PointerToRawData, SeekOrigin.Begin); code.Write(mw, sdata.VirtualAddress); if (sdata.SizeOfRawData != 0) { stream.Seek(sdata.PointerToRawData, SeekOrigin.Begin); mw.Write(moduleBuilder.initializedData); } if (rsrc.SizeOfRawData != 0) { stream.Seek(rsrc.PointerToRawData, SeekOrigin.Begin); resources.Write(mw, rsrc.VirtualAddress); } if (reloc.SizeOfRawData != 0) { stream.Seek(reloc.PointerToRawData, SeekOrigin.Begin); code.WriteRelocations(mw); } // file alignment stream.SetLength(reloc.PointerToRawData + reloc.SizeOfRawData); // do the strong naming if (keyPair != null) { StrongName(stream, keyPair, writer.HeaderSize, text.PointerToRawData, code.StrongNameSignatureRVA - text.VirtualAddress + text.PointerToRawData, code.StrongNameSignatureLength); } if (moduleBuilder.symbolWriter != null) { moduleBuilder.WriteSymbolTokenMap(); moduleBuilder.symbolWriter.Close(); } }
internal void SetMain(MethodInfo m, PEFileKinds target, Dictionary<string, string> props, bool noglobbing, Type apartmentAttributeType) { MethodBuilder mainStub = this.GetTypeWrapperFactory().ModuleBuilder.DefineGlobalMethod("main", MethodAttributes.Public | MethodAttributes.Static, Types.Int32, new Type[] { Types.String.MakeArrayType() }); if(apartmentAttributeType != null) { mainStub.SetCustomAttribute(new CustomAttributeBuilder(apartmentAttributeType.GetConstructor(Type.EmptyTypes), new object[0])); } CodeEmitter ilgen = CodeEmitter.Create(mainStub); CodeEmitterLocal rc = ilgen.DeclareLocal(Types.Int32); TypeWrapper startupType = LoadClassByDottedName("ikvm.runtime.Startup"); if(props.Count > 0) { ilgen.Emit(OpCodes.Newobj, JVM.Import(typeof(System.Collections.Generic.Dictionary<string, string>)).GetConstructor(Type.EmptyTypes)); foreach(KeyValuePair<string, string> kv in props) { ilgen.Emit(OpCodes.Dup); ilgen.Emit(OpCodes.Ldstr, kv.Key); ilgen.Emit(OpCodes.Ldstr, kv.Value); if(kv.Value.IndexOf('%') < kv.Value.LastIndexOf('%')) { ilgen.Emit(OpCodes.Call, JVM.Import(typeof(Environment)).GetMethod("ExpandEnvironmentVariables", new Type[] { Types.String })); } ilgen.Emit(OpCodes.Callvirt, JVM.Import(typeof(System.Collections.Generic.Dictionary<string, string>)).GetMethod("Add")); } startupType.GetMethodWrapper("setProperties", "(Lcli.System.Collections.IDictionary;)V", false).EmitCall(ilgen); } ilgen.BeginExceptionBlock(); startupType.GetMethodWrapper("enterMainThread", "()V", false).EmitCall(ilgen); ilgen.Emit(OpCodes.Ldarg_0); if (!noglobbing) { ilgen.Emit(OpCodes.Ldc_I4_0); startupType.GetMethodWrapper("glob", "([Ljava.lang.String;I)[Ljava.lang.String;", false).EmitCall(ilgen); } ilgen.Emit(OpCodes.Call, m); CodeEmitterLabel label = ilgen.DefineLabel(); ilgen.Emit(OpCodes.Leave, label); ilgen.BeginCatchBlock(Types.Exception); LoadClassByDottedName("ikvm.runtime.Util").GetMethodWrapper("mapException", "(Ljava.lang.Throwable;)Ljava.lang.Throwable;", false).EmitCall(ilgen); CodeEmitterLocal exceptionLocal = ilgen.DeclareLocal(Types.Exception); ilgen.Emit(OpCodes.Stloc, exceptionLocal); TypeWrapper threadTypeWrapper = ClassLoaderWrapper.LoadClassCritical("java.lang.Thread"); CodeEmitterLocal threadLocal = ilgen.DeclareLocal(threadTypeWrapper.TypeAsLocalOrStackType); threadTypeWrapper.GetMethodWrapper("currentThread", "()Ljava.lang.Thread;", false).EmitCall(ilgen); ilgen.Emit(OpCodes.Stloc, threadLocal); ilgen.Emit(OpCodes.Ldloc, threadLocal); threadTypeWrapper.GetMethodWrapper("getThreadGroup", "()Ljava.lang.ThreadGroup;", false).EmitCallvirt(ilgen); ilgen.Emit(OpCodes.Ldloc, threadLocal); ilgen.Emit(OpCodes.Ldloc, exceptionLocal); ClassLoaderWrapper.LoadClassCritical("java.lang.ThreadGroup").GetMethodWrapper("uncaughtException", "(Ljava.lang.Thread;Ljava.lang.Throwable;)V", false).EmitCallvirt(ilgen); ilgen.Emit(OpCodes.Ldc_I4_1); ilgen.Emit(OpCodes.Stloc, rc); ilgen.Emit(OpCodes.Leave, label); ilgen.BeginFinallyBlock(); startupType.GetMethodWrapper("exitMainThread", "()V", false).EmitCall(ilgen); ilgen.Emit(OpCodes.Endfinally); ilgen.EndExceptionBlock(); ilgen.MarkLabel(label); ilgen.Emit(OpCodes.Ldloc, rc); ilgen.Emit(OpCodes.Ret); ilgen.DoEmit(); assemblyBuilder.SetEntryPoint(mainStub, target); }
public VsaEngine(bool fast) : base("JScript", "7.0.3300.0", true){ this.alwaysGenerateIL = false; this.autoRef = false; this.doCRS = false; this.doFast = fast; this.cachedPEFileName = ""; this.genDebugInfo = false; this.genStartupClass = true; this.doPrint = false; this.doWarnAsError = false; this.nWarningLevel = 4; this.isCLSCompliant = false; this.versionSafe = false; this.PEFileName = null; this.PEFileKind = PEFileKinds.Dll; this.errorCultureInfo = null; this.libpath = null; this.libpathList = null; this.globalScope = null; this.vsaItems = new VsaItems(this); this.packages = null; this.scopes = null; this.classCounter = 0; this.implicitAssemblies = null; this.implicitAssemblyCache = null; this.cachedTypeLookups = null; this.isEngineRunning = false; this.isEngineCompiled = false; this.isCompilerSet = false; this.isClosed = false; this.runningThread = null; this.compilerGlobals = null; this.globals = null; this.runtimeDirectory = null; Globals.contextEngine = this; this.runtimeAssembly = null; this.typenameTable = null; }
public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) { if(entryMethod == null) { throw new ArgumentNullException("entryMethod"); } if(entryMethod.DeclaringType.Assembly != this) { throw new InvalidOperationException (_("Invalid_EntryNotInAssembly")); } entryPoint = entryMethod; this.fileKind = fileKind; }
internal CompilerGlobals(VsaEngine engine, string assemName, string assemblyFileName, PEFileKinds PEFileKind, bool save, bool run, bool debugOn, bool isCLSCompliant, Version version, Globals globals) { string fileName = null; string dir = null; if (assemblyFileName != null) { try { dir = Path.GetDirectoryName(Path.GetFullPath(assemblyFileName)); } catch (Exception exception) { throw new JSVsaException(JSVsaError.AssemblyNameInvalid, assemblyFileName, exception); } fileName = Path.GetFileName(assemblyFileName); if ((assemName == null) || (string.Empty == assemName)) { assemName = Path.GetFileName(assemblyFileName); if (Path.HasExtension(assemName)) { assemName = assemName.Substring(0, assemName.Length - Path.GetExtension(assemName).Length); } } } if ((assemName == null) || (assemName == string.Empty)) { assemName = "JScriptAssembly"; } if (fileName == null) { if (PEFileKind == PEFileKinds.Dll) { fileName = "JScriptModule.dll"; } else { fileName = "JScriptModule.exe"; } } AssemblyName name = new AssemblyName { CodeBase = assemblyFileName }; if (globals.assemblyCulture != null) { name.CultureInfo = globals.assemblyCulture; } name.Flags = AssemblyNameFlags.None; if ((globals.assemblyFlags & AssemblyFlags.PublicKey) != AssemblyFlags.SideBySideCompatible) { name.Flags = AssemblyNameFlags.PublicKey; } AssemblyFlags flags = globals.assemblyFlags & AssemblyFlags.CompatibilityMask; if (flags == AssemblyFlags.NonSideBySideAppDomain) { name.VersionCompatibility = AssemblyVersionCompatibility.SameDomain; } else if (flags == AssemblyFlags.NonSideBySideProcess) { name.VersionCompatibility = AssemblyVersionCompatibility.SameProcess; } else if (flags == AssemblyFlags.NonSideBySideMachine) { name.VersionCompatibility = AssemblyVersionCompatibility.SameMachine; } else { name.VersionCompatibility = (AssemblyVersionCompatibility) 0; } name.HashAlgorithm = globals.assemblyHashAlgorithm; if (globals.assemblyKeyFileName != null) { try { using (FileStream stream = new FileStream(globals.assemblyKeyFileName, FileMode.Open, FileAccess.Read)) { StrongNameKeyPair pair = new StrongNameKeyPair(stream); if (globals.assemblyDelaySign) { if (stream.Length == 160L) { byte[] buffer = new byte[160]; stream.Seek(0L, SeekOrigin.Begin); stream.Read(buffer, 0, 160); name.SetPublicKey(buffer); } else { name.SetPublicKey(pair.PublicKey); } } else { byte[] publicKey = pair.PublicKey; name.KeyPair = pair; } } goto Label_024E; } catch { globals.assemblyKeyFileNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyFileName); goto Label_024E; } } if (globals.assemblyKeyName != null) { try { StrongNameKeyPair pair2 = new StrongNameKeyPair(globals.assemblyKeyName); byte[] buffer2 = pair2.PublicKey; name.KeyPair = pair2; } catch { globals.assemblyKeyNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyName); } } Label_024E: name.Name = assemName; if (version != null) { name.Version = version; } else if (globals.assemblyVersion != null) { name.Version = globals.assemblyVersion; } AssemblyBuilderAccess reflectionOnly = save ? (run ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Save) : AssemblyBuilderAccess.Run; if (engine.ReferenceLoaderAPI == LoaderAPI.ReflectionOnlyLoadFrom) { reflectionOnly = AssemblyBuilderAccess.ReflectionOnly; } if (globals.engine.genStartupClass) { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, reflectionOnly, dir, globals.engine.Evidence); } else { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, reflectionOnly, dir); } if (save) { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", fileName, debugOn); } else { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", debugOn); } if (isCLSCompliant) { this.module.SetCustomAttribute(new CustomAttributeBuilder(clsCompliantAttributeCtor, new object[] { isCLSCompliant })); } if (debugOn) { ConstructorInfo constructor = Typeob.DebuggableAttribute.GetConstructor(new Type[] { Typeob.Boolean, Typeob.Boolean }); this.assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { (globals.assemblyFlags & AssemblyFlags.EnableJITcompileTracking) != AssemblyFlags.SideBySideCompatible, (globals.assemblyFlags & AssemblyFlags.DisableJITcompileOptimizer) != AssemblyFlags.SideBySideCompatible })); } this.compilationEvidence = globals.engine.Evidence; this.classwriter = null; }
public void SetEntryPoint(System.Reflection.MethodInfo entryMethod, PEFileKinds fileKind) { }
internal CompilerGlobals(String assemName, String assemblyFileName, PEFileKinds PEFileKind, bool save, bool run, bool debugOn, bool isCLSCompliant, Version version, Globals globals) { String moduleFileName = null; String directory = null; //Default has assembly stored in current directory if (assemblyFileName != null) { //The directory is an absolute path where the assembly is written try{ directory = Path.GetDirectoryName(Path.GetFullPath(assemblyFileName)); }catch (Exception e) { throw new VsaException(VsaError.AssemblyNameInvalid, assemblyFileName, e); } //For a single file assembly module filename is set to assembly filename moduleFileName = Path.GetFileName(assemblyFileName); //If simple name is not specified, get it by extracting the basename from assembly name if (null == assemName || String.Empty == assemName) { assemName = Path.GetFileName(assemblyFileName); if (Path.HasExtension(assemName)) { assemName = assemName.Substring(0, assemName.Length - Path.GetExtension(assemName).Length); } } } //Setup default simple assembly name and module name for the case where no assemblyFileName is specified. if (assemName == null || assemName == String.Empty) { assemName = "JScriptAssembly"; } if (moduleFileName == null) { if (PEFileKind == PEFileKinds.Dll) { moduleFileName = "JScriptModule.dll"; } else { moduleFileName = "JScriptModule.exe"; } } AssemblyName assemblyName = new AssemblyName(); assemblyName.CodeBase = assemblyFileName; if (globals.assemblyCulture != null) { assemblyName.CultureInfo = globals.assemblyCulture; } assemblyName.Flags = AssemblyNameFlags.None; if ((globals.assemblyFlags & AssemblyFlags.PublicKey) != 0) { assemblyName.Flags = AssemblyNameFlags.PublicKey; } switch ((AssemblyFlags)(globals.assemblyFlags & AssemblyFlags.CompatibilityMask)) { case AssemblyFlags.NonSideBySideAppDomain: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameDomain; break; case AssemblyFlags.NonSideBySideMachine: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameMachine; break; case AssemblyFlags.NonSideBySideProcess: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameProcess; break; default: assemblyName.VersionCompatibility = (AssemblyVersionCompatibility)0; break; } assemblyName.HashAlgorithm = globals.assemblyHashAlgorithm; if (globals.assemblyKeyFileName != null) { try{ FileStream fs = new FileStream(globals.assemblyKeyFileName, FileMode.Open, FileAccess.Read); StrongNameKeyPair keyPair = new StrongNameKeyPair(fs); if (globals.assemblyDelaySign) { if (fs.Length == 160) { Byte[] pkey = new Byte[160]; fs.Seek(0, SeekOrigin.Begin); int len = fs.Read(pkey, 0, 160); assemblyName.SetPublicKey(pkey); } else { assemblyName.SetPublicKey(keyPair.PublicKey); } } else { assemblyName.KeyPair = keyPair; } }catch (Exception) {} } else if (globals.assemblyKeyName != null) { try{ assemblyName.KeyPair = new StrongNameKeyPair(globals.assemblyKeyName); }catch (Exception) {} } assemblyName.Name = assemName; if (version != null) { assemblyName.Version = version; } else if (globals.assemblyVersion != null) { assemblyName.Version = globals.assemblyVersion; } AssemblyBuilderAccess access = save ? (run ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Save) : AssemblyBuilderAccess.Run; // Supply the evidence to assemblies built for VSA if (globals.engine.genStartupClass) { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, access, directory, globals.engine.Evidence); } else { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, access, directory); } if (save) { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", moduleFileName, debugOn); } else { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", debugOn); } if (isCLSCompliant) { this.module.SetCustomAttribute(new CustomAttributeBuilder(clsCompliantAttributeCtor, new Object[] { isCLSCompliant })); } if (debugOn) { ConstructorInfo debuggableAttr = typeof(DebuggableAttribute).GetConstructor(new Type[] { Typeob.Boolean, Typeob.Boolean }); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(debuggableAttr, new Object[] { (globals.assemblyFlags & AssemblyFlags.EnableJITcompileTracking) != 0, (globals.assemblyFlags & AssemblyFlags.DisableJITcompileOptimizer) != 0 })); } this.classwriter = null; }
public VsaEngine(bool fast) : base("JScript", VsaEngine.engineVersion, true){ this.alwaysGenerateIL = false; this.autoRef = false; this.doCRS = false; this.doFast = fast; this.genDebugInfo = false; this.genStartupClass = true; this.doPrint = false; this.doWarnAsError = false; this.nWarningLevel = 4; this.isCLSCompliant = false; this.versionSafe = false; this.PEFileName = null; this.PEFileKind = PEFileKinds.Dll; this.PEKindFlags = PortableExecutableKinds.ILOnly; this.PEMachineArchitecture = ImageFileMachine.I386; this.ReferenceLoaderAPI = LoaderAPI.LoadFrom; this.errorCultureInfo = null; this.libpath = null; this.libpathList = null; this.globalScope = null; this.vsaItems = new VsaItems(this); this.packages = null; this.scopes = null; this.classCounter = 0; this.implicitAssemblies = null; this.implicitAssemblyCache = null; this.cachedTypeLookups = null; this.isEngineRunning = false; this.isEngineCompiled = false; this.isCompilerSet = false; this.isClosed = false; this.runningThread = null; this.compilerGlobals = null; this.globals = null; this.runtimeDirectory = null; Globals.contextEngine = this; this.runtimeAssembly = null; this.typenameTable = null; }
/// <summary>Sets the entry point for this assembly and defines the type of the portable executable (PE file) being built.</summary><param name="entryMethod">A reference to the method that represents the entry point for this dynamic assembly. </param><param name="fileKind">The type of the assembly executable being built. </param><exception cref="T:System.ArgumentNullException"><paramref name="entryMethod" /> is null. </exception><exception cref="T:System.InvalidOperationException"><paramref name="entryMethod" /> is not contained within this assembly. </exception><exception cref="T:System.Security.SecurityException">The caller does not have the required permission. </exception> public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) { throw new NotImplementedException(); }
/// <include file='doc\AssemblyBuilder.uex' path='docs/doc[@for="AssemblyBuilder.SetEntryPoint1"]/*' /> public void SetEntryPoint( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. { CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit); try { Enter(); BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint"); if (entryMethod == null) throw new ArgumentNullException("entryMethod"); // Module tmpModule = entryMethod.InternalReflectedClass(true).Module; if (!(tmpModule is ModuleBuilder && this.Equals(tmpModule.Assembly))) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly")); m_assemblyData.m_entryPointModule = (ModuleBuilder) tmpModule; m_assemblyData.m_entryPointMethod = entryMethod; m_assemblyData.m_peFileKind = fileKind; m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethod); } finally { Exit(); } }
public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind) { if (entryMethod == null) throw new ArgumentNullException ("entryMethod"); if (entryMethod.DeclaringType.Assembly != this) throw new InvalidOperationException ("Entry method is not defined in the same assembly."); entry_point = entryMethod; pekind = fileKind; }
internal CompilerGlobals(VsaEngine engine, string assemName, string assemblyFileName, PEFileKinds PEFileKind, bool save, bool run, bool debugOn, bool isCLSCompliant, Version version, Globals globals) { string fileName = null; string dir = null; if (assemblyFileName != null) { try { dir = Path.GetDirectoryName(Path.GetFullPath(assemblyFileName)); } catch (Exception exception) { throw new JSVsaException(JSVsaError.AssemblyNameInvalid, assemblyFileName, exception); } fileName = Path.GetFileName(assemblyFileName); if ((assemName == null) || (string.Empty == assemName)) { assemName = Path.GetFileName(assemblyFileName); if (Path.HasExtension(assemName)) { assemName = assemName.Substring(0, assemName.Length - Path.GetExtension(assemName).Length); } } } if ((assemName == null) || (assemName == string.Empty)) { assemName = "JScriptAssembly"; } if (fileName == null) { if (PEFileKind == PEFileKinds.Dll) { fileName = "JScriptModule.dll"; } else { fileName = "JScriptModule.exe"; } } AssemblyName name = new AssemblyName { CodeBase = assemblyFileName }; if (globals.assemblyCulture != null) { name.CultureInfo = globals.assemblyCulture; } name.Flags = AssemblyNameFlags.None; if ((globals.assemblyFlags & AssemblyFlags.PublicKey) != AssemblyFlags.SideBySideCompatible) { name.Flags = AssemblyNameFlags.PublicKey; } AssemblyFlags flags = globals.assemblyFlags & AssemblyFlags.CompatibilityMask; if (flags == AssemblyFlags.NonSideBySideAppDomain) { name.VersionCompatibility = AssemblyVersionCompatibility.SameDomain; } else if (flags == AssemblyFlags.NonSideBySideProcess) { name.VersionCompatibility = AssemblyVersionCompatibility.SameProcess; } else if (flags == AssemblyFlags.NonSideBySideMachine) { name.VersionCompatibility = AssemblyVersionCompatibility.SameMachine; } else { name.VersionCompatibility = (AssemblyVersionCompatibility)0; } name.HashAlgorithm = globals.assemblyHashAlgorithm; if (globals.assemblyKeyFileName != null) { try { using (FileStream stream = new FileStream(globals.assemblyKeyFileName, FileMode.Open, FileAccess.Read)) { StrongNameKeyPair pair = new StrongNameKeyPair(stream); if (globals.assemblyDelaySign) { if (stream.Length == 160L) { byte[] buffer = new byte[160]; stream.Seek(0L, SeekOrigin.Begin); stream.Read(buffer, 0, 160); name.SetPublicKey(buffer); } else { name.SetPublicKey(pair.PublicKey); } } else { byte[] publicKey = pair.PublicKey; name.KeyPair = pair; } } goto Label_024E; } catch { globals.assemblyKeyFileNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyFileName); goto Label_024E; } } if (globals.assemblyKeyName != null) { try { StrongNameKeyPair pair2 = new StrongNameKeyPair(globals.assemblyKeyName); byte[] buffer2 = pair2.PublicKey; name.KeyPair = pair2; } catch { globals.assemblyKeyNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyName); } } Label_024E: name.Name = assemName; if (version != null) { name.Version = version; } else if (globals.assemblyVersion != null) { name.Version = globals.assemblyVersion; } AssemblyBuilderAccess reflectionOnly = save ? (run ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Save) : AssemblyBuilderAccess.Run; if (engine.ReferenceLoaderAPI == LoaderAPI.ReflectionOnlyLoadFrom) { reflectionOnly = AssemblyBuilderAccess.ReflectionOnly; } if (globals.engine.genStartupClass) { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, reflectionOnly, dir, globals.engine.Evidence); } else { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, reflectionOnly, dir); } if (save) { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", fileName, debugOn); } else { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", debugOn); } if (isCLSCompliant) { this.module.SetCustomAttribute(new CustomAttributeBuilder(clsCompliantAttributeCtor, new object[] { isCLSCompliant })); } if (debugOn) { ConstructorInfo constructor = Typeob.DebuggableAttribute.GetConstructor(new Type[] { Typeob.Boolean, Typeob.Boolean }); this.assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { (globals.assemblyFlags & AssemblyFlags.EnableJITcompileTracking) != AssemblyFlags.SideBySideCompatible, (globals.assemblyFlags & AssemblyFlags.DisableJITcompileOptimizer) != AssemblyFlags.SideBySideCompatible })); } this.compilationEvidence = globals.engine.Evidence; this.classwriter = null; }
public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) { lock (this.SyncRoot) { this.SetEntryPointNoLock(entryMethod, fileKind); } }
public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) => throw new PlatformNotSupportedException();
internal void SetEntryPoint(MethodInfo mi, PEFileKinds kind) { _myAssembly.SetEntryPoint(mi, kind); }
private void SetEntryPointNoLock(MethodInfo entryMethod, PEFileKinds fileKind) { if (entryMethod == null) { throw new ArgumentNullException("entryMethod"); } Module module = entryMethod.Module; if ((module == null) || !this.InternalAssembly.Equals(module.Assembly)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly")); } this.m_assemblyData.m_entryPointMethod = entryMethod; this.m_assemblyData.m_peFileKind = fileKind; ModuleBuilder builder = module as ModuleBuilder; if (builder != null) { this.m_assemblyData.m_entryPointModule = builder; } else { this.m_assemblyData.m_entryPointModule = this.GetModuleBuilder((InternalModuleBuilder) module); } MethodToken methodToken = this.m_assemblyData.m_entryPointModule.GetMethodToken(entryMethod); this.m_assemblyData.m_entryPointModule.SetEntryPoint(methodToken); }