How to specify base addresses for sections when linking or alternatively how to rebase a section after linking?
Asked Answered
C

1

8

Symbols can be linked at certain addresses with defsym as illustrated here. My question is whether the same can be done with sections? That is, given some .o object file, is it possible to specify the base address that sections will be relocated to?

Alternatively, is it possible to rebase a section after the final link? That is, to change the address of a section in a binary and have all information affected by relocation (such as relative branches out of the section, etc.) to be relocated properly.

If my question is not clear, I can edit it and add an image to explain better.

Character answered 29/2, 2012 at 23:24 Comment(0)
D
10

Judging by the question you reference and the tag of Linux, I am going to assume that you are using GNU ld.

The short answer for GNU ld is yes, sections can be placed at specific addresses.

The longer answer is that you will need to create a custom linker script to do that, which can be specified the -T for ld. If you are using gcc as a wrapper around ld, you will need pass it the linker via the gcc -Wl, option.

The linker script will have to include something like the following:

SECTIONS {
   .text 0x08049000 :
       {
       foo.o (.text)
       bar.o (.text)
       }
}

Something to watch out for though is that -T option replaces the default linker script that ld uses. You may want to modify the default linker script to do what you want. The default linker script can be dumped by passing the --verbose option to ld without any other options.

More info about linker scripts is available in the LD Manual.

Dato answered 3/3, 2012 at 21:46 Comment(1)
Thanks for the answer. I am now doing it like so: gcc -std=gnu99 -Wall -Wl,--section-start=.secname=0xABCDEF Lala.c -o LalaCharacter

© 2022 - 2024 — McMap. All rights reserved.