从加载的 DLL 函数中获取文件偏移量

Get file offset from a loaded DLL's function

本文关键字:获取 文件 偏移量 函数 加载 DLL      更新时间:2023-10-16

我想问,如何在DLL中定位特定的(导出)函数。例如,我想在Kernel32中查找ReadProcessMemory。我不想依赖Import表,我想根据它们的地址来定位不同的API,这是我通过自定义函数获得的。

我试着对VA、RVA&文件偏移,但我没有成功。下面是我尝试过的一个例子,但它不起作用(在所有情况下都返回0):

DWORD Rva2Offset(DWORD dwRva, UINT_PTR uiBaseAddress)
{
    WORD wIndex = 0;
    PIMAGE_SECTION_HEADER pSectionHeader = NULL;
    PIMAGE_NT_HEADERS pNtHeaders = NULL;
    pNtHeaders = (PIMAGE_NT_HEADERS) (uiBaseAddress + ((PIMAGE_DOS_HEADER) uiBaseAddress)->e_lfanew);
    pSectionHeader = (PIMAGE_SECTION_HEADER) ((UINT_PTR) (&pNtHeaders->OptionalHeader) + pNtHeaders->FileHeader.SizeOfOptionalHeader);
    if (dwRva < pSectionHeader[0].PointerToRawData)
        return dwRva;
    for (wIndex = 0; wIndex < pNtHeaders->FileHeader.NumberOfSections; wIndex++)
    {
        if (dwRva >= pSectionHeader[wIndex].VirtualAddress && dwRva < (pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].SizeOfRawData))
            return (dwRva - pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].PointerToRawData);
    }
    return 0;
}

你能帮我怎样才能完成这项简单的任务吗?

谢谢。

附言:我不坚持上面的函数,如果你能指出问题所在,或者提供一个更好的来源,那就太棒了

这将为您提供相对虚拟地址

uintptr_t baseAddr = (uintptr_t)GetModuleHandle("nameOfExe.exe");
uintptr_t relativeAddr = functionAddress - baseAddr;

这将相对虚拟地址转换为文件偏移量:

DWORD RVAToFileOffset(IMAGE_NT_HEADERS32* pNtHdr, DWORD dwRVA)
{
int i;
WORD wSections;
PIMAGE_SECTION_HEADER pSectionHdr;
pSectionHdr = IMAGE_FIRST_SECTION(pNtHdr);
wSections = pNtHdr->FileHeader.NumberOfSections;
for (i = 0; i < wSections; i++)
{
if (pSectionHdr->VirtualAddress <= dwRVA)
if ((pSectionHdr->VirtualAddress + pSectionHdr->Misc.VirtualSize) > dwRVA)
{
dwRVA -= pSectionHdr->VirtualAddress;
  dwRVA += pSectionHdr->PointerToRawData;
return (dwRVA);
}
pSectionHdr++;
}
return (-1);
}