Exemple #1
0
 private static byte[] EmitHelloWorldConsoleExeAssembly(PortableExecutableKinds peKind, ImageFileMachine machine)
 {
     byte[] bytes;
     var asmName = new AssemblyName { Name = "Dummy" + Guid.NewGuid() };
     var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
         asmName,
         System.Reflection.Emit.AssemblyBuilderAccess.Save);
     var modBuilder = asmBuilder.DefineDynamicModule(asmName.Name, asmName.Name + ".exe");
     var programTypeBuilder = modBuilder.DefineType("Program");
     var mainMethodBuilder = programTypeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), Type.EmptyTypes);
     var il = mainMethodBuilder.GetILGenerator();
     il.EmitWriteLine("Hello, World!");
     il.Emit(OpCodes.Ret);
     asmBuilder.SetEntryPoint(mainMethodBuilder);
     programTypeBuilder.CreateType();
     asmBuilder.Save(asmName.Name + ".exe", peKind, machine);
     try
     {
         bytes = File.ReadAllBytes(asmName.Name + ".exe");
     }
     finally
     {
         File.Delete(asmName.Name);
     }
     return bytes;
 }
        public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            peKind = 0;
            if ((cliHeader.Flags & CliHeader.COMIMAGE_FLAGS_ILONLY) != 0)
            {
                peKind |= PortableExecutableKinds.ILOnly;
            }
            switch (cliHeader.Flags & (CliHeader.COMIMAGE_FLAGS_32BITREQUIRED | CliHeader.COMIMAGE_FLAGS_32BITPREFERRED))
            {
            case CliHeader.COMIMAGE_FLAGS_32BITREQUIRED:
                peKind |= PortableExecutableKinds.Required32Bit;
                break;

            case CliHeader.COMIMAGE_FLAGS_32BITREQUIRED | CliHeader.COMIMAGE_FLAGS_32BITPREFERRED:
                peKind |= PortableExecutableKinds.Preferred32Bit;
                break;

            default:
                // COMIMAGE_FLAGS_32BITPREFERRED by itself is illegal, so we ignore it
                // (not setting any flag is ok)
                break;
            }
            if (peFile.OptionalHeader.Magic == IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC)
            {
                peKind |= PortableExecutableKinds.PE32Plus;
            }

            machine = (ImageFileMachine)peFile.FileHeader.Machine;
        }
		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);
			}
		}
Exemple #4
0
        internal AssemblyGen(AssemblyName name, string outDir, string outFileExtension, bool isDebuggable,
                             PortableExecutableKinds peKind, ImageFileMachine machine)
        {
            ContractUtils.RequiresNotNull(name, "name");

#if SILVERLIGHT  // AssemblyBuilderAccess.RunAndSave, Environment.CurrentDirectory
            _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
            _myModule   = _myAssembly.DefineDynamicModule(name.Name, isDebuggable);
#else
            if (outFileExtension == null)
            {
                outFileExtension = ".dll";
            }

            if (outDir != null)
            {
                try {
                    outDir = Path.GetFullPath(outDir);
                } catch (Exception) {
                    throw Error.InvalidOutputDir();
                }
                try {
                    Path.Combine(outDir, name.Name + outFileExtension);
                } catch (ArgumentException) {
                    throw Error.InvalidAsmNameOrExtension();
                }

                _outFileName = name.Name + outFileExtension;
                _outDir      = outDir;
            }

            // mark the assembly transparent so that it works in partial trust:
            CustomAttributeBuilder[] attributes = new CustomAttributeBuilder[] {
                new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[0])
            };

            if (outDir != null)
            {
                _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, outDir,
                                                                            null, null, null, null, false, attributes);

                _myModule = _myAssembly.DefineDynamicModule(name.Name, _outFileName, isDebuggable);
            }
            else
            {
                _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run, attributes);
                _myModule   = _myAssembly.DefineDynamicModule(name.Name, isDebuggable);
            }

            _myAssembly.DefineVersionInfoResource();
#endif
            _machine      = machine;
            _peKind       = peKind;
            _isDebuggable = isDebuggable;

            if (isDebuggable)
            {
                SetDebuggableAttributes();
            }
        }
Exemple #5
0
        private static string SearchDdkDirForCdb(ImageFileMachine architecture)
        {
            string path = null;

            try
            {
                string ddkFolder = System.IO.Path.Combine(System.IO.Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)), DdkFolder);
                if (Directory.Exists(ddkFolder))
                {
                    DirectoryInfo ddkFolderInfo = new DirectoryInfo(ddkFolder);
                    FileInfo[]    candidates    = ddkFolderInfo.GetFiles("cdb.exe", SearchOption.AllDirectories);

                    if (candidates.Length > 0)
                    {
                        for (int i = candidates.Length - 1; i >= 0; i--)
                        {
                            if (ClientUtils.VerifyArchitecture(architecture, candidates[i].FullName))
                            {
                                path = candidates[i].FullName;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                               "SearchDdkDirForCdb Failed",
                                               ex);
            }

            return(path);
        }
Exemple #6
0
 private static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm)
 {
     if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus)
     {
         ImageFileMachine imageFileMachine = ifm;
         if (imageFileMachine != ImageFileMachine.I386)
         {
             if (imageFileMachine == ImageFileMachine.IA64)
             {
                 return(ProcessorArchitecture.IA64);
             }
             if (imageFileMachine == ImageFileMachine.AMD64)
             {
                 return(ProcessorArchitecture.Amd64);
             }
         }
         else if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly)
         {
             return(ProcessorArchitecture.MSIL);
         }
     }
     else if (ifm == ImageFileMachine.I386)
     {
         if ((pek & PortableExecutableKinds.Required32Bit) != PortableExecutableKinds.Required32Bit && (pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly)
         {
             return(ProcessorArchitecture.MSIL);
         }
         return(ProcessorArchitecture.X86);
     }
     return(ProcessorArchitecture.None);
 }
