Reputation: 2600
So we know that linker
(in my case ld
) adds the Program Headers
to the Relocatable file
while creating the actual Executable
.
Then these Headers are used to load the program into memory at run-time.
First of all how ld
calculates and adds these headers to the file?
And then if the Program Headers
are used only to load the program into memory (correct me if I'm wrong), how come different executables have different number of Program Headers
?
For example a simple helloworld written in assembly has 2 Program headers:
readelf -h helloworld
...
Number of program headers: 2
...
But the bash
has 11 program headers:
readelf -h /bin/bash
...
Number of program headers: 11
...
Upvotes: 1
Views: 324
Reputation: 213636
First of all how ld calculates and adds these headers to the file?
This question is too general to answer. You may wish to read this series of blogposts explaining how the linker works.
And then if the Program Headers are used only to load the program into memory (correct me if I'm wrong), how come different executables have different number of Program Headers?
Executables have different number of Program Headers because they have different needs.
For example, a fully-static executable doesn't need any interaction with dynamic linker, and therefore doesn't need PT_DYNAMIC
segment (and the program header that describes that segment).
Common dynamically linked executables will have at least two PT_LOAD
segments (data and code), PT_INTERP
(to tell which runtime loader to use), PT_DYNAMIC
(to tell which shared libraries to use, and other info for ld.so
), PT_NOTE
(for linker build-id), and PT_PHDR
. Each of these will have its own program header.
Upvotes: 2