DWORD GetFunctionAddrByName(IN PVOID pFileBuffer,IN DWORD NameOfFunction)
{
PIMAGE_DOS_HEADER pDosHeader = NULL;
PIMAGE_NT_HEADERS pNTHeader = NULL;
PIMAGE_FILE_HEADER pPEHeader = NULL;
PIMAGE_OPTIONAL_HEADER32 pOptionHeader = NULL;
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
PIMAGE_DATA_DIRECTORY pDataDirectory = NULL;
if(!pFileBuffer)
{
printf("文件无效\n");
free(pFileBuffer);
return 0;
}
if(*(PDWORD)((DWORD)pFileBuffer) != IMAGE_DOS_SIGNATURE)
{
printf("不是有效的PE文件\n");
free(pFileBuffer);
return 0;
}
pDosHeader = (PIMAGE_DOS_HEADER)pFileBuffer;
pNTHeader = (PIMAGE_NT_HEADERS)((DWORD)pDosHeader + pDosHeader->e_lfanew);
pPEHeader = (PIMAGE_FILE_HEADER)((DWORD)pNTHeader + 4);
pOptionHeader = (PIMAGE_OPTIONAL_HEADER)((DWORD)pPEHeader + IMAGE_SIZEOF_FILE_HEADER);
pSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD)pOptionHeader + pPEHeader->SizeOfOptionalHeader);
//定位数据目录
pDataDirectory = pOptionHeader->DataDirectory;
//定位导出表
DWORD RVAOfDataDirectoryExportAddr = 0;
DWORD dataDirectoryExportSize = 0;
RVAOfDataDirectoryExportAddr = pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
dataDirectoryExportSize = pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
//用导出表指针取导出表大小,获得导出表
DWORD FOAOfDataDirectoryExportAddr = 0;
FOAOfDataDirectoryExportAddr = RVA2FOA (pFileBuffer,RVAOfDataDirectoryExportAddr);
IMAGE_EXPORT_DIRECTORY dataDirectoryExport = *(PIMAGE_EXPORT_DIRECTORY)(FOAOfDataDirectoryExportAddr + dataDirectoryExportSize);
//获取3个表的FOA
PDWORD FOAOfAddressOfFunctions = NULL;
PDWORD FOAOfAddressOfNames = NULL;
PDWORD FOAOfddressOfNameOrdinals = NULL;
FOAOfAddressOfFunctions = (PDWORD)RVA2FOA (pFileBuffer,dataDirectoryExport.AddressOfFunctions);
FOAOfAddressOfNames= (PDWORD)RVA2FOA (pFileBuffer,dataDirectoryExport.AddressOfNames);
FOAOfddressOfNameOrdinals= (PDWORD)RVA2FOA (pFileBuffer,dataDirectoryExport.AddressOfNameOrdinals);
//通过3个表的FOA找到3个表,但表中存储的都是RVA,取出来后也要转换
PDWORD FOAOfNames = NULL;
PDWORD FOAOfNmaeOrdinals =NULL;
PDWORD FOAOfFunctions = NULL;
DWORD AddrOfFunction = 0;
for(int i=0;i<dataDirectoryExport.NumberOfNames;i++)
{
FOAOfNames = (PDWORD)RVA2FOA (pFileBuffer,*(PWORD)FOAOfAddressOfNames[i]);
if(strcmp(NameOfFunction,*(FOAOfNames)))
{
AddrOfFunction = RVA2FOA (pFileBuffer,FOAOfFunctions[FOAOfNmaeOrdinals[i]]);
free(pFileBuffer);
return AddrOfFunction;
}
}
}
1.(AddressOfNameOrdinals)导出序号表中的的值 = 发布的导出序号 - Base(发布的最小导出序号),
反之发布的导出序号 =AddressOfNameOrdinals值 + Base(发布的最小导出序号)
2.如果用发布序号找函数地址,直接:发布序号- BASE = 直接拿到AddressOfFunctions的序号,
和AddressOfNameOrdinals中值的算法一样,但(AddressOfNameOrdinals)导出序号表中没有存储
总之,无论1.AddressOfNameOrdinals中的值,还是2.直接发布序号-Base,都是所对应函数的地址表的下标,算法一样
3.不要搞混淆序号表中的值和函数地址表数量:NumberOfFunctions的数量 = 发布序号的最大值 - 最小值 + 1,比如发布序号0,0-0 + 1 = 1, 故在AddressOfFunctions中对应从1开始分配位置,0就不用了,
所以AddressOfNameOrdinals中不可能存有0的情况;
或者比如发布序号为1,2 3 4 5,5 - 1 + 1 = 5,会在AddressOfFunctions表中分配5个,有一个是多余的,也就是0