Exemple #7
0
 public override void GetPEKind(
     out PortableExecutableKinds peKind,
     out ImageFileMachine machine
     )
 {
     ModuleHandle.GetPEKind(this, out peKind, out machine);
 }
        private void CheckCompatibility()
        {
            // If reference is agnostic, then compatible
            PortableExecutableKinds RefPEKindFlags;
            ImageFileMachine        RefPEMachineArchitecture;

            this.assembly.ManifestModule.GetPEKind(out RefPEKindFlags, out RefPEMachineArchitecture);

            if (RefPEMachineArchitecture == ImageFileMachine.I386 &&
                PortableExecutableKinds.ILOnly == (RefPEKindFlags & (PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit)))
            {
                return;
            }

            // Warn if building an agnostic assembly, but referenced assembly is not.
            PortableExecutableKinds PEKindFlags           = engine.PEKindFlags;
            ImageFileMachine        PEMachineArchitecture = engine.PEMachineArchitecture;

            if (PEMachineArchitecture == ImageFileMachine.I386 &&
                PortableExecutableKinds.ILOnly == (PEKindFlags & (PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit)))
            {
                // We are agnostic, but the reference is not. Do not emit a warning - this is a very common
                // case. Many of the system libraries are platform specific.
                return;
            }

            // Warning if architectures don't match.
            if (RefPEMachineArchitecture != PEMachineArchitecture)
            {
                JScriptException e = new JScriptException(JSError.IncompatibleAssemblyReference);
                e.value = this.assemblyName;
                this.engine.OnCompilerError(e);
            }
        }
Exemple #9
0
        public sealed override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            PEHeaders peHeaders   = PEReader.PEHeaders;
            PEMagic   peMagic     = peHeaders.PEHeader.Magic;
            Machine   coffMachine = peHeaders.CoffHeader.Machine;
            CorFlags  corFlags    = peHeaders.CorHeader.Flags;

            peKind = default;
            if ((corFlags & CorFlags.ILOnly) != 0)
            {
                peKind |= PortableExecutableKinds.ILOnly;
            }

            if ((corFlags & CorFlags.Prefers32Bit) != 0)
            {
                peKind |= PortableExecutableKinds.Preferred32Bit;
            }
            else if ((corFlags & CorFlags.Requires32Bit) != 0)
            {
                peKind |= PortableExecutableKinds.Required32Bit;
            }

            if (peMagic == PEMagic.PE32Plus)
            {
                peKind |= PortableExecutableKinds.PE32Plus;
            }

            machine = (ImageFileMachine)coffMachine;
        }
Exemple #10
0
 public void Save(String assemblyFileName,
                  PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
 {
     lock (SyncRoot)
     {
         SaveNoLock(assemblyFileName, portableExecutableKind, imageFileMachine);
     }
 }
 internal void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
 {
     if (value == IntPtr.Zero)
     {
         throw new ArgumentNullException(String.Empty, "Invalid handle");
     }
     Module.GetPEKind(value, out peKind, out machine);
 }
Exemple #12
0
        internal AssemblyGen(AssemblyName name, string outDir, string outFileExtension, bool isDebuggable,
            PortableExecutableKinds peKind, ImageFileMachine machine) {

            ContractUtils.RequiresNotNull(name, "name");

#if SILVERLIGHT  // AssemblyBuilderAccess.RunAndSave, Environment.CurrentDirectory
            _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
            _myModule = _myAssembly.DefineDynamicModule(name.Name, isDebuggable);
#else
            if (outFileExtension == null) {
                outFileExtension = ".dll";
            }

            if (outDir != null) {
                try {
                    outDir = Path.GetFullPath(outDir);
                } catch (Exception) {
                    throw Error.InvalidOutputDir();
                }
                try {
                    Path.Combine(outDir, name.Name + outFileExtension);
                } catch (ArgumentException) {
                    throw Error.InvalidAsmNameOrExtension();
                }

                _outFileName = name.Name + outFileExtension;
                _outDir = outDir;
            }

            // mark the assembly transparent so that it works in partial trust:
            CustomAttributeBuilder[] attributes = new CustomAttributeBuilder[] { 
                new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[0])
            };

            if (outDir != null) {
#if CLR4
                _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, outDir, false, attributes);
#else
                //The API DefineDynamicAssembly is obsolete in Dev10.
                _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, outDir, 
                    null, null, null, null, false, attributes);
#endif
                _myModule = _myAssembly.DefineDynamicModule(name.Name, _outFileName, isDebuggable);
            } else {
                _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run, attributes);
                _myModule = _myAssembly.DefineDynamicModule(name.Name, isDebuggable);
            }

            _myAssembly.DefineVersionInfoResource();
#endif
            _machine = machine;
            _peKind = peKind;
            _isDebuggable = isDebuggable;

            if (isDebuggable) {
                SetDebuggableAttributes();
            }
        }
Exemple #13
0
        public static string GetCdbPath(ImageFileMachine architecture)
        {
            string path = null;

            switch (architecture)
            {
            case ImageFileMachine.AMD64:
                if (ClientUtils.VerifyArchitecture(architecture, Cdb64on64Default))
                {
                    path = Cdb64on64Default;
                }
                else if (ClientUtils.VerifyArchitecture(architecture, Cdb64on64Default2))
                {
                    path = Cdb64on64Default2;
                }
                else
                {
                    path = SearchDdkDirForCdb(architecture);
                }
                break;

            case ImageFileMachine.I386:
                if (SystemInformation.Is64BitSystem())
                {
                    if (ClientUtils.VerifyArchitecture(architecture, Cdb32on64Default))
                    {
                        path = Cdb32on64Default;
                    }
                    else
                    {
                        path = SearchDdkDirForCdb(architecture);
                    }
                }
                else
                {
                    if (ClientUtils.VerifyArchitecture(architecture, Cdb32on32Default))
                    {
                        path = Cdb32on32Default;
                    }
                    else if (ClientUtils.VerifyArchitecture(architecture, Cdb32on32Default2))
                    {
                        path = Cdb32on32Default2;
                    }
                    else
                    {
                        path = SearchDdkDirForCdb(architecture);
                    }
                }
                break;

            case ImageFileMachine.IA64:
            default:
                // not supported
                break;
            }

            return(path);
        }
