2

我正在尝试解析 PE 文件,将其加载到内存中,并将 WinNT 结构指针设置为适当的地址。但是,我无法对 PE\0\0 签名进行愚蠢的检查,因为我与 DOS 标头的偏移量错误(一个字节太多)。因此,当我检查 IMAGE_NT_HEADERS.Signature 时,我会收到从“E”开始的 4 个字节。

#define SHOW_VAR(x)  std::cout << #x << " = " << x << std::endl
#define SHOW_HEX(x)  std::cout << std::showbase << std::hex << #x << " = " << x << std::endl; std::cout << std::dec

uintmax_t fileSize = boost::filesystem::file_size(m_filePath);
m_image.reset(new char[fileSize]);

boost::filesystem::ifstream file;
file.open(m_filePath, std::ios::in);
file.read(m_image.get(), fileSize);
file.close();

m_DOSHeader = reinterpret_cast<PIMAGE_DOS_HEADER>(m_image.get());
// --m_DOSHeader->e_lfanew; <---- THIS SOLVES THE PROBLEM BUT WHY?
m_NTHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(m_image.get() + m_DOSHeader->e_lfanew);

// DEBUG
SHOW_HEX(m_DOSHeader->e_lfanew);
for(int i = m_DOSHeader->e_lfanew - 5; i < m_DOSHeader->e_lfanew + 5; ++i)
{
    if(i == m_DOSHeader->e_lfanew)
        std::cout << "---> ";
    SHOW_HEX(m_image[i]);
}

// check if MZ
if(m_DOSHeader->e_magic != IMAGE_DOS_SIGNATURE)
    throw std::runtime_error("[PEFile] MZ signature not found");

// check if PE00
SHOW_VAR((char)m_NTHeaders->Signature);
if(m_NTHeaders->Signature != IMAGE_NT_SIGNATURE)
    throw std::runtime_error("[PEFile] PE00 signature not found");

调试片段的结果是:

m_DOSHeader->e_lfanew = 0xf0
m_image[i] =  
m_image[i] =  
m_image[i] =  
m_image[i] =  
m_image[i] = P
---> m_image[i] = E
m_image[i] =  
m_image[i] =  
m_image[i] = L
m_image[i] = 
(char)m_NTHeaders->Signature = E
[ERROR] [PEFile] PE00 signature not found

我用 pedump.me 检查了它,m_DOSHeader->e_lfanew = 0xf0 没问题。我做错了什么,我必须减少这个偏移量才能得到真正正确的签名?

我在 64 位 Windows 8.1 上使用 VS2013 RC,但我检查了我是否设置了 _WIN32 定义。32 位和 64 位 exe 文件都会出现此错误。

4

1 回答 1

3
file.open(m_filepath, std::ios::in | std::ios::binary);

如果您不以二进制模式打开,则 std::fstream 在处理输入时可以添加或删除其他字符。

于 2013-10-21T20:22:31.217 回答