I wish to know if ELF format has specified that each section should be aligned to 4kb boundary? Or, only on x86 platform, the 'implementation' of ELF should align each section to 4kb boundary.
Is there any specification to judge about this?
I wish to know if ELF format has specified that each section should be aligned to 4kb boundary? Or, only on x86 platform, the 'implementation' of ELF should align each section to 4kb boundary.
Is there any specification to judge about this?
The ELF 1.2 specifications describes entities that reside at a specific offset in the file, often denoted as p_offset
, and that will be loaded at a specific address in memory (often denoted as p_vaddr
).
The specification doesn't mandate any alignment of a segment directly.
However it requires that
Loadable process segments must have congruent values for
p_vaddr
andp_offset
, modulo the page size.
This member [p_align
] gives the value to which the segments are aligned in memory and in the file.
Values 0 and 1 mean that no alignment is required. Otherwise,p_align
should be a positive, integral power of 2, andp_addr
should equalp_offset
, modulop_align
.
The terminology is a bit off in my opinion (segments are not aligned in the usual sense, they don't start at a multiple of p_align
).
The rationale behind the quote is that the system must be able to quickly load a segment, it is thus necessary to avoid shifting it in memory to match its loading address.
The file when loaded are made of one or mode "unit" of memory, called pages.
Pages has generally fixed size, thus they all start at address that are multiple of their size.
For 32-bit x86 system, this size is 4KiB, imagine then a sequence of pages and their starting addresses:
Page 0 Page 1 Page 2 ... Page 4 ... Page 100 ... Page K
0 4096 8192 16384 409600 K*4096
The point is that is possible to change the address of a page very quickly, without copying any byte, this is called remapping.
Once the file is loaded the OS remaps the page of the file so that each segment is at its address specified in p_vaddr
.
Now if start of the segment in the file doesn't satisfy the conditions stated in the quote and p_align
is not a multiple of 4KiB, this "trick" won't work and the OS needs to revert to shifting the segment once loaded.
To make things easy and don't waste memory, segments are usually aligned to 4KiB in the file.