Exemple #14
0
        internal static ProcessorArchitecture CalculateProcArchIndex(
            PortableExecutableKinds pek,
            ImageFileMachine ifm,
            AssemblyNameFlags flags
            )
        {
            if (((uint)flags & 0xF0) == 0x70)
            {
                return(ProcessorArchitecture.None);
            }

            if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus)
            {
                switch (ifm)
                {
                case ImageFileMachine.IA64:
                    return(ProcessorArchitecture.IA64);

                case ImageFileMachine.AMD64:
                    return(ProcessorArchitecture.Amd64);

                case ImageFileMachine.I386:
                    if (
                        (pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly
                        )
                    {
                        return(ProcessorArchitecture.MSIL);
                    }
                    break;
                }
            }
            else
            {
                if (ifm == ImageFileMachine.I386)
                {
                    if (
                        (pek & PortableExecutableKinds.Required32Bit)
                        == PortableExecutableKinds.Required32Bit
                        )
                    {
                        return(ProcessorArchitecture.X86);
                    }

                    if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly)
                    {
                        return(ProcessorArchitecture.MSIL);
                    }

                    return(ProcessorArchitecture.X86);
                }
                if (ifm == ImageFileMachine.ARM)
                {
                    return(ProcessorArchitecture.Arm);
                }
            }
            return(ProcessorArchitecture.None);
        }
Exemple #15
0
        public void Save(AssemblyBuilder ass, string filename, ImageFileMachine machineKind)
        {
#if !NETCOREAPP2_1_OR_GREATER
            ass.Save(filename, PortableExecutableKinds.ILOnly, machineKind);
#elif LOKAD
            var gen = new Lokad.ILPack.AssemblyGenerator();
            gen.GenerateAssembly(ass, filename);
#endif
        }
Exemple #16
0
        internal void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            int num;
            int num2;

            this._GetPEKind(out num, out num2);
            peKind  = (PortableExecutableKinds)num;
            machine = (ImageFileMachine)num2;
        }
Exemple #17
0
        public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            RuntimeModule module = this as RuntimeModule;

            if (module != null)
            {
                module.GetPEKind(out peKind, out machine);
            }
            throw new NotImplementedException();
        }
Exemple #18
0
 public static int GetSize(ImageFileMachine arch)
 {
     if (arch == ImageFileMachine.ARM)
     {
         return(ARMImageRuntimeFunctionEntry.GetSize());
     }
     else
     {
         return(AMD64ImageRuntimeFunctionEntry.GetSize());
     }
 }
Exemple #19
0
        public static bool VerifyArchitecture(ImageFileMachine architecture, string exePath)
        {
            bool matches = false;

            if (exePath == null)
            {
                return(false);
            }

            try
            {
                if (File.Exists(exePath))
                {
                    int machineType = 0;

                    using (FileStream fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        BinaryReader br = new BinaryReader(fs);

                        fs.Seek(0x3c, SeekOrigin.Begin);
                        int peOffset = br.ReadInt32();
                        fs.Seek(peOffset, SeekOrigin.Begin);
                        uint peHead = br.ReadUInt32();
                        if (peHead == 0x00004550)
                        {
                            machineType = br.ReadUInt16();
                        }
                    }

                    switch (architecture)
                    {
                    case ImageFileMachine.AMD64:
                        matches = machineType == 0x8664;
                        break;

                    case ImageFileMachine.I386:
                        matches = machineType == 0x14c;
                        break;

                    default:
                        // not supported
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                               "VerifyArchitecture Failed",
                                               ex);
            }

            return(matches);
        }
Exemple #20
0
 public static RuntimeFunctionEntry ReadFrom(BinaryReader r, ImageFileMachine arch)
 {
     if (arch == ImageFileMachine.ARM)
     {
         return(ARMImageRuntimeFunctionEntry.ReadFrom(r));
     }
     else
     {
         return(AMD64ImageRuntimeFunctionEntry.ReadFrom(r));
     }
 }
Exemple #21
0
        //------------------------------------------------------------
        // CAsmLink::AddImport (sscli)
        //------------------------------------------------------------
        //virtual internal HRESULT AddImport(
        //    mdAssembly AssemblyID,
        //    mdToken ImportToken,
        //    DWORD dwFlags,
        //    mdFile * pFileToken)
        //{
        //    // If we have already emitted the manifest, and then we import
        //    // a file with a CA that maps to an assembly option, we're in trouble!
        //    ASSERT(m_bInited && !m_bAssemblyEmitted && !m_bPreClosed && !m_bManifestEmitted);
        //
        //    HRESULT hr;
        //    CFile *file = NULL;
        //    if (TypeFromToken(ImportToken) == mdtModule) {
        //        ASSERT(RidFromToken(ImportToken) < m_pModules->CountFiles());
        //        hr = m_pModules->GetFile( ImportToken, &file);
        //    } else {
        //        ASSERT(TypeFromToken(ImportToken) == mdtAssemblyRef && RidFromToken(ImportToken) < m_pImports->CountFiles());
        //        hr = m_pImports->GetFile( ImportToken, &file);
        //    }
        //    if (FAILED(hr))
        //        return hr;
        //    ASSERT(file != NULL);
        //    if (FAILED(hr = m_pAssem->AddFile(file, dwFlags, pFileToken)))
        //        return hr;
        //    else if (AssemblyID == AssemblyIsUBM) {
        //        if (pFileToken)
        //            *pFileToken = ImportToken;
        //        return S_FALSE;
        //    }
        //    ASSERT(AssemblyID == TokenFromRid(mdtAssembly, 1));
        //    if (FAILED(hr = m_pModules->RemoveFile( ImportToken)))
        //        return hr;
        //    if (FAILED(hr = file->ImportFile( NULL, m_pAssem)))
        //        return hr;
        //    return file->ImportResources(m_pAssem);
        //}

        // virtual internal HRESULT  GetScope(mdAssembly AssemblyID, mdToken FileToken, DWORD dwScope, IMetaDataImport** ppImportScope);
        // virtual internal HRESULT  GetScope2(mdAssembly AssemblyID, mdToken FileToken, DWORD dwScope, IMetaDataImport2** ppImportScope);
        // virtual internal HRESULT  GetAssemblyRefHash(mdToken FileToken, const void** ppvHash, DWORD* pcbHash);
        // virtual internal HRESULT  GetPublicKeyToken(LPCWSTR pszKeyFile, LPCWSTR pszKeyContainer, void * pvPublicKeyToken, DWORD * pcbPublicKeyToken);

        //------------------------------------------------------------
        // CAsmLink.SetPEKind (1)
        //
        /// <summary>
        /// Set PE kind and machin of a given CAssemblyBuilder instance.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="peKind"></param>
        /// <param name="machine"></param>
        /// <returns></returns>
        //------------------------------------------------------------
        virtual internal bool SetPEKind(
            CAssemblyBuilderEx builder,
            PortableExecutableKinds peKind,
            ImageFileMachine machine)
        {
            if (builder == null)
            {
                return(false);
            }
            builder.SetPEKind(peKind, machine);
            return(true);
        }
Exemple #22
0
        public string Save(PortableExecutableKinds peKind, ImageFileMachine machine)
        {
            if (!_created)
            {
                throw new InvalidOperationException("The Assembly has not been created.");
            }

            var path = _graph.FileName;

            _graph.Builder.Save(path, peKind, machine);

            return(path);
        }
Exemple #23
0
        protected override void SaveModule(PortableExecutableKinds pekind, ImageFileMachine machine)
        {
            try {
                var module_only     = typeof(AssemblyBuilder).GetProperty("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                var set_module_only = module_only.GetSetMethod(true);

                set_module_only.Invoke(Builder, new object[] { true });
            } catch {
                base.SaveModule(pekind, machine);
            }

            Builder.Save(file_name, pekind, machine);
        }
Exemple #24
0
        public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            // This API was made virtual in V4. Code compiled against V2 might use
            // "call" rather than "callvirt" to call it.
            // This makes sure those code still works.
            RuntimeModule rtModule = this as RuntimeModule;

            if (rtModule != null)
            {
                rtModule.GetPEKind(out peKind, out machine);
            }

            throw new NotImplementedException();
        }
Exemple #25
0
        public byte[] SaveAndGetBytes(PortableExecutableKinds peKind, ImageFileMachine machine, bool delete = false)
        {
            if (!_created)
            {
                throw new InvalidOperationException("The Assembly has not been created.");
            }

            byte[] outBytes = null;

            //string oldDir = null;
            //if (delete)
            //{
            //    oldDir = Environment.CurrentDirectory;
            //    Environment.CurrentDirectory = Path.GetTempPath();
            //}

            string path = Save(peKind, machine);

            try
            {
                using (var file = File.OpenRead(path))
                {
                    outBytes = new byte[file.Length];
                    file.Read(outBytes, 0, outBytes.Length);
                }
            }
            finally
            {
                if (delete)
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }


                    //Environment.CurrentDirectory = oldDir;
                }

                //Always delete PDB, it is not useful
                path = _graph.AssemblyName.Name + ".pdb";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }

            return(outBytes);
        }
 public void Save(String assemblyFileName,
                  PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
 {
     if (m_assemblyData.m_isSynchronized)
     {
         lock (m_assemblyData)
         {
             SaveNoLock(assemblyFileName, portableExecutableKind, imageFileMachine);
         }
     }
     else
     {
         SaveNoLock(assemblyFileName, portableExecutableKind, imageFileMachine);
     }
 }
Exemple #27
0
        private static bool IsRegSvrNeeded(string filename)
        {
            // If we are running a 64 bit process and have a 32 bit binary, we cannot load the
            //  library within the current process and must let regsvr32 handle the call

            ImageFileMachine binaryArchitecture = GetBinaryArchitecture(filename);
            string           architecture       = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE").ToUpperInvariant();

            // X86 PROCESS_ARCH is represented by I386 in the enum
            if (architecture == "X86")
            {
                architecture = "I386";
            }

            return(architecture != binaryArchitecture.ToString().ToUpperInvariant());
        }
Exemple #28
0
		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);
			}
		}
