检查非托管 DLL 是 32 位还是 64 位?

发布于 2024-07-24 21:55:47 字数 45 浏览 5 评论 0原文

如何在 C# 中以编程方式判断非托管 DLL 文件是 x86 还是 x64?

How can I programmatically tell in C# if an unmanaged DLL file is x86 or x64?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦明 2024-07-31 21:55:47

请参阅规范。 这是一个基本实现:

public static MachineType GetDllMachineType (string dllPath)
{
    // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
    // Offset to PE header is always at 0x3C.
    // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
    // followed by a 2-byte machine type field (see the document above for the enum).
    //
    using (var fs = new FileStream (dllPath, FileMode.Open, FileAccess.Read))
    using (var br = new BinaryReader (fs))
    {
        fs.Seek (0x3c, SeekOrigin.Begin);
        Int32 peOffset = br.ReadInt32();

        fs.Seek (peOffset, SeekOrigin.Begin);
        UInt32 peHead = br.ReadUInt32();

        if (peHead != 0x00004550) // "PE\0\0", little-endian
            throw new Exception ("Can't find PE header");

        return (MachineType)br.ReadUInt16();
    }
}

MachineType 枚举定义为:

public enum MachineType : ushort
{
    IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
    IMAGE_FILE_MACHINE_AM33 = 0x1d3,
    IMAGE_FILE_MACHINE_AMD64 = 0x8664,
    IMAGE_FILE_MACHINE_ARM = 0x1c0,
    IMAGE_FILE_MACHINE_EBC = 0xebc,
    IMAGE_FILE_MACHINE_I386 = 0x14c,
    IMAGE_FILE_MACHINE_IA64 = 0x200,
    IMAGE_FILE_MACHINE_M32R = 0x9041,
    IMAGE_FILE_MACHINE_MIPS16 = 0x266,
    IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
    IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
    IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
    IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
    IMAGE_FILE_MACHINE_R4000 = 0x166,
    IMAGE_FILE_MACHINE_SH3 = 0x1a2,
    IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
    IMAGE_FILE_MACHINE_SH4 = 0x1a6,
    IMAGE_FILE_MACHINE_SH5 = 0x1a8,
    IMAGE_FILE_MACHINE_THUMB = 0x1c2,
    IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
    IMAGE_FILE_MACHINE_ARM64 = 0xaa64 
}

我只需要其中三个,但为了完整性我将它们全部包含在内。 最终 64 位检查:

// Returns true if the dll is 64-bit, false if 32-bit, and null if unknown
public static bool? UnmanagedDllIs64Bit(string dllPath)
{
    switch (GetDllMachineType(dllPath))
    {
        case MachineType.IMAGE_FILE_MACHINE_AMD64:
        case MachineType.IMAGE_FILE_MACHINE_IA64:
            return true;
        case MachineType.IMAGE_FILE_MACHINE_I386:
            return false;
        default:
            return null;
    }
}

Refer to the specifications. Here's a basic implementation:

public static MachineType GetDllMachineType (string dllPath)
{
    // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
    // Offset to PE header is always at 0x3C.
    // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
    // followed by a 2-byte machine type field (see the document above for the enum).
    //
    using (var fs = new FileStream (dllPath, FileMode.Open, FileAccess.Read))
    using (var br = new BinaryReader (fs))
    {
        fs.Seek (0x3c, SeekOrigin.Begin);
        Int32 peOffset = br.ReadInt32();

        fs.Seek (peOffset, SeekOrigin.Begin);
        UInt32 peHead = br.ReadUInt32();

        if (peHead != 0x00004550) // "PE\0\0", little-endian
            throw new Exception ("Can't find PE header");

        return (MachineType)br.ReadUInt16();
    }
}

The MachineType enum is defined as:

public enum MachineType : ushort
{
    IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
    IMAGE_FILE_MACHINE_AM33 = 0x1d3,
    IMAGE_FILE_MACHINE_AMD64 = 0x8664,
    IMAGE_FILE_MACHINE_ARM = 0x1c0,
    IMAGE_FILE_MACHINE_EBC = 0xebc,
    IMAGE_FILE_MACHINE_I386 = 0x14c,
    IMAGE_FILE_MACHINE_IA64 = 0x200,
    IMAGE_FILE_MACHINE_M32R = 0x9041,
    IMAGE_FILE_MACHINE_MIPS16 = 0x266,
    IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
    IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
    IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
    IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
    IMAGE_FILE_MACHINE_R4000 = 0x166,
    IMAGE_FILE_MACHINE_SH3 = 0x1a2,
    IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
    IMAGE_FILE_MACHINE_SH4 = 0x1a6,
    IMAGE_FILE_MACHINE_SH5 = 0x1a8,
    IMAGE_FILE_MACHINE_THUMB = 0x1c2,
    IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
    IMAGE_FILE_MACHINE_ARM64 = 0xaa64 
}

