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

50

我该如何在C#中编程判断一个非托管DLL文件是x86还是x64?


请查看 Stack Overflow 上的问题 *如何确定本机 DLL 文件是作为 x64 还是 x86 编译的?*。 - Lazarus
这个回答解决了你的问题吗?如何查找本地 DLL 文件是以 x64 还是 x86 编译的? - StayOnTarget
5个回答

56

请参考规范。以下是一个基本实现:

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;
    }
}

我在你的FileStream实例化中添加了FileAccess.Read - 否则当尝试确定C:\Windows或C:\Program Files中DLL的位数时,它会使我们崩溃。 - AngryHacker
当检查32位程序集时,GetPEKind(http://msdn.microsoft.com/en-us/library/system.reflection.module.getpekind%28VS.80%29.aspx)在64位进程中失败。你的代码能处理这个问题吗? - Kiquenet

22

使用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

5
更简单的方法:查看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) 环境中运行。

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

以下是链接:

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/zh-cn/library/system.reflection.imagefilemachine.aspx


9
只有在你的进程中真正加载了该程序集,才能使其起作用。如果机器类型和位数不匹配,则在调用Assembly.LoadFile()时会出现“坏图像格式”异常,并且您将无法继续执行GetPEKind()函数。 - yoyoyoyosef

1

使用Assembly.ReflectionOnlyLoadFrom代替Assembly.LoadFile。这样可以避免“Bad Image Format”异常。


很遗憾,使用 Assembly.ReflectionOnlyLoadFrom 仍然会导致 System.BadImageFormatException - A N

0

我知道这已经有一段时间没有更新了。通过将文件加载到自己的AppDomain中,我成功地避免了“Bad Image Format”异常。

        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), "");
        }
    }

在我的Windows\Assembly目录下运行此程序,经过处理的文件数超过3600个,却没有出现任何错误。 注意:我使用字典来加载返回值。
希望这会有所帮助。你们的结果可能会有所不同。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接