MyGetProcAddress
程序员文章站
2022-06-04 10:41:53
...
手动实现了GetProcAddress(),在明白了导出表的结构之后似乎也没什么难度。。。
下面的示例为用手写的MyGetProcAddress()得到MessageBoxW的函数地址并调用该函数:
#include <Windows.h>
#include <stdio.h>
DWORD MyGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
//一键找到模块的导出表描述符IMAGE_EXPORT_DIRECTORY
PIMAGE_EXPORT_DIRECTORY pImageExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((PIMAGE_NT_HEADERS((DWORD)hModule + ((PIMAGE_DOS_HEADER)((DWORD)hModule))->e_lfanew))->OptionalHeader.DataDirectory[0].VirtualAddress + (DWORD)hModule);
//遍历所有有名称的函数
for (int i = 0; i < pImageExportDirectory->NumberOfNames; ++i)
{
DWORD dwAdName = *(DWORD*)((DWORD)hModule + pImageExportDirectory->AddressOfNames + i * sizeof(DWORD)) + (DWORD)hModule;
if (lstrcmpiA((char*)dwAdName, lpProcName) == 0)
{
//得到该函数的索引index
WORD index = *(DWORD*)((DWORD)hModule + pImageExportDirectory->AddressOfNameOrdinals + i * sizeof(WORD));
//得到该函数的RVA
DWORD dwFuncRVA = (DWORD)hModule + pImageExportDirectory->AddressOfFunctions + index * sizeof(DWORD);
//返回该函数的VA
return *(DWORD*)dwFuncRVA + (DWORD)hModule;
}
}
//未找到该函数返回NULL
return 0;
}
int main()
{
typedef DWORD (WINAPI* MessageBoxWFunc)(
HWND hWnd, // handle to owner window
LPCWSTR lpText, // text in message box
LPCWSTR lpCaption, // message box title
UINT uType // message box style
);
HMODULE hModule = LoadLibraryA("user32.dll");
MessageBoxWFunc MESSAGEBOXW = (MessageBoxWFunc)MyGetProcAddress(hModule, "MessageBoxW");
MESSAGEBOXW(NULL, L"1234", L"1234", MB_OK);
return 0;
}
推荐阅读