I only needed three of these, but I included them all for completeness. Final 64-bit check:

// Returns true if the dll is 64-bit, false if 32-bit, and null if unknown
public static bool? UnmanagedDllIs64Bit(string dllPath)
{
    switch (GetDllMachineType(dllPath))
    {
        case MachineType.IMAGE_FILE_MACHINE_AMD64:
        case MachineType.IMAGE_FILE_MACHINE_IA64:
            return true;
        case MachineType.IMAGE_FILE_MACHINE_I386:
            return false;
        default:
            return null;
    }
}
烟─花易冷 2024-07-31 21:55:47

使用 Visual Studio 命令提示符, dumpbin /headers dllname.dll 也可以工作。 在我的机器上,输出的开头指出:

FILE HEADER VALUES
8664 machine (x64)
5 number of sections
47591774 time date stamp Fri Dec 07 03:50:44 2007

Using a Visual Studio command prompt, dumpbin /headers dllname.dll works too. On my machine the beginning of the output stated:

FILE HEADER VALUES
8664 machine (x64)
5 number of sections
47591774 time date stamp Fri Dec 07 03:50:44 2007
温暖的光 2024-07-31 21:55:47

更简单:查看 System.Reflection.Module 类。 它包括 GetPEKind 方法,该方法返回 2 个描述代码类型和 CPU 目标的枚举。 不再有十六进制!

