1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using System;
- using System.Diagnostics;
- using System.Drawing;
- using System.IO;
- using System.Reflection;
- using Aio1Ef.Packer.Common.ExternalCodes;
- namespace Aio1Ef.Packer.Common
- {
- internal static class CoffUtility
- {
- /// <summary>
- /// Parses the PE header and determines whether the given assembly is a console application.
- /// </summary>
- /// <param name="assemblyPath">The path of the assembly to check.</param>
- /// <returns>True if the given assembly is a console application; false otherwise.</returns>
- /// <remarks>The magic numbers in this method are extracted from the PE/COFF file
- /// format specification available from http://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx
- /// </remarks>
- public static bool AssemblyUsesConsoleSubsystem(string assemblyPath)
- {
- using (var s = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read))
- {
- var rawPeSignatureOffset = new byte[4];
- s.Seek(0x3c, SeekOrigin.Begin);
- s.Read(rawPeSignatureOffset, 0, 4);
- int peSignatureOffset = rawPeSignatureOffset[0];
- peSignatureOffset |= rawPeSignatureOffset[1] << 8;
- peSignatureOffset |= rawPeSignatureOffset[2] << 16;
- peSignatureOffset |= rawPeSignatureOffset[3] << 24;
- var coffHeader = new byte[24];
- s.Seek(peSignatureOffset, SeekOrigin.Begin);
- s.Read(coffHeader, 0, 24);
- byte[] signature = { (byte)'P', (byte)'E', (byte)'\0', (byte)'\0' };
- for (var index = 0; index < 4; index++)
- {
- Debug.Assert(coffHeader[index] == signature[index],
- "Attempted to check a non PE file for the console subsystem!");
- }
- var subsystemBytes = new byte[2];
- s.Seek(68, SeekOrigin.Current);
- s.Read(subsystemBytes, 0, 2);
- var subSystem = subsystemBytes[0] | subsystemBytes[1] << 8;
- return subSystem == 3; /*IMAGE_SUBSYSTEM_WINDOWS_CUI*/
- }
- }
- public static string GetTargetPlatform(Assembly assembly)
- {
- PortableExecutableKinds pek;
- ImageFileMachine ifm;
- assembly.ManifestModule.GetPEKind(out pek, out ifm);
- if (pek == (PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit) && ifm == ImageFileMachine.I386)
- return "x86";
- if (pek == (PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus) && ifm == ImageFileMachine.AMD64)
- return "x64";
- if (pek == (PortableExecutableKinds.ILOnly) && ifm == ImageFileMachine.I386)
- return "anycpu";
- if (pek == (PortableExecutableKinds.ILOnly | PortableExecutableKinds.Preferred32Bit) && ifm == ImageFileMachine.I386)
- return "anycpu";
- throw new ArgumentException($"Not support {pek} & {ifm}");
- }
- public static Icon GetIconFromFile(string path)
- {
- try
- {
- return new IconExtractor(path).GetIcon(0);
- }
- catch
- {
- return null;
- }
- }
- }
- }
|