遍历PE导入表遇到问题 <<<问题已经解决>>>
我想同过遍历PE导入表,获得cmd.exe中使用到的DLL文件名,但是却得到了一堆无意义的字符....请高手指点我的代码如下:
#include <windows.h>
#include <stdio.h>
//如果是全零则返回TRUE,否则返回FALSE
BOOL allzero(BYTE data[],int datasize)
{
int i=0;
for(i=0;i<datasize;i++)
{
if(data[i]) return FALSE;
}
return TRUE;
}
BOOL ReadPeHeader(char FileName[MAX_PATH])
{
IMAGE_DOS_HEADER image_dos_header;
IMAGE_NT_HEADERS image_nt_header;
DWORD dwRead;
HANDLE hFile;
long peoffset;
hFile=CreateFile(FileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(INVALID_HANDLE_VALUE==hFile) return FALSE;
ReadFile(hFile,&image_dos_header,sizeof(image_dos_header),&dwRead,NULL);
if(dwRead==sizeof(image_dos_header))
//PE header偏移量,相对于文件首部
peoffset=image_dos_header.e_lfanew;
else
return FALSE;
SetFilePointer(hFile,peoffset,NULL,FILE_BEGIN);
ReadFile(hFile,&image_nt_header,sizeof(image_nt_header),&dwRead,NULL);
if(dwRead==sizeof(image_nt_header))
{
//导入表的rav
DWORD import_table_rav;
//导入表相对文件起始的偏移
DWORD improt_table_offset;
IMAGE_IMPORT_DESCRIPTOR image_import_descriptor;
IMAGE_SECTION_HEADER image_section_header;
int i;
int sectionsnum;
//data directory数组第二项的VirtualAddress包含引入表的rav
import_table_rav=image_nt_header.OptionalHeader.DataDirectory[1].VirtualAddress;
//确定导入表相对文件的偏移地址
sectionsnum=image_nt_header.FileHeader.NumberOfSections;
SetFilePointer(hFile,peoffset+sizeof(IMAGE_NT_HEADERS),NULL,FILE_BEGIN);
for(i=0;i<sectionsnum;i++)
{
ReadFile(hFile,&image_section_header,sizeof(image_section_header),&dwRead,NULL);
if(dwRead==sizeof(IMAGE_SECTION_HEADER))
{
if((import_table_rav>=image_section_header.VirtualAddress) &&
(import_table_rav<=(image_section_header.VirtualAddress+image_section_header.SizeOfRawData)))
{
improt_table_offset=image_section_header.PointerToRawData+import_table_rav-image_section_header.VirtualAddress;
printf("section name: %s\n",&image_section_header.Name);
break;
}
}
else
return FALSE;
}
i=-1;
while(1)
{
i++;
SetFilePointer(hFile,improt_table_offset+sizeof(image_import_descriptor)*i,NULL,FILE_BEGIN);
ReadFile(hFile,&image_import_descriptor,sizeof(image_import_descriptor),&dwRead,NULL);
if(dwRead==sizeof(image_import_descriptor))
{
IMAGE_IMPORT_BY_NAME image_import_by_name;
if(allzero((BYTE *)&image_import_descriptor,dwRead)) break;
printf("dll filename: %s\n",&image_import_descriptor.Name);
}
else
return FALSE;
}
}
else
return FALSE;
CloseHandle(hFile);
return TRUE;
}
int main()
{
ReadPeHeader("c:\\windows\\system32\\cmd.exe");
return 0;
}
[[it] 本帖最后由 redice 于 2008-6-5 14:47 编辑 [/it]]