1

When an ELF file is run and its various segments are loaded into memory, is there a way to know in advance how the segments will be arranged in relation to each other? That is, could I know, for example, that the rodata segment comes after the bss segment?

1 Answer 1

3

is there a way to know in advance how the segments will be arranged in relation to each other?

Yes. There are two types of ELF files: ET_EXEC and ER_DYN. The former is for executables, the latter for PIE executables and shared libraries.

An ET_EXEC segments will be in memory in exactly the location they were linked at. The executable will not work if its segments are loaded anywhere else.

You can examine the linked-at addresses with readelf -Wl a.out.

For ET_DYN, the segments will be loaded at a single fixed offset of where they were linked. That is, if the first PT_LOAD segment is linked at address 0x0, and loaded at address 0x1234000, then you can add 0x1234000 to the p_vaddr of every subsequent segment to determine where it is loaded in memory.

could I know, for example, that the rodata segment comes after the bss segment?

There is no such thing as rodata and bss segment -- they are sections. To see which segment these sections are assigned to, use readelf -Wl.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I seem to have trouble remembering the difference between sections and segments.
Please allow a follow-up question. Do the program headers correspond to the segments? I notice that the output of readelf -Wl for my sample ELF contains nine of each.
@DanielWalker Yes: program headers describe ELF segments, and there is 1:1 relationship. Note: not all segments are loadable, only the ones with .p_type == PT_LOAD. Note: non-loadable segments may overlap and be included as part of some loadable ones.
Perfect! That's just what I needed to know. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.