如何从visual c ++中的exe文件中获取“入口点的地址”?

时间:2017-06-08 09:48:16

标签: visual-c++

我在Visual Studio 2008中编写C ++应用程序,需要通过读取可执行文件来获取入口点的地址。我怎么能得到这个?

2 个答案:

答案 0 :(得分:1)

找到以下方法来查找入口点的地址以及读取各种标头参数。

LPCSTR fileName; //exe file to parse
HANDLE hFile; 
HANDLE hFileMapping;
LPVOID lpFileBase;
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS peHeader;

hFile = CreateFileA(fileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

if(hFile==INVALID_HANDLE_VALUE)
{
    printf("\n CreateFile failed in read mode \n");
    return 1;
}

hFileMapping = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL);

if(hFileMapping==0)
{
    printf("\n CreateFileMapping failed \n");
    CloseHandle(hFile);
    return 1;
}

lpFileBase = MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0);

if(lpFileBase==0)
{
    printf("\n MapViewOfFile failed \n");
    CloseHandle(hFileMapping);
    CloseHandle(hFile);
    return 1;
}

dosHeader = (PIMAGE_DOS_HEADER) lpFileBase;  //pointer to dos headers

if(dosHeader->e_magic==IMAGE_DOS_SIGNATURE)
{
    //if it is executable file print different fileds of structure
    //dosHeader->e_lfanew : RVA for PE Header
    printf("\n DOS Signature (MZ) Matched");

    //pointer to PE/NT header
    peHeader = (PIMAGE_NT_HEADERS) ((u_char*)dosHeader+dosHeader->e_lfanew);

    if(peHeader->Signature==IMAGE_NT_SIGNATURE)
    {
        printf("\n PE Signature (PE) Matched \n");

        //address of entry point
        //peHeader->OptionalHeader.AddressOfEntryPoint

    }
    UnmapViewOfFile(lpFileBase);
    CloseHandle(hFileMapping);
    CloseHandle(hFile);
    return 0;
}
else
{
    printf("\n DOS Signature (MZ) Not Matched \n");
    UnmapViewOfFile(lpFileBase);
    CloseHandle(hFileMapping);
    CloseHandle(hFile);
    return 1;
}

答案 1 :(得分:-1)

IMAGE_NT_HEADERS的帮助下,您可以访问任何可执行文件的点条目。

typedef struct _IMAGE_NT_HEADERS {
  DWORD                 Signature;
  IMAGE_FILE_HEADER     FileHeader;
  IMAGE_OPTIONAL_HEADER OptionalHeader;
} IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS;

从具有 AddressOfEntryPoint 成员变量的上述结构IMAGE_OPTIONAL_HEADER访问入口点的地址。

以下小代码可以为您提供更多帮助:

FILE *executable; 
executable= fopen("YourExe.exe","rb");

IMAGE_NT_HEADERS executableInformation;
fread(&executableInformation,sizeof(executableInformation),1,executable);

注意:代码未经过测试,可能有错误。