前言
使用boost C++ 读取PE文件,通过NT头判断PE是32位还是64位
提示:以下是本篇文章正文内容,下面案例可供参考
一、功能代码
#ifndef __GHOS_FILE_HPP__
#define __GHOS_FILE_HPP__
#include<Windows.h>
#include<boost/filesystem.hpp>
#include<boost/format.hpp>
#define boost_file boost::filesystem
using namespace std;
using namespace boost;
namespace ghos {
namespace pe {
string struct_check(boost_file::path pe_path)
{
string ret_info = "";
if (!boost_file::exists(pe_path))
{
return (format("%s not exists!\r\n") % pe_path).str();
}
auto f_size = boost_file::file_size(pe_path);;
if (f_size <= 0)
{
return (format("%s file size error!%ll\r\n") % pe_path % f_size).str();
}
boost_file::fstream pe_file;
pe_file.open(pe_path);
if (!pe_file.is_open())
{
return (format("%s file open failed!\r\n") % pe_path).str();
}
IMAGE_DOS_HEADER dos_header;
pe_file.read(reinterpret_cast<char*>(&dos_header),sizeof(IMAGE_DOS_HEADER));
if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
{
ret_info = "IMAGE_DOS_SIGNATURE MZ not find!\r\n";
goto close_ret;
}
IMAGE_NT_HEADERS nt_header;
pe_file.seekp(dos_header.e_lfanew);
pe_file.read(reinterpret_cast<char*>(&nt_header), sizeof(IMAGE_NT_HEADERS));
if (nt_header.Signature != IMAGE_NT_SIGNATURE)
{
ret_info = "IMAGE_NT_SIGNATURE PE not find!\r\n";
goto close_ret;
}
if (nt_header.FileHeader.Machine == IMAGE_FILE_MACHINE_I386)
{
ret_info = "32";
goto close_ret;
}
if (nt_header.FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 || nt_header.FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
{
ret_info = "64";
goto close_ret;
}
else
{
ret_info = "not 32/64 PE,other case\r\n";
goto close_ret;
}
close_ret:
pe_file.close();
return ret_info;
}
}//namespace pe
}//namespace ghos
#endif
二、测试代码
#include"pe.hpp"
#define test_pe_32 "C:\\OpenSSL-Win32\\aborttest.exe"
#define test_pe_64 "C:\\OpenSSL-Win64\\aborttest.exe"
using namespace ghos;
int main()
{
auto info1 = pe::struct_check(test_pe_32);
auto info2 = pe::struct_check(test_pe_64);
return 0;
}
三、测试结果
总结
简单的boost C++的一个例子,学习用