您的位置:首页 > 其它

获取PE文件的OEP值 (源码)

2007-06-05 17:19 260 查看
两种方法读取PE文件的OEP值:一是 直接读取文件,二是 通过内存映射。

#include "stdafx.h"
#include <afx.h>

//-------------------------------
//read the file of .exe get the OEP (Original Entry Point)
//-------------------------------
BOOL ReadOPEbyFile(LPCSTR szFileName)
{
HANDLE hFile;
if ((hFile = CreateFile(szFileName,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,0))==INVALID_HANDLE_VALUE)
{
printf("Can't open the file");
return FALSE;
}
DWORD dwOEP,cbRead;
IMAGE_DOS_HEADER dos_head[sizeof(IMAGE_DOS_HEADER)];
if (!ReadFile(hFile,dos_head,sizeof(IMAGE_DOS_HEADER),&cbRead,NULL))
{
printf("Read image_dos_header failed ./n");
CloseHandle(hFile);
return FALSE;
}
int nEntryPos = dos_head->e_lfanew+40;
SetFilePointer(hFile,nEntryPos,NULL,FILE_BEGIN);
if (!ReadFile(hFile,&dwOEP,sizeof(dwOEP),&cbRead,NULL)) {
printf("Read OEP failed ./n");
CloseHandle(hFile);
return FALSE;
}

CloseHandle(hFile);
printf("OEP by file: %d/n",dwOEP);
return TRUE;
}
//-----------------------------------------
//fileMapping get the OEP
//-----------------------------------------

BOOL ReadOEPbyMemory(LPCSTR szFileName)
{
struct PE_HEADER_MAP
{
DWORD signature;
IMAGE_FILE_HEADER _head;
IMAGE_OPTIONAL_HEADER opt_head;
IMAGE_SECTION_HEADER section_header[6];
}*header;

HANDLE hFile;
HANDLE hMapping;
void *basepointer;

//open the file
if ((hFile = CreateFile(szFileName,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,0))==INVALID_HANDLE_VALUE) {
printf("Can't open the file");
return FALSE;
}
if (!(hMapping = CreateFileMapping(hFile,0,PAGE_READONLY|SEC_COMMIT,0,0,0))) {
printf("Mapping failed./n");
CloseHandle(hFile);
return FALSE;
}
if (!(basepointer = MapViewOfFile(hMapping,FILE_MAP_READ,0,0,0)))
{
printf("View failed./n");
CloseHandle(hMapping);
CloseHandle(hFile);
return FALSE;
}

IMAGE_DOS_HEADER *dos_head = (IMAGE_DOS_HEADER *)basepointer;
header = (PE_HEADER_MAP *)((char *)dos_head+dos_head->e_lfanew);
DWORD dwOEP = header->opt_head.AddressOfEntryPoint;

UnmapViewOfFile(basepointer);
CloseHandle(hMapping);
CloseHandle(hFile);

printf("OEP by memory :%d/n",dwOEP);
return TRUE;
}

int main(int argc, char* argv[])
{
printf("Hello World!/n");
ReadOPEbyFile("D://jp.exe");
ReadOEPbyMemory("D://jp.exe");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: