So does this really mean you cannot have packed structs that are odd size? That would be really strange indeed.
To add to your experiment, also a strange thing is that the original Elf64ExecutionHeader packed struct is 64 bytes in size (so even number). And it still fails if you want to print out certain fields with alignment issue, even though const header: *Elf64ExecutionHeader = @ptrCast(@alignCast(&buffer));
produced no errors. Crash only happens when I try to print it out (then I get alignment issue).
std.debug.print("Object file type: {}\n", .{header.type});
std.debug.print("Architecture: {}\n", .{header.machine});
std.debug.print("Object file version: 0x{X:0>2}\n", .{header.version});
std.debug.print("Entry point virtual address: 0x{X:0>2}\n", .{header.entry});
std.debug.print("Program header table file offset: {}\n", .{header.phoff});
std.debug.print("Section header table file offset: {}\n", .{header.shoff});
std.debug.print("Processor-specific flags: 0x{X:0>2}\n", .{header.flags});
std.debug.print("ELF header size in bytes: {}\n", .{header.ehsize});
std.debug.print("Program header table entry size: {}\n", .{header.phentsize});
// std.debug.print("Program header table entry count: {}\n", .{header.phnum});
// std.debug.print("Section header table entry size: {}\n", .{header.shentsize});
// std.debug.print("Section header table entry count: {}\n", .{header.shnum});
// std.debug.print("Section header string table index: {}\n", .{header.shstrndx});
I intentionally don’t print out the bottom 4 fields because the program crashes.
zig run main.zig
thread 2199375 panic: incorrect alignment
/home/m/Vault/projects/probe/zig-elf/main.zig:36:43: 0x103920a in main (main)
const header: *Elf64ExecutionHeader = @ptrCast(@alignCast(&buffer));
^
/home/m/.local/bin/zig-linux-x86_64-0.14.0-dev.1587+feaee2ba1/lib/std/start.zig:619:37: 0x1038eb2 in posixCallMainAndExit (main)
const result = root.main() catch |err| {
^
/home/m/.local/bin/zig-linux-x86_64-0.14.0-dev.1587+feaee2ba1/lib/std/start.zig:250:5: 0x1038a8f in _start (main)
asm volatile (switch (native_arch) {
^
???:?:?: 0x0 in ??? (???)
This crash happens when I try to print std.debug.print("Program header table entry count: {}\n", .{header.phnum});
that is commented out from my example above.
Additionally, I added @sizeOf
and @bitSizeOf
to check the struct size just to be sure, and they are the same.
sizeOf(Elf64ExecutionHeader) = 64
bitSizeOf(Elf64ExecutionHeader) = 512 (512/8=64)
I am baffled by this. There must be an explanation for this.