Exemple #29
0
        public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            peKind = 0;
            if ((cliHeader.Flags & CliHeader.COMIMAGE_FLAGS_ILONLY) != 0)
            {
                peKind |= PortableExecutableKinds.ILOnly;
            }
            if ((cliHeader.Flags & CliHeader.COMIMAGE_FLAGS_32BITREQUIRED) != 0)
            {
                peKind |= PortableExecutableKinds.Required32Bit;
            }
            if (peFile.OptionalHeader.Magic == IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC)
            {
                peKind |= PortableExecutableKinds.PE32Plus;
            }

            machine = (ImageFileMachine)peFile.FileHeader.Machine;
        }
Exemple #30
0
 public AssemblyInfo(
     string fileName,
     string fullPath,
     string fileExtension,
     PortableExecutableKinds portableExecutableKinds,
     ImageFileMachine imageFileMachine,
     IEnumerable <AssemblyName> referencedAssemblies,
     string imageRuntimeVersion
     )
 {
     this.FileName                = fileName;
     this.FullPath                = fullPath;
     this.FileExtension           = fileExtension;
     this.PortableExecutableKinds = portableExecutableKinds;
     this.ImageFileMachine        = imageFileMachine;
     this.ReferencedAssemblies    = referencedAssemblies;
     this.ImageRuntimeVersion     = imageRuntimeVersion;
 }
Exemple #31
0
 private static byte[] EmitLibraryAssembly(PortableExecutableKinds peKind, ImageFileMachine machine)
 {
     byte[] bytes;
     var asmName = new AssemblyName { Name = "Dummy" + Guid.NewGuid() };
     var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
         asmName,
         System.Reflection.Emit.AssemblyBuilderAccess.Save);
     asmBuilder.Save(asmName.Name, peKind, machine);
     try
     {
         bytes = File.ReadAllBytes(asmName.Name);
     }
     finally
     {
         File.Delete(asmName.Name);
     }
     return bytes;
 }
