Relocatable Object Files

Overview

Relocatable object files are those, typically ending with a .o suffix, produced by the assembler. They contain binary code and data in a form that can be combined with other relocatable object files at compile time. The following diagram shows how one looks like when formatted using ELF:

relocatable-elf.png

Symbols

Every relocatable object module m has a symbol table that contains information about the symbols defined and referenced by m. In the context of a linker, there are three different kinds of symbols:

  1. Global symbols defined by m and that can be referenced by other modules.
  2. Global symbols referenced by m but defined by another module.
  3. Local symbols defined and referenced exclusively by m.

Pseudosections

There are three special pseudosections specified in the symbol table that do not have entries in the section header table. Pseudosections only exist in relocatable object files.

ABS

Marks symbols that should not be relocated.

UNDEF

Marks undefined symbols. These are referenced in the object module but (presumably) defined elsewhere.

COMMON

Assuming -fcommon, marks unitialized data objects that are not yet allocated.

At compile time, the compiler exports each global symbol as either strong or weak, and the assembler encodes this information in the symbol table. Functions and initialized global variables get strong symbols whereas uninitialized global variables get weak symbols. The linker then resolves global symbols as follows:

  1. Multiple strong symbols with the same name are not allowed.
  2. Given a strong symbol and multiple weak symbols with the same name, choose the strong symbol.
  3. Given multiple weak symbols with the same name, choose any of the weak symbols.

Relocation Entries

Whenever the assembler encounters a reference to an object whose ultimate location is unknown, it generates a relocation entry that tells the linker how to modify the reference when it merges the object file into an executable. Each entry looks something like:

struct Elf64_Rela {
  long offset;       // Offset of the reference to relocate
  long type : 32,    // Relocation type
       symbol : 32;  // Symbol table index
  long addend;       // Additional constant used to bias the value
};
Powered by Forestry.md