Calculating file offset from RVA in .NET Assembly

2019-07-14 09:50发布

问题:

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.

回答1:

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



标签: clr