C语言编程获取PE文件导入函数

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

DWORD RvaToOffset(PIMAGE_NT_HEADERS pImageNtHeaders, DWORD dwRva);


int _tmain(int argc, TCHAR *argv[])
{
	PIMAGE_DOS_HEADER pImageDOSHeader;
	PIMAGE_NT_HEADERS pImageNTHeader;
	PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor;
	PIMAGE_IMPORT_BY_NAME pImageImportByName;
	DWORD dwCount;
	DWORD dwCount2;
	DWORD *Thunks;
	DWORD dwFileOffset;
	HANDLE hFile;
	HANDLE hMapObject;
	PUCHAR uFileMap;

	if(argc<2)
		return -1;
	if(!(hFile=CreateFile(argv[1],GENERIC_READ,0,NULL,OPEN_EXISTING,0,0)))
		return -1;
	if (!(hMapObject = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL)))
		return (-1);
	if (!(uFileMap = MapViewOfFile(hMapObject, FILE_MAP_READ, 0, 0, 0)))
		return (-1);
	pImageDOSHeader=(PIMAGE_DOS_HEADER)uFileMap;
	if(pImageDOSHeader->e_magic != IMAGE_DOS_SIGNATURE)
		return -1;
	pImageNTHeader = (PIMAGE_NT_HEADERS)((PUCHAR)uFileMap + pImageDOSHeader->e_lfanew);
	if(pImageNTHeader->Signature != IMAGE_NT_SIGNATURE)
		return -1;
	if (!(pImageNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress))
	{
		printf("No import function!")
			return 0;
	}
	dwFileOffset = RvaToOffset(pImageNTHeader,pImageNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
	pImageImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)((PUCHAR)uFileMap+dwFileOffset);
	dwCount = 0;
	while(pImageImportDescriptor[dwCount].FirstThunk)
	{
		printf("\nModule Name: %s\n\n",((PUCHAR)uFileMap+RvaToOffset(pImageNTHeader,pImageImportDescriptor[dwCount].Name)));
		Thunks = (DWORD *)((PUCHAR)uFileMap+RvaToOffset(pImageNTHeader,pImageImportDescriptor[dwCount].OriginalFirstThunk));
		dwCount2=0;
		while(Thunks[dwCount2])
		{
			pImageImportByName=(PIMAGE_IMPORT_BY_NAME)((PUCHAR)uFileMap+RvaToOffset(pImageNTHeader,Thunks[dwCount2]));
			printf("Name: %s\n",pImageImportByName->Name);
			dwCount2++;
		}
		dwCount++;
	}
	
	UnmapViewOfFile(uFileMap);
	CloseHandle(hMapObject);
	CloseHandle(hFile);
	return 0;
}

DWORD RvaToOffset(PIMAGE_NT_HEADERS pImageNtHeaders, DWORD dwRva)
{
	PIMAGE_SECTION_HEADER pImageSectionHeader;
	DWORD dwCount;
	DWORD dwFileOffset;
	pImageSectionHeader = IMAGE_FIRST_SECTION(pImageNtHeaders);
	dwFileOffset = dwRva;
	for (dwCount=0;dwCount<pImageNtHeaders->FileHeader.NumberOfSections;dwCount++)
	{
		if(dwRva>=pImageSectionHeader[dwCount].VirtualAddress && dwRva<(pImageSectionHeader[dwCount].VirtualAddress+pImageSectionHeader[dwCount].SizeOfRawData))
		{
			dwFileOffset-=pImageSectionHeader[dwCount].VirtualAddress;
			dwFileOffset+=pImageSectionHeader[dwCount].PointerToRawData;
			return dwFileOffset;
		}
	}

	return 0;
}

posted @ 2016-02-02 22:41  星空天宇  阅读(104)  评论(0编辑  收藏  举报