C# – Writing a Compiler – .reloc section of the COFF

ccompilernet

I'm looking for a little bit of direction in writing a compiler. I've written in Common Intermediate Language, C#, and various other .NET languages; I've written my own Metadata Parser and now I'm trying to understand the various aspects of the Portable Executable (PE) layout. One thing that somewhat befuddles me is the .reloc section.

I have the Relocs parsing (or at least I think I do? 🙂 and I wanted to know, within .NET libraries they usually have a single Reloc block with a single HighLow (IMAGE_REL_BASED_HIGHLOW, or just 3) reloc at a given offset that changes. When I go to writing my own PE Header and COFF sections, how do I calculate the Relative Virtual Address of the block, and the Offset (lower 12 bits) on the TypeOffset entry that follows that block header?

I'm currently using the pecoff_v83.docx (Microsoft Portable Executable and Common Object File Format Specification Revision 8.3) from Microsoft's website, but I think there's a step I'm missing out on.

I'll link a relevant post: How are PE Base Relocations build up?

^ That helped me parse the Reloc entries, but parsing them and generating the data that goes into them are different questions.

Best Answer

... how do I calculate the Relative Virtual Address of the block, and the Offset (lower 12 bits) on the Type Offset entry that follows that block header?

Microsoft - PE Format (05/30/2018):

"Base Relocation Block

Each base relocation block starts with the following structure:

Offset      Size      Field      Description


   0              4          RVA      The image base plus the page RVA is added to each offset to create the VA where the base relocation must be applied.

   4              4           BS         The total number of bytes in the base relocation
block, including the Page RVA and Block Size fields and the Type/Offset fields that follow.

 

The Block Size field is then followed by any number of Type or Offset field entries. Each entry is a WORD (2 bytes) and has the following structure:

Offset      Size      Field      Description


   0             4b        Type      Stored in the high 4 bits of the WORD, a value that indicates the type of base relocation to be applied. For more information, see Base Relocation Types.

   0            12b       Type      Stored in the remaining 12 bits of the WORD, an offset from the starting address that was specified in the Page RVA field for the block. This offset specifies where the base relocation is to be applied.

...

".

Example code is in BinUtils.

You can find testing code in binutils/ld/testsuite/ld-cygwin.

Related Topic