1
votes

This is a repeat of a question but I could not quickly find an answer to my question. That's why asking it.

Some ELF files contain(executables or shared libs) program headers which explain segments. They contain a field called virtual address and file offsets and some other fields.

There are also corresponding sections which explain "address in memory" and file offset.

Now I am little confused how sections and segments are related. (For statically compiled executables and for non-statically compiled executables.) How file offsets are different for statically compiled binaries? Is there any relation between virtual address in program headers and memory address in section headers.

Thanks

1
I myself found a nice article which clears most of my confusion: "mylinuxbook.com/readelf-command" - agent.smith
Could you summarize what you've learned in the form of answer to your question? - Ross Ridge

1 Answers

3
votes

A section is the smallest continuous region of the file. So ELF files are subdivided into sections. Sections cannot overlap, that is, no byte can possibly be part of more than one section. But there can be bytes that don't belong to any section ("garbage").

Sections are generally used for linking purposes. They contain different parts of the file that can be rearranged, merged etc. by the linker.

But executable files can contain sections too – to describe the contents of the file, and where each piece of code or data begins. Shared objects use sections too. Those contain symbol tables for dynamic linking & stuff like that.

All sections contained in the ELF file are described in the Section Headers Table, each section having an entry in it.

But in order to make an executable, you need something else: segments. These tell the loader which parts of the file it should load into memory and to what addresses. So segments map into the executable process's memory space. They can contain code as well as data, so segments can be subdivided into sections to achieve that. And I guess that's the answer to your question.

Loadable segments are described in the Program Headers Table.

Long story short:
In executables, you have segments, that can be subdivided further into sections. Segments are loaded into the process's memory. Sections are optional, but can help subdivide the segments further or describe their contents. In relocatable modules (compiler outputs, .o files) it's the other way around: sections are required, because they describe what's in the file and allow for linking.



all

Physical addresses are not used, so they can be left as zeros, but could be set to the same addresses just in case.