如何确定针对哪个平台编译了可执行文件? [英] How can I determine for which platform an executable is compiled?

查看:13
本文介绍了如何确定针对哪个平台编译了可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用为 x86、x64 和 IA64 制作的 Windows 可执行文件.我想通过检查文件本身以编程方式确定平台.

I have a need to work with Windows executables which are made for x86, x64, and IA64. I'd like to programmatically figure out the platform by examining the files themselves.

我的目标语言是 PowerShell,但 C# 示例也可以.如果您知道所需的逻辑,那其中任何一个都失败了,那就太好了.

My target language is PowerShell but a C# example will do. Failing either of those, if you know the logic required that would be great.

推荐答案

(来自另一个 Q,已移除)

(from another Q, since removed)

机器类型:这是我基于一些获取链接器时间戳的快速代码.这是在同一个头文件中,它似乎有效 - 编译时返回 I386 -any cpu- 和 x64 编译时将其作为目标平台.

Machine type: This is a quick little bit of code I based on some that gets the linker timestamp. This is in the same header, and it seems to work - it returns I386 when compiled -any cpu-, and x64 when compiled with that as the target platform.

Exploring PE Headers (K. Stanton, MSDN) 博客条目向我展示了偏移量,如另一条回复所述.

The Exploring PE Headers (K. Stanton,MSDN) blog entry that showed me the offset, as another response noted.

public enum MachineType {
    Native = 0, I386 = 0x014c, Itanium = 0x0200, x64 = 0x8664
}

public static MachineType GetMachineType(string fileName)
{
    const int PE_POINTER_OFFSET = 60;            
    const int MACHINE_OFFSET = 4;
    byte[] data = new byte[4096];
    using (Stream s = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
        s.Read(data, 0, 4096);
    }
    // dos header is 64 bytes, last element, long (4 bytes) is the address of the PE header
    int PE_HEADER_ADDR = BitConverter.ToInt32(data, PE_POINTER_OFFSET);
    int machineUint = BitConverter.ToUInt16(data, PE_HEADER_ADDR + MACHINE_OFFSET);
    return (MachineType)machineUint;
}

这篇关于如何确定针对哪个平台编译了可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