How to use the sh_addralign?

Viewed 582

I am working on elf reader, I couldn't understand the purpose of "sh_addralign" from the elf doc. it says as below

Some sections have address alignment constraints. For example, if a section holds a doubleword, the system must ensure doubleword alignment for the entire section. That is, the value of sh_addr must be congruent to 0, modulo the value of sh_addralign. Currently, only 0 and positive integral powers of two are allowed. Values 0 and 1 mean the section has no alignment constraints. "

Can someone please explain me with some calcualation? and also why it is important ?

2 Answers

I am working on elf reader, I couldn't understand the purpose of "sh_addralign"

For an ELF reader, sh_addralign serves no purpose.

Its only purpose is to tell the linker (which writes ELF) that it must arrange for the section contents to be properly aligned in memory.

The original creator of that section expected that alignment.

So for example, if it's 0, then the creator doesn't know or care. If it's a string table then the creator might use 1 but could use 0, 1, 2, 4, 8, ... If, as in the example, the section contains a double then the creator could say 8, 16, .... If it's RISC-V text then the alignment would be 4. If the section is being addressed with cache line aware code then it might want 64 byte alignment.

Only the creator knows these requirements and they are expecting the next tool in the chain to respect those alignments. Recall that ELF was spec'd in the mid 90s. Today with GB memories, wasting a small amount of alignment space for better performance is a good tradeoff. Read that as a recommendation to over-align.

Related