Exemple #32
0
 public CompilerOptions(){
   this.autoRef = true;
   this.PEFileKind = PEFileKinds.ConsoleApplication;
   this.PEKindFlags = PortableExecutableKinds.ILOnly;
   this.PEMachineArchitecture = ImageFileMachine.I386;
   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 AssemblyGen(string moduleName, string outDir, string outFile, bool emitDebugInfo,
                           PortableExecutableKinds peKind, ImageFileMachine machine)
        {
            Debug.WriteLine("===============outFileName=" + outFile);
            this.outFileName   = outFile;
            this.outDir        = outDir;
            this.emitDebugInfo = emitDebugInfo;
            this.peKind        = peKind;
            this.machine       = machine;

            AssemblyName asmname = new AssemblyName();

            AppDomain domain = System.Threading.Thread.GetDomain();

            asmname.Name = Path.GetFileNameWithoutExtension(outFileName);

            if (outFileName == null)
            {
                myAssembly = domain.DefineDynamicAssembly(
                    asmname,
                    AssemblyBuilderAccess.Run,
                    outDir,
                    null);
                myModule = myAssembly.DefineDynamicModule(moduleName);
            }
            else
            {
                myAssembly = domain.DefineDynamicAssembly(
                    asmname,
                    AssemblyBuilderAccess.RunAndSave,
                    outDir,
                    null);
                myModule = myAssembly.DefineDynamicModule(outFileName, outFileName, emitDebugInfo);
            }

            myAssembly.DefineVersionInfoResource();

            if (emitDebugInfo)
            {
                SetDebuggableAttributes();
            }
        }
        private void CheckCompatibility()
        {
            PortableExecutableKinds kinds;
            ImageFileMachine        machine;

            this.assembly.ManifestModule.GetPEKind(out kinds, out machine);
            if ((machine != ImageFileMachine.I386) || (PortableExecutableKinds.ILOnly != (kinds & (PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly))))
            {
                PortableExecutableKinds pEKindFlags           = base.engine.PEKindFlags;
                ImageFileMachine        pEMachineArchitecture = base.engine.PEMachineArchitecture;
                if (((pEMachineArchitecture != ImageFileMachine.I386) || (PortableExecutableKinds.ILOnly != (pEKindFlags & (PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly)))) && (machine != pEMachineArchitecture))
                {
                    JScriptException se = new JScriptException(JSError.IncompatibleAssemblyReference)
                    {
                        value = this.assemblyName
                    };
                    base.engine.OnCompilerError(se);
                }
            }
        }
Exemple #35
0
        private static byte[] EmitLibraryAssembly(PortableExecutableKinds peKind, ImageFileMachine machine)
        {
            byte[] bytes;
            var    asmName = new AssemblyName {
                Name = "Dummy" + Guid.NewGuid()
            };
            var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                asmName,
                System.Reflection.Emit.AssemblyBuilderAccess.Save);

            asmBuilder.Save(asmName.Name, peKind, machine);
            try
            {
                bytes = File.ReadAllBytes(asmName.Name);
            }
            finally
            {
                File.Delete(asmName.Name);
            }
            return(bytes);
        }
Exemple #36
0
		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);
			}
		}
 internal static System.Reflection.ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags)
 {
     if ((flags & 240) != 0x70)
     {
         if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus)
         {
             ImageFileMachine machine = ifm;
             if (machine == ImageFileMachine.I386)
             {
                 if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly)
                 {
                     return(System.Reflection.ProcessorArchitecture.MSIL);
                 }
             }
             else
             {
                 if (machine == ImageFileMachine.IA64)
                 {
                     return(System.Reflection.ProcessorArchitecture.IA64);
                 }
                 if (machine == ImageFileMachine.AMD64)
                 {
                     return(System.Reflection.ProcessorArchitecture.Amd64);
                 }
             }
         }
         else if (ifm == ImageFileMachine.I386)
         {
             if (((pek & PortableExecutableKinds.Required32Bit) != PortableExecutableKinds.Required32Bit) && ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly))
             {
                 return(System.Reflection.ProcessorArchitecture.MSIL);
             }
             return(System.Reflection.ProcessorArchitecture.X86);
         }
     }
     return(System.Reflection.ProcessorArchitecture.None);
 }
        public AssemblyGen(string moduleName, string outDir, string outFile, bool emitDebugInfo,
            bool staticTypes, PortableExecutableKinds peKind, ImageFileMachine machine)
        {
            this.outFileName = outFile;
            this.outDir = outDir;
            this.emitDebugInfo = emitDebugInfo;
            this.staticTypes = staticTypes;
            this.peKind = peKind;
            this.machine = machine;

            AssemblyName asmname = new AssemblyName();

            AppDomain domain = System.Threading.Thread.GetDomain();
            asmname.Name = Path.GetFileNameWithoutExtension(outFileName);

            if (outFileName == null) {
                myAssembly = domain.DefineDynamicAssembly(
                                    asmname,
                                    AssemblyBuilderAccess.Run,
                                    outDir,
                                    null);
                myModule = myAssembly.DefineDynamicModule(moduleName);
            } else {
                myAssembly = domain.DefineDynamicAssembly(
                                    asmname,
                                    AssemblyBuilderAccess.RunAndSave,
                                    outDir,
                                    null);
                myModule = myAssembly.DefineDynamicModule(outFileName, outFileName, emitDebugInfo);

            }

            myAssembly.DefineVersionInfoResource();

            if (emitDebugInfo) SetDebuggableAttributes();
        }
Exemple #39
0
        internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags)
        {
            if (((uint)flags & 0xF0) == 0x70)
                return ProcessorArchitecture.None;

            if ((pek & System.Reflection.PortableExecutableKinds.PE32Plus) == System.Reflection.PortableExecutableKinds.PE32Plus)
            {
                switch (ifm)
                {
                    case System.Reflection.ImageFileMachine.IA64:
                        return ProcessorArchitecture.IA64;
                    case System.Reflection.ImageFileMachine.AMD64:
                        return ProcessorArchitecture.Amd64;
                    case System.Reflection.ImageFileMachine.I386:
                        if ((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly)
                            return ProcessorArchitecture.MSIL;
                        break;
                }
            }
            else
            {
                if (ifm == System.Reflection.ImageFileMachine.I386)
                {
                    if ((pek & System.Reflection.PortableExecutableKinds.Required32Bit) == System.Reflection.PortableExecutableKinds.Required32Bit)
                        return ProcessorArchitecture.X86;

                    if ((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly)
                        return ProcessorArchitecture.MSIL;

                    return ProcessorArchitecture.X86;
                }
                if (ifm == System.Reflection.ImageFileMachine.ARM)
                {
                    return ProcessorArchitecture.Arm;
                }
            }
            return ProcessorArchitecture.None;
        }
Exemple #40
0
 internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm)
 {
     ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _Flags);
 }
