Yves
Yves

Reputation: 12381

Why is a defined function put in the relocation table

I'm learning how a linker works in Linux. Here is my code as an example:

// main.c
int printf(const char *format, ...);

void func1(int i)
{
    printf("%d\n", i);
}

int main(void)
{
    func1(1);
    return 0;
}

I execute the command gcc -c main.c and get an obj file named main.o.

Then I execute the command objdump -r main.o and here is the output:

main.o:     file format elf64-x86-64

RELOCATION RECORDS FOR [.text]:
OFFSET           TYPE              VALUE
0000000000000011 R_X86_64_32       .rodata
000000000000001b R_X86_64_PC32     printf-0x0000000000000004
000000000000002c R_X86_64_PC32     func1-0x0000000000000004


RELOCATION RECORDS FOR [.eh_frame]:
OFFSET           TYPE              VALUE
0000000000000020 R_X86_64_PC32     .text
0000000000000040 R_X86_64_PC32     .text+0x0000000000000022

If I'm right, objdump -r will show us all of the relocation tables in the obj file. In this case, printf and func1 are all put into the relocation table.

printf isn't defined in this C file so it needs to be relocated, but why can func1 be found in the relocation table too? As my understanding, func1 should be well defined and can be found in the .text section, it needn't to be relocated, right?

Upvotes: 2

Views: 653

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223254

The relocation records are locations that need to be adjusted when addresses of sections are determined. In many architectures, including x86, it is possible to write position-independent code that refers to objects or functions by offsets from one place within a section to another (and so the offsets do not change when whole section is moved) and may refer to objects or functions by offsets across sections with some additional linker assistance (and so the offsets do not change after linking, and the entire combined image may be shifted in memory).

However, the fact that it is possible does not mean your build tools are using position-independent code. For whatever reason, it appears the tools you are using, with the switches you are using, are not generating position-independent code. Thus, when there is a reference to printf or func1, a relocatable reference to it is generated, resulting in a relocation record that must be adjusted by the linker or loader.

Upvotes: 2

Related Questions