Calculating file offset from RVA in .NET Assembly

2019-07-14 09:35发布

I'm trying to calculate the CLI Header file offset using the optional header, I manually checked a sample .NET Assembly and noticed that the optional header gives me the RVA for the CLI Header which is 0x2008 and the file offset of the CLI Header is 0x208. How can I calculate the file offset from the RVA? Thanks.

标签: clr
1条回答
Melony?
2楼-- · 2019-07-14 09:41

The PE file contains a bunch of sections that get mapped to page aligned virtual addresses using the section table (just after the optional header).

So to read the CLI Header, you can either:

  • use something like LoadLibrary or LoadLibraryEx to map it into memory and then just add the RVA to the returned module base address,
  • or you can read the section table and use it to map the RVA to a file position.
/* pseudo code */
int GetFilePosition(int rva)
{
    foreach (var section in Sections)
    {
        var pos = rva - section.VirtualAddress;

        if (pos >= 0 && pos < section.VirtualSize)
        {
            return pos + section.PointerToRawData;
        }
    }

    Explode();
}

The Section table is described in ECMA-335 Partition II Section 25.3

查看更多
登录 后发表回答