Reputation: 1
Quoting the man page:
All data structures that the file format defines follow the "natural" size and alignment guidelines for the relevant class. If necessary, data structures contain explicit padding to ensure 4-byte alignment for 4-byte objects, to force structure sizes to a multiple of 4, and so on.
But since aligment is implementation defined I imagine that is not a good pratice suppose that the structures are allways packed.
For example, the following (pseudocode) can falls in some systems/compilers:
unsigned char e_ident[EI_NIDENT]; // Supposing that sizeof(unsigned char) == sizeof(uint8_t)
Elf32_Ehdr *ehdr;
// First read the e_ident
fread(e_ident, EI_NIDENT, 1, file_ptr);
// Now read the ELF header
if(e_ident[EI_CLASS] == ELFCLASS32){
ehdr = malloc(sizeof(Elf32_Ehdr));
memcpy(ehdr->e_ident, e_ident, EI_NIDENT);
fread(&(ehdr->e_type), sizeof(uint8_t), sizeof(Elf32_Ehdr) - (size_t)EI_NIDENT, file_ptr);
}
On negative answer for the main question, there is some portable way to ensure that elf.h
structures are packed?
NOTE: I'm using the elf.h
from musl.
Upvotes: 0
Views: 55
Reputation: 114
Generally, the alignment is something done by your compiler and is not explicitly defined by elf.h
(Although you can use attributes like __attribute__((packed, aligned(4)))
to do so); therefore, there is not going to be a compatibility issue with any standard system. Whenever you compile your program using your target platform's compiler, the compiler is going to obey the alignment specification according to your platform's ABI; thus any compiler generates the output object with the correct alignment and padding (if required).
In special cases (When explicit attribute are used for structures), you may want to lookup for the elf.h
written for that specific system. These kind of explicit declarations may also be useful when you're cross-compiling.
Upvotes: 0