Load shared libraries with preferred base address

For performance, sometimes we need to adjust the address space layout. The following way allows the shared or executable object to be loaded with preferred base address.

When the dynamic link maps the shared object, the virtual address of segment(that in ELF program header) will be used as the mapping address hints.

Type 1
Link with text-segment starting address.

# Adjust base address to 0x10000 */
gcc -shared ... -Wl,-Ttext-segment=0x10000

Type 2
We can adjust the virtual address of loaded segment by linker scripts.

0x1 Get link script template

gcc -shared -Wl,--verbose > ld.script

Clear the contents before and after the ‘equal sign’.

0x2 Adjust the base address

....
SECTIONS
{
    /* Adjust base address to 0x10000 */
    . = SEGMENT_START("text-segment", 0x10000) + SIZEOF_HEADERS;
    ...
}
....

0x3 Link with script

gcc -shared ... -Wl,-T ld.script

Over!