Exemple #41
0
		void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) {
			ModuleHandle.GetPEKind (out peKind, out machine);
		}
Exemple #42
0
 public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
 {
     ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine);
 }
Exemple #43
0
        public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            // This API was made virtual in V4. Code compiled against V2 might use
            // "call" rather than "callvirt" to call it.
            // This makes sure those code still works.
            RuntimeModule rtModule = this as RuntimeModule;
            if (rtModule != null)
                rtModule.GetPEKind(out peKind, out machine);

            throw new NotImplementedException();
        }
Exemple #44
0
		public virtual void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine)
		{
			throw CreateNIE ();
		}
        [System.Security.SecurityCritical]  // auto-generated
        internal void Save(String fileName, bool isAssemblyFile, PortableExecutableKinds portableExecutableKind, 
            ImageFileMachine imageFileMachine)
        {
            // This is a helper called by AssemblyBuilder save to save information for the persistable modules.
            if (m_moduleData.m_embeddedRes != null)
            {
                // There are embedded resources for this module
                ResWriterData   resWriter;

                // Add each resource content into the to be saved PE file
                for (resWriter = m_moduleData.m_embeddedRes; resWriter != null; resWriter = resWriter.m_nextResWriter)
                {
                    if (resWriter.m_resWriter != null)
                        resWriter.m_resWriter.Generate();                    
                    
                    byte[] resBytes = new byte[resWriter.m_memoryStream.Length];
                    resWriter.m_memoryStream.Flush();
                    resWriter.m_memoryStream.Position = 0;
                    resWriter.m_memoryStream.Read(resBytes, 0, resBytes.Length);

                    AddResource(GetNativeHandle(),
                                resWriter.m_strName, 
                                resBytes,
                                resBytes.Length,
                                m_moduleData.FileToken,
                                (int)resWriter.m_attribute, 
                                (int)portableExecutableKind,
                                (int)imageFileMachine);
                }
            }

            DefineNativeResource(portableExecutableKind, imageFileMachine);

            PEFileKinds pekind = isAssemblyFile ? ContainingAssemblyBuilder.m_assemblyData.m_peFileKind : PEFileKinds.Dll;

            SavePEFile(GetNativeHandle(), fileName, m_EntryPoint.Token, (int)pekind, isAssemblyFile); 

            m_moduleData.m_isSaved = true;
        }
        [System.Security.SecurityCritical]  // auto-generated
        internal void DefineNativeResource(PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
        {
            string strResourceFileName = m_moduleData.m_strResourceFileName;
            byte[] resourceBytes = m_moduleData.m_resourceBytes;

            if (strResourceFileName != null)
            {
                DefineNativeResourceFile(GetNativeHandle(),
                    strResourceFileName,
                    (int)portableExecutableKind, (int)imageFileMachine);
            }
            else
            if (resourceBytes != null)
            {
                DefineNativeResourceBytes(GetNativeHandle(),
                    resourceBytes, resourceBytes.Length,
                    (int)portableExecutableKind, (int)imageFileMachine);
            }
        }
Exemple #47
0
        public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            peKind = 0;
            if ((cliHeader.Flags & CliHeader.COMIMAGE_FLAGS_ILONLY) != 0)
            {
                peKind |= PortableExecutableKinds.ILOnly;
            }
            switch (cliHeader.Flags & (CliHeader.COMIMAGE_FLAGS_32BITREQUIRED | CliHeader.COMIMAGE_FLAGS_32BITPREFERRED))
            {
                case CliHeader.COMIMAGE_FLAGS_32BITREQUIRED:
                    peKind |= PortableExecutableKinds.Required32Bit;
                    break;
                case CliHeader.COMIMAGE_FLAGS_32BITREQUIRED | CliHeader.COMIMAGE_FLAGS_32BITPREFERRED:
                    peKind |= PortableExecutableKinds.Preferred32Bit;
                    break;
                default:
                    // COMIMAGE_FLAGS_32BITPREFERRED by itself is illegal, so we ignore it
                    // (not setting any flag is ok)
                    break;
            }
            if (peFile.OptionalHeader.Magic == IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC)
            {
                peKind |= PortableExecutableKinds.PE32Plus;
            }

            machine = (ImageFileMachine)peFile.FileHeader.Machine;
        }
Exemple #48
0
 private static extern bool StackWalkEx(
     ImageFileMachine MachineType,
     IntPtr hProcess,
     IntPtr hThread,
     ref STACKFRAME_EX StackFrame,
     IntPtr ContextRecord,
     ReadProcessMemoryProc64 ReadMemoryRoutine,
     FunctionTableAccessProc64 FunctionTableAccessRoutine,
     GetModuleBaseProc64 GetModuleBaseRoutine,
     TranslateAddressProc64 TranslateAddress,
     uint Flags);
        // making this internal, used by Module.GetPEKind
        internal void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            int _peKind;
            int _machine;

            _GetPEKind(out _peKind, out _machine);

            peKind = (PortableExecutableKinds)_peKind;
            machine = (ImageFileMachine)_machine;
        }
Exemple #50
0
		public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
		{
			throw new MissingModuleException(this);
		}
