From 57357c43e3b56fd636cd08af591c50a08223b654 Mon Sep 17 00:00:00 2001 From: Jakub Konka Date: Wed, 9 Feb 2022 23:45:50 +0100 Subject: [PATCH] elf: pad out file to the required size when init data We need to pad out the file to the required maximum size equal the final section's offset plus the section's size. We only need to this when populating initial metadata and only when section header was updated. --- src/link/Elf.zig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/link/Elf.zig b/src/link/Elf.zig index 9ab84de1ce..23bd5bb2dd 100644 --- a/src/link/Elf.zig +++ b/src/link/Elf.zig @@ -922,6 +922,21 @@ pub fn populateMissingMetadata(self: *Elf) !void { } // We are starting with an empty file. The default values are correct, null and empty list. } + + if (self.shdr_table_dirty) { + // We need to find out what the max file offset is according to section headers. + // Otherwise, we may end up with an ELF binary with file size not matching the final section's + // offset + it's filesize. + var max_file_offset: u64 = 0; + + for (self.sections.items) |shdr| { + if (shdr.sh_offset + shdr.sh_size > max_file_offset) { + max_file_offset = shdr.sh_offset + shdr.sh_size; + } + } + + try self.base.file.?.pwriteAll(&[_]u8{0}, max_file_offset); + } } pub const abbrev_compile_unit = 1;