在读取PE文件的部分时,SetFilePointer无法正常工作

时间:2013-04-25 17:50:23

标签: c executable portable-executable

好的,我要做的是打印PE可执行文件的所有数据:

#include<stdio.h>
#include<Windows.h>
int dth(int dec)
{
    return 0;
}

int main()
{
    IMAGE_NT_HEADERS peHead;
    IMAGE_DOS_HEADER dosMZ;
    IMAGE_SECTION_HEADER *secHead;
    unsigned long d;
    char file[]=".\\test.exe";
    HANDLE host;
    int i=0;
    printf("\nScanning %s :-",file);
    if((host=CreateFileA(file,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL))==INVALID_HANDLE_VALUE)
    {
        printf("\nFile OPEN Error");
        return 0;
    }
    if(!ReadFile(host,(void*)&dosMZ,sizeof(dosMZ),&d,NULL))
    {
        printf("\nRead Fail");
        return 0;
    }
    if(!(dosMZ.e_magic==IMAGE_DOS_SIGNATURE))
    {
        printf("\nNot a Valid PE");
        return 0;
    }
    printf("\nDos Signature Found");
    SetFilePointer(host,dosMZ.e_lfanew,NULL,FILE_BEGIN);
    if(!ReadFile(host,(void*)&peHead,sizeof(peHead),&d,NULL))
    {
        printf("\nRead Fail");
        return 0;
    }
    if(!(peHead.Signature==IMAGE_NT_SIGNATURE))
    {
        printf("\nNot Valid PE");
        return 0;
    }
    printf("\nPe Signature Found");
    printf("\nMachine to be Executed on: %x   ;Intelx86 for 0x14c",peHead.FileHeader.Machine);
    printf("\nNumber of Sections : %d",peHead.FileHeader.NumberOfSections);
    if(peHead.FileHeader.Characteristics==0x10f)
        printf("\nCharachteristics : Executable File");
    else
        printf("\nCharachteristics : DLL File");
    printf("\nReading Sections :");
    printf("%d",peHead.OptionalHeader.SizeOfHeaders);

    secHead=(IMAGE_SECTION_HEADER*)GlobalAlloc(GMEM_FIXED,sizeof(IMAGE_SECTION_HEADER)*peHead.FileHeader.NumberOfSections);
    ReadFile(host,(void*)secHead,sizeof(IMAGE_SECTION_HEADER)*peHead.FileHeader.NumberOfSections,&d,NULL);
    for(i=0;i<peHead.FileHeader.NumberOfSections;i++)
    {
        printf("\n Section Name : %s",secHead[i].Name);
        printf("\n RVA          : %x",secHead[i].VirtualAddress);
        printf("\n Pointer to Raw Data : %x",secHead[i].PointerToRawData);
        printf("\n Size of Data : %x",secHead[i].SizeOfRawData);
    }

    printf("\nPrinting opcodes of code Section:\n\n");

    SetFilePointer(host,(int)secHead[1].PointerToRawData,NULL,FILE_BEGIN);

    char ab;
    for(i=0;i<=(secHead[1].SizeOfRawData);i++)
    {
        ReadFile(host,&ab,1,&d,NULL);
        printf("%c",ab);
    }
    printf("%d\n,%d",i);
    CloseHandle(host);
    return 0;
}

setfilepointer将指针设置为.text部分的开头,并且必须将文件指针设置为文件的4096位置时,会发生错误,而是指向{{ 1}}位置。我在用ollydbg调试问题后发现了这个。

Anyoone可以告诉我什么错了?

0 个答案:

没有答案