From wiki Executable and Linkable Format:
The segments contain information that is necessary for runtime execution of the file, while sections contain important data for linking and relocation. Any byte in the entire file can be owned by at most one section, and there can be orphan bytes which are not owned by any section.
But what's difference between section and segment? In an executable ELF file, does a segment contain one or more sections?
Exactly what you quoted: the segments contain information needed at runtime, while the sections contain information needed during linking.
A segment can contain 0 or more sections. Example:
Here,
PHDR
segment contains 0 sections,INTERP
segment contains.interp
section, and the firstLOAD
segment contains a whole bunch of sections.Further reading with a nice illustration.
Section contains static for the linker, segment dynamic data for the OS
The quote is correct, but to actually understand it the difference, you should try to understand the fields of the section header and program header (segment) entries, and how they are be used by the linker (sections) and operating system (segment).
Particularly important informations are (besides lengths):
section: tell the linker if a section is either:
.data
,.text
, etc..symtab
,.srttab
,.rela.text
segment: tells the operating system:
I have written a tutorial that covers that in more detail at: http://www.cirosantilli.com/elf-hello-world/
Does a segment contain one or more sections?
Yes, and it is the linker that puts sections into segments.
In Binutils, how sections are put into segments by
ld
is determined by a text file called a linker script. Docs: https://sourceware.org/binutils/docs/ld/Scripts.htmlYou can get the default one with
ld --verbose
, and set a custom one with-T
.For example, my default Ubuntu 17.04 linker script contains:
which tells the linker to put sections named
.text.unlikely
,.text.*_unlikely
,.text.exit
, etc. in the.text
segment.OS development is a case where custom scripts are useful, minimal example: https://github.com/cirosantilli/x86-bare-metal-examples/blob/d217b180be4220a0b4a453f31275d38e697a99e0/linker.ld
Once the executable is linked, it is only possible to know which section went to which segment if the linker stores the optional section header in the executable: Where is the "Section to segment mapping" stored in ELF files?