How are PE Base Relocations build up?

Neither options you indicated entirely correct/true.

This excellent tutorial on How to inject code in a PE file shows that the actual IMAGE_BASE_RELOCATION structure is:

typedef struct _IMAGE_BASE_RELOCATION {
  DWORD   VirtualAddress;
  DWORD   SizeOfBlock;
} IMAGE_BASE_RELOCATION, *PIMAGE_BASE_RELOCATION;

Section 5.2 of this Microsoft Portable Executable and Common Object File Format Specification describe the structure. The SizeOfBlock-8 actually indicates how many WORD TypeOffset follow after the VirtualAddress and SizeOfBlock.

I think you would also be interested in Table 7 of the tutorial, which shows the structure of the blocks from the relocation table. I'll copy-paste the table here for quick-reference.

enter image description here


from some code.. aldo check out reactos :)

BOOL FixRelocs(void *base, void *rBase, IMAGE_NT_HEADERS *ntHd, IMAGE_BASE_RELOCATION *reloc,
               unsigned int size) {
    unsigned long ImageBase = ntHd->OptionalHeader.ImageBase;
    unsigned int nBytes = 0;
    unsigned long delta = MakeDelta(unsigned long, rBase, ImageBase);
    unsigned long *locBase;
unsigned int numRelocs;
unsigned short *locData;
unsigned int i;

while(1) {
  locBase =
     (unsigned long *)GetPtrFromRVA((DWORD)(reloc->VirtualAddress), ntHd, (PBYTE)base);
  numRelocs = (reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);

  if(nBytes >= size) break;

  locData = MakePtr(unsigned short *, reloc, sizeof(IMAGE_BASE_RELOCATION));
  for(i = 0; i < numRelocs; i++) {       
     if(((*locData >> 12) == IMAGE_REL_BASED_HIGHLOW))
         *MakePtr(unsigned long *, locBase, (*locData & 0x0FFF)) += delta;
     locData++;
  }

  nBytes += reloc->SizeOfBlock;
  reloc = (IMAGE_BASE_RELOCATION *)locData;
   }

   return TRUE;

}