Exemple #51
0
        public AssemblyGen(string moduleName, 
            string outDir, 
            string outFile, 
            AssemblyGenAttributes generationAttributes,
            PortableExecutableKinds peKind, 
            ImageFileMachine machine)
        {
            Contract.Requires(!String.IsNullOrEmpty(moduleName), "moduleName", "Module name cannot be a null reference or an empty string.");
            Contract.Requires(outFile != null || !SaveAndReloadAssemblies, "outFile", "SaveAssemblies mode requires non-null output file name.");

            _genAttrs = generationAttributes;

            AssemblyName asmname = new AssemblyName();

            AppDomain domain = AppDomain.CurrentDomain; //System.Threading.Thread.GetDomain();

            _machine = machine;
            _peKind = peKind;
            _outFileName = outFile;

            #if SILVERLIGHT  // AssemblyBuilderAccess.RunAndSave, Environment.CurrentDirectory
            asmname.Name = moduleName;
            _myAssembly = domain.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
            _myModule = _myAssembly.DefineDynamicModule(moduleName, EmitDebugInfo);
            #else
            try {
                outDir = Path.GetFullPath(String.IsNullOrEmpty(outDir) ? Environment.CurrentDirectory : outDir);
            } catch (Exception e) {
                throw new ArgumentException("Invalid output directory", e);
            }

            if (SaveAndReloadAssemblies
            #if PEVERIFY
              || VerifyAssemblies
            #endif
              ) {
                _outDir = outDir;
            }

            if (moduleName == "ironscheme.boot.new")
            {
              _outDir = outDir = Path.Combine(outDir, "build");
              _outFileName = "ironscheme.boot.dll";
            }

              // SymbolWriter fails on Mono for some reason

            if (SaveAndReloadAssemblies) {
                asmname.Name = moduleName == "ironscheme.boot.new" ? "ironscheme.boot" : moduleName;
                if (File.Exists("DEVELOPMENT.snk"))
                {
                  asmname.KeyPair = new StrongNameKeyPair(File.ReadAllBytes("DEVELOPMENT.snk"));
                }
                asmname.Version = new Version("1.0.0.0");
            #pragma warning disable 0618
                _myAssembly = domain.DefineDynamicAssembly(asmname, moduleName == "ironscheme.boot.new" ? AssemblyBuilderAccess.Save : AssemblyBuilderAccess.Save, outDir, null);
            #pragma warning restore 0618

                _myModule = _myAssembly.DefineDynamicModule( moduleName == "ironscheme.boot.new" ? "ironscheme.boot.dll" : _outFileName,
                                                           _outFileName, EmitDebugInfo);
            } else {
                asmname.Name = moduleName;
                _myAssembly = domain.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
                _myModule = _myAssembly.DefineDynamicModule(moduleName, EmitDebugInfo);
            }
            _myAssembly.DefineVersionInfoResource();

            #endif
            if (EmitDebugInfo) SetDebuggableAttributes();
        }
Exemple #52
0
		public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
		{
			throw new NotSupportedException();
		}
Exemple #53
0
		void Save (string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
		{
			this.peKind = portableExecutableKind;
			this.machine = imageFileMachine;

			if ((peKind & PortableExecutableKinds.PE32Plus) != 0 || (peKind & PortableExecutableKinds.Unmanaged32Bit) != 0)
				throw new NotImplementedException (peKind.ToString ());
			if (machine == ImageFileMachine.IA64 || machine == ImageFileMachine.AMD64)
				throw new NotImplementedException (machine.ToString ());

			if (resource_writers != null) {
				foreach (IResourceWriter writer in resource_writers) {
					writer.Generate ();
					writer.Close ();
				}
			}

			// Create a main module if not already created
			ModuleBuilder mainModule = null;
			if (modules != null) {
				foreach (ModuleBuilder module in modules)
					if (module.FullyQualifiedName == assemblyFileName)
						mainModule = module;
			}
			if (mainModule == null)
				mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);

			if (!is_module_only)
				mainModule.IsMain = true;

			/* 
			 * Create a new entry point if the one specified
			 * by the user is in another module.
			 */
			if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
				Type[] paramTypes;
				if (entry_point.GetParametersCount () == 1)
					paramTypes = new Type [] { typeof (string) };
				else
					paramTypes = Type.EmptyTypes;

				MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
				ILGenerator ilgen = mb.GetILGenerator ();
				if (paramTypes.Length == 1)
					ilgen.Emit (OpCodes.Ldarg_0);
				ilgen.Emit (OpCodes.Tailcall);
				ilgen.Emit (OpCodes.Call, entry_point);
				ilgen.Emit (OpCodes.Ret);

				entry_point = mb;
			}

			if (version_res != null)
				DefineVersionInfoResourceImpl (assemblyFileName);

			if (sn != null) {
				// runtime needs to value to embed it into the assembly
				public_key = sn.PublicKey;
			}

			foreach (ModuleBuilder module in modules)
				if (module != mainModule)
					module.Save ();

			// Write out the main module at the end, because it needs to
			// contain the hash of the other modules
			mainModule.Save ();

			if ((sn != null) && (sn.CanSign)) {
				sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
			}

			created = true;
		}
Exemple #54
0
		public void __Save(Stream stream, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
		{
			if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek || stream.Position != 0)
			{
				throw new ArgumentException("Stream must support read/write/seek and current position must be zero.", "stream");
			}
			if (modules.Count != 1)
			{
				throw new NotSupportedException("Saving to a stream is only supported for single module assemblies.");
			}
			SaveImpl(modules[0].fileName, stream, portableExecutableKind, imageFileMachine);
		}
 public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
 {
     InternalModule.GetPEKind(out peKind, out machine);
 }
Exemple #56
0
		public void Save(string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
		{
			SaveImpl(assemblyFileName, null, portableExecutableKind, imageFileMachine);
		}
        [System.Security.SecurityCritical]  // auto-generated
        internal void PreSave(String fileName,
            PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
        {
            if (m_moduleData.m_isSaved == true)
            {
                // can only save once
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                    Environment.GetResourceString("InvalidOperation_ModuleHasBeenSaved"),
                    m_moduleData.m_strModuleName));
            }
        
            if (m_moduleData.m_fGlobalBeenCreated == false && m_moduleData.m_fHasGlobal == true)
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalFunctionNotBaked")); 

            TypeBuilder typeBuilder;
            foreach (Type item in m_TypeBuilderDict.Values)
            {
                if (item is TypeBuilder)
                {
                    typeBuilder = (TypeBuilder)item;
                }
                else
                {
                    EnumBuilder enumBuilder = (EnumBuilder)item;
                    typeBuilder = enumBuilder.m_typeBuilder;
                }

                if (!typeBuilder.IsCreated())
                {
                    // cannot save to PE file without creating all of the types first 
                    throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
                        Environment.GetResourceString("NotSupported_NotAllTypesAreBaked"), 
                        typeBuilder.FullName)); 
                }
            }

            PreSavePEFile(GetNativeHandle(), (int)portableExecutableKind, (int)imageFileMachine);
        }
