打印出PE文件的imports表中第一个条目的名称

时间:2012-03-13 16:48:30

标签: windows executable exe portable-executable

我试图在PE文件的导入表中打印出第一个条目的名称(我认为是user32.dll),但程序意外终止说“无法读取内存”,有人可以解释一下我为什么??

#include<iostream>
#include<Windows.h>
#include<stdio.h>
#include<WinNT.h>


int main()
{


HANDLE  hFile,hFileMapping;
LPVOID lpFileBase;
LPVOID lp;

if((hFile = CreateFile(TEXT("c:\\linked list.exe"),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0)) == INVALID_HANDLE_VALUE)
    std::cout<<"unable to open";

if((hFileMapping = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL)) == 0)
{
    CloseHandle(hFile);
    std::cout<<"unable to open for mapping";
}

if((lpFileBase = MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0))== 0)
{
    CloseHandle(hFile);
    CloseHandle(hFileMapping);
    std::cout<<"couldn't map view of file";
}

PIMAGE_DOS_HEADER pimdh;
pimdh = (PIMAGE_DOS_HEADER)lpFileBase;

PIMAGE_NT_HEADERS pimnth;
pimnth = (PIMAGE_NT_HEADERS)((char *)pimdh + pimdh->e_lfanew);

PIMAGE_SECTION_HEADER pimsh;
pimsh = (PIMAGE_SECTION_HEADER)(pimnth + 1);

int i;
for(i = 0; i<pimnth->FileHeader.NumberOfSections; i++)
{
    if(!strcmp((char *)pimsh->Name,".idata"))
    {
        char *p;

        PIMAGE_IMPORT_DESCRIPTOR pimid;
        pimid = (PIMAGE_IMPORT_DESCRIPTOR)(pimnth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + (char *)lpFileBase);
        p = (char *)((char *)lpFileBase + pimid->Name);
        printf("%s",p);
    };

    pimsh++;
}



}

1 个答案:

答案 0 :(得分:1)

几天前

You asked a similar question查看你的代码,你已经阅读了我答案的三分之二。

另外三分之一表示pimid->Name不是文件偏移量,它是相对虚拟地址(或RVA),您需要将其转换为文件偏移量。这就是你收到错误的原因。了解RVAs read the MSDN article。有关转换的示例代码,请查看文章中引用的pedump