我们如何将某个位置的 RVA(相对虚拟地址)映射到 PE 文件偏移量?

Usm*_*man 2 c++ debugging process cffile portable-executable

从磁盘位置读取 PE 文件时,我需要将 RVA(取自 pdb 文件的相对虚拟地址)映射到 PE 文件(EXE)偏移量。为此,我需要将 RVA 转换为文件偏移量,以便我可以从该位置读出 GUIDS(CLSID,IID)。

问候乌斯曼

Len*_*ate 5

template <class T> LPVOID GetPtrFromRVA(
   DWORD rva,
   T* pNTHeader,
   PBYTE imageBase ) // 'T' = PIMAGE_NT_HEADERS
{
   PIMAGE_SECTION_HEADER pSectionHdr;
   INT delta;

   pSectionHdr = GetEnclosingSectionHeader( rva, pNTHeader);
   if ( !pSectionHdr )
      return 0;

   delta = (INT)(pSectionHdr->VirtualAddress-pSectionHdr->PointerToRawData);
   return (PVOID) ( imageBase + rva - delta );
}

template <class T> PIMAGE_SECTION_HEADER GetEnclosingSectionHeader(
   DWORD rva,
   T* pNTHeader)   // 'T' == PIMAGE_NT_HEADERS
{
    PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader);
    unsigned i;

    for ( i=0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++ )
    {
      // This 3 line idiocy is because Watcom's linker actually sets the
      // Misc.VirtualSize field to 0.  (!!! - Retards....!!!)
      DWORD size = section->Misc.VirtualSize;
      if ( 0 == size )
         size = section->SizeOfRawData;

        // Is the RVA within this section?
        if ( (rva >= section->VirtualAddress) &&
             (rva < (section->VirtualAddress + size)))
            return section;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩...


Aby*_*byx 5

您可以使用ImageRvaToVa函数。