直接贴代码了
// pe.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
DWORD AddressConvert(char* lpBase,DWORD dwAddr,BOOL bRvaToFoa)
{
DWORD dwRet = -1;//返回值
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)lpBase;
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((DWORD)lpBase + pDosHeader->e_lfanew);
int secNum = pNtHeader->FileHeader.NumberOfSections;
PIMAGE_SECTION_HEADER pSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD)lpBase + pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS));
DWORD dwHeaderOfSize = pNtHeader->OptionalHeader.SizeOfHeaders;
//判断地址是否在表头内
if(dwAddr <= dwHeaderOfSize)
{
return dwAddr;
}
for (int i=0;i<secNum;i++)
{
if(bRvaToFoa == TRUE)
{
if(pSectionHeader[i].VirtualAddress <= dwAddr && dwAddr <= pSectionHeader[i].VirtualAddress + pSectionHeader->Misc.VirtualSize)
{
dwRet = pSectionHeader[i].PointerToRawData + dwAddr - pSectionHeader[i].VirtualAddress;
break;
}
}
else
{
if(pSectionHeader[i].PointerToRawData <= dwAddr && dwAddr <= pSectionHeader[i].PointerToRawData + pSectionHeader->SizeOfRawData)
{
dwRet = pSectionHeader[i].VirtualAddress + dwAddr - pSectionHeader[i].PointerToRawData;
break;
}
}
}
return dwRet;
}
int main(int argc, char* argv[])
{
char* lpBase = NULL;
char fileName[] = "C:\\VC++6.0MSDN.exe";
DWORD dwFileSize = 0;//文件大小
FILE* fp = fopen(fileName,"rb+");
if(fp== 0)
{
printf("读取失败\n");
}
fseek(fp,0,SEEK_END);
dwFileSize = ftell(fp);
if(dwFileSize ==0)
{
printf("读取失败\n");
}
lpBase = new char[dwFileSize];
memset(lpBase,0,dwFileSize);
fseek(fp,0,SEEK_SET);
fread(lpBase,1,dwFileSize,fp);
fclose(fp);
DWORD dwRet = AddressConvert(lpBase,0x1000,TRUE);
printf("%.8X\n",dwRet);
delete lpBase;
lpBase = NULL;
printf("Hello World!\n");
return 0;
}
网友评论