Exemple #58
0
		private void SaveImpl(string assemblyFileName, Stream streamOrNull, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
		{
			ModuleBuilder manifestModule = null;

			foreach (ModuleBuilder moduleBuilder in modules)
			{
				moduleBuilder.SetIsSaved();
				moduleBuilder.PopulatePropertyAndEventTables();

				if (manifestModule == null
					&& string.Compare(moduleBuilder.fileName, assemblyFileName, StringComparison.OrdinalIgnoreCase) == 0)
				{
					manifestModule = moduleBuilder;
				}
			}

			if (manifestModule == null)
			{
				manifestModule = DefineDynamicModule("RefEmit_OnDiskManifestModule", assemblyFileName, false);
			}

			AssemblyTable.Record assemblyRecord = new AssemblyTable.Record();
			assemblyRecord.HashAlgId = (int)hashAlgorithm;
			assemblyRecord.Name = manifestModule.Strings.Add(name);
			assemblyRecord.MajorVersion = majorVersion;
			assemblyRecord.MinorVersion = minorVersion;
			assemblyRecord.BuildNumber = buildVersion;
			assemblyRecord.RevisionNumber = revisionVersion;
			if (publicKey != null)
			{
				assemblyRecord.PublicKey = manifestModule.Blobs.Add(ByteBuffer.Wrap(publicKey));
				assemblyRecord.Flags = (int)(flags | AssemblyNameFlags.PublicKey);
			}
			else
			{
				assemblyRecord.Flags = (int)(flags & ~AssemblyNameFlags.PublicKey);
			}
			if (culture != null)
			{
				assemblyRecord.Culture = manifestModule.Strings.Add(culture);
			}
			manifestModule.AssemblyTable.AddRecord(assemblyRecord);

			ResourceSection unmanagedResources = versionInfo != null || win32icon != null || win32manifest != null || win32resources != null
				? new ResourceSection()
				: null;

			if (versionInfo != null)
			{
				versionInfo.SetName(GetName());
				versionInfo.SetFileName(assemblyFileName);
				foreach (CustomAttributeBuilder cab in customAttributes)
				{
					// .NET doesn't support copying blob custom attributes into the version info
					if (!cab.HasBlob || universe.DecodeVersionInfoAttributeBlobs)
					{
						versionInfo.SetAttribute(this, cab);
					}
				}
				ByteBuffer versionInfoData = new ByteBuffer(512);
				versionInfo.Write(versionInfoData);
				unmanagedResources.AddVersionInfo(versionInfoData);
			}

			if (win32icon != null)
			{
				unmanagedResources.AddIcon(win32icon);
			}

			if (win32manifest != null)
			{
				unmanagedResources.AddManifest(win32manifest, fileKind == PEFileKinds.Dll ? (ushort)2 : (ushort)1);
			}

			if (win32resources != null)
			{
				unmanagedResources.ExtractResources(win32resources);
			}

			foreach (CustomAttributeBuilder cab in customAttributes)
			{
				// we intentionally don't filter out the version info (pseudo) custom attributes (to be compatible with .NET)
				manifestModule.SetCustomAttribute(0x20000001, cab);
			}

			manifestModule.AddDeclarativeSecurity(0x20000001, declarativeSecurity);

			foreach (TypeForwarder fwd in typeForwarders)
			{
				manifestModule.AddTypeForwarder(fwd.Type, fwd.IncludeNested);
			}

			foreach (ResourceFile resfile in resourceFiles)
			{
				if (resfile.Writer != null)
				{
					resfile.Writer.Generate();
					resfile.Writer.Close();
				}
				int fileToken = AddFile(manifestModule, resfile.FileName, 1 /*ContainsNoMetaData*/);
				ManifestResourceTable.Record rec = new ManifestResourceTable.Record();
				rec.Offset = 0;
				rec.Flags = (int)resfile.Attributes;
				rec.Name = manifestModule.Strings.Add(resfile.Name);
				rec.Implementation = fileToken;
				manifestModule.ManifestResource.AddRecord(rec);
			}

			int entryPointToken = 0;

			foreach (ModuleBuilder moduleBuilder in modules)
			{
				moduleBuilder.FillAssemblyRefTable();
				moduleBuilder.EmitResources();
				if (moduleBuilder != manifestModule)
				{
					int fileToken;
					if (entryPoint != null && entryPoint.Module == moduleBuilder)
					{
						ModuleWriter.WriteModule(null, null, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, moduleBuilder.unmanagedResources, entryPoint.MetadataToken);
						entryPointToken = fileToken = AddFile(manifestModule, moduleBuilder.fileName, 0 /*ContainsMetaData*/);
					}
					else
					{
						ModuleWriter.WriteModule(null, null, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, moduleBuilder.unmanagedResources, 0);
						fileToken = AddFile(manifestModule, moduleBuilder.fileName, 0 /*ContainsMetaData*/);
					}
					moduleBuilder.ExportTypes(fileToken, manifestModule);
				}
			}

			foreach (Module module in addedModules)
			{
				int fileToken = AddFile(manifestModule, module.FullyQualifiedName, 0 /*ContainsMetaData*/);
				module.ExportTypes(fileToken, manifestModule);
			}

			if (entryPointToken == 0 && entryPoint != null)
			{
				entryPointToken = entryPoint.MetadataToken;
			}

			// finally, write the manifest module
			ModuleWriter.WriteModule(keyPair, publicKey, manifestModule, fileKind, portableExecutableKind, imageFileMachine, unmanagedResources ?? manifestModule.unmanagedResources, entryPointToken, streamOrNull);
		}
Exemple #59
0
 [System.Security.SecuritySafeCritical]  // auto-generated
 internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
 {
     int lKind, lMachine;
     GetPEKind(module.GetNativeHandle(), out lKind, out lMachine);
     peKind = (PortableExecutableKinds)lKind;
     machine = (ImageFileMachine)lMachine;
 }
Exemple #60
0
		internal static extern void GetPEKind (IntPtr module, out PortableExecutableKinds peKind, out ImageFileMachine machine);