(这篇内容非常丰富的文章的其余部分是从 http: //www.developersdex.com/vb/message.asp?p=2924&r=6413567)

示例代码:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom(@"<assembly Path>");
PortableExecutableKinds kinds;
ImageFileMachine imgFileMachine;
assembly.ManifestModule.GetPEKind(out kinds, out imgFileMachine);

PortableExecutableKinds 可用于检查哪种程序集。 它
有 5 个值:

ILOnly:可执行文件仅包含 Microsoft 中间语言
(MSIL),因此对于 32 位或 64 位而言是中性的
平台。

NotAPortableExecutableImage:该文件不在可移植可执行文件 (PE) 中
文件格式。

PE32Plus:可执行文件需要 64 位平台。

required32Bit:可执行文件可以在 32 位平台上运行,或者在
64 位平台上的 32 位 Windows on Windows (WOW) 环境。

非托管32位:可执行文件包含纯非托管代码。

以下是链接:

Module.GetPEKind 方法:
http://msdn.microsoft.com/en- us/library/system.reflection.module.getpekind.aspx

PortableExecutableKinds 枚举:
http://msdn.microsoft.com /en-us/library/system.reflection.portableexecutablekinds(VS.80).aspx

ImageFileMachine 枚举:
http://msdn.microsoft.com/en-us/库/system.reflection.imagefilemachine.aspx

Even easier: check out the System.Reflection.Module class. It includes the GetPEKind method, which returns 2 enums that describe the type of code and the CPU target. No more hex!

(the rest of this very informative post was copied shamelessly from http://www.developersdex.com/vb/message.asp?p=2924&r=6413567)

Sample code:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom(@"<assembly Path>");
PortableExecutableKinds kinds;
ImageFileMachine imgFileMachine;
assembly.ManifestModule.GetPEKind(out kinds, out imgFileMachine);

PortableExecutableKinds can be used to check what kind of the assembly. It
has 5 values:

ILOnly: The executable contains only Microsoft intermediate language
(MSIL), and is therefore neutral with respect to 32-bit or 64-bit
platforms.

NotAPortableExecutableImage: The file is not in portable executable (PE)
file format.

PE32Plus: The executable requires a 64-bit platform.

Required32Bit: The executable can be run on a 32-bit platform, or in the
32-bit Windows on Windows (WOW) environment on a 64-bit platform.

Unmanaged32Bit: The executable contains pure unmanaged code.

Following are the links:

Module.GetPEKind Method:
http://msdn.microsoft.com/en-us/library/system.reflection.module.getpekind.aspx

PortableExecutableKinds Enumeration:
http://msdn.microsoft.com/en-us/library/system.reflection.portableexecutablekinds(VS.80).aspx

ImageFileMachine Enumeration:
http://msdn.microsoft.com/en-us/library/system.reflection.imagefilemachine.aspx

柠檬心 2024-07-31 21:55:47

使用 Assembly.ReflectionOnlyLoadFrom,而不是 Assembly.LoadFile。 这将使您能够解决“错误图像格式”异常。

Instead of Assembly.LoadFile, use Assembly.ReflectionOnlyLoadFrom. This will let you work around the "Bad Image Format" exceptions.

书信已泛黄 2024-07-31 21:55:47

我知道自从更新以来已经有一段时间了。 通过将文件加载到它自己的 AppDomain 中,我能够摆脱“错误图像格式”异常。

        private static (string pkName, string imName) FindPEKind(string filename)
    {
        // some files, especially if loaded into memory
        // can cause errors. Thus, load into their own appdomain
        AppDomain tempDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
        PEWorkerClass remoteWorker =
            (PEWorkerClass)tempDomain.CreateInstanceAndUnwrap(
                typeof(PEWorkerClass).Assembly.FullName,
                typeof(PEWorkerClass).FullName);

        (string pkName, string imName) = remoteWorker.TryReflectionOnlyLoadFrom_GetManagedType(filename);

        AppDomain.Unload(tempDomain);
        return (pkName, imName);
    }

此时,我执行以下操作:

        public (string pkName, string imName) TryReflectionOnlyLoadFrom_GetManagedType(string fileName)
    {
        string pkName;
        string imName;
        try
        {
            Assembly assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile: fileName);
            assembly.ManifestModule.GetPEKind(
                peKind: out PortableExecutableKinds peKind,
                machine: out ImageFileMachine imageFileMachine);

            // Any CPU builds are reported as 32bit.
            // 32bit builds will have more value for PortableExecutableKinds
            if (peKind == PortableExecutableKinds.ILOnly && imageFileMachine == ImageFileMachine.I386)
            {
                pkName = "AnyCPU";
                imName = "";
            }
            else
            {
                PortableExecutableKindsNames.TryGetValue(
                    key: peKind,
                    value: out pkName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    pkName = "*** ERROR ***";
                }

                ImageFileMachineNames.TryGetValue(
                    key: imageFileMachine,
                    value: out imName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    imName = "*** ERROR ***";
                }
            }

            return (pkName, imName);
        }
        catch (Exception ex)
        {
            return (ExceptionHelper(ex), "");
        }
    }

针对我的 Widows\Assembly 目录运行此命令,处理的文件数超过 3600 个,结果为零错误。
注意:我使用字典来加载返回的值。

我希望它有帮助。 青年MMV

I know it has been a while since this was updated. I was able to get away with the "Bad Image Format" exceptions by loading the file into it's own AppDomain.

        private static (string pkName, string imName) FindPEKind(string filename)
    {
        // some files, especially if loaded into memory
        // can cause errors. Thus, load into their own appdomain
        AppDomain tempDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
        PEWorkerClass remoteWorker =
            (PEWorkerClass)tempDomain.CreateInstanceAndUnwrap(
                typeof(PEWorkerClass).Assembly.FullName,
                typeof(PEWorkerClass).FullName);

        (string pkName, string imName) = remoteWorker.TryReflectionOnlyLoadFrom_GetManagedType(filename);

        AppDomain.Unload(tempDomain);
        return (pkName, imName);
    }

At this point, I do the following:

        public (string pkName, string imName) TryReflectionOnlyLoadFrom_GetManagedType(string fileName)
    {
        string pkName;
        string imName;
        try
        {
            Assembly assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile: fileName);
            assembly.ManifestModule.GetPEKind(
                peKind: out PortableExecutableKinds peKind,
                machine: out ImageFileMachine imageFileMachine);

            // Any CPU builds are reported as 32bit.
            // 32bit builds will have more value for PortableExecutableKinds
            if (peKind == PortableExecutableKinds.ILOnly && imageFileMachine == ImageFileMachine.I386)
            {
                pkName = "AnyCPU";
                imName = "";
            }
            else
            {
                PortableExecutableKindsNames.TryGetValue(
                    key: peKind,
                    value: out pkName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    pkName = "*** ERROR ***";
                }

                ImageFileMachineNames.TryGetValue(
                    key: imageFileMachine,
                    value: out imName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    imName = "*** ERROR ***";
                }
            }

            return (pkName, imName);
        }
        catch (Exception ex)
        {
            return (ExceptionHelper(ex), "");
        }
    }

Running this against my Widows\Assembly directory gives me zero errors with over 3600 files processed.
note: I use a dictionary to load the values being returned.

I hope it helps. YMMV

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文