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

时间:2014-10-15 19:03:57

标签: c++ visual-studio-2013 offset virtual-address-space

我想问一下,如何在DLL中找到特定的(导出)函数。例如,我想在Kernel32中找到ReadProcessMemory。我不想依赖导入表,我希望根据他们使用自定义函数获得的地址找到不同的API。

我试图对VA,RVA& amp;文件抵消,但我没有成功。这是我尝试过的一个例子,但它不起作用(在所有情况下都返回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;
}

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

谢谢。

Ps:我不坚持上述功能,如果你能指出问题是什么,或者提供更好的资源就会很棒。

1 个答案:

答案 0 :(得分: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);
}