3

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

5

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 and p_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, and p_addr should equal p_offset, modulo p_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.

Sections loaded in memory

Now if start of the segment in the file doesn't satisfy the conditions stated in the quote and p_alignis 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.

Margaret Bloom
  • 41,768
  • 5
  • 78
  • 124
  • 2
    Note that the question is about sections (which have no 4KiB alignment requirements whatsoever). It's not clear whether the OP understand the distinction between sections and segments. – Employed Russian Oct 08 '16 at 03:16
  • In the right figure, why there is *data* padding in **text** segment and *text* padding in **data** seggment? – rosshjb Aug 02 '23 at 09:54