From c27026469be8c8ae3b947175bf0c4352e481f09e Mon Sep 17 00:00:00 2001 From: Sunil Nimmagadda Date: Wed, 4 Nov 2026 22:01:47 +0530 Subject: Pack before opening the file for write. Any pack errors shouldn't cause partial writes. Assemble binary in memory before opening the out file. --- mkelf.lua | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/mkelf.lua b/mkelf.lua index a66c779..3b80aec 100644 --- a/mkelf.lua +++ b/mkelf.lua @@ -86,6 +86,17 @@ local function loadconfig(fn) return state.header, state.segments, state.sections end +local function elf_pack(header, segments, sections) + local binary = elf.header.pack(header) + for _, segment in ipairs(segments) do + binary = binary .. elf.segment.pack(segment, header.class, header.endian) + end + for _, section in ipairs(sections) do + binary = binary .. elf.section.pack(section, header.class, header.endian) + end + return binary +end + local M = {} function M.main() @@ -109,14 +120,10 @@ function M.main() -- if header.phnum == 0 then header.phnum = #segments end -- if header.shnum == 0 then header.shnum = #sections end local out , err = io.open(outfn, "wb") + local binary = elf_pack(header, segments, sections) if out == nil then die("failed to open: %s", outfn, err) end - out:write(elf.header.pack(header)) - for _, segment in ipairs(segments) do - out:write(elf.segment.pack(segment, header.data, header.class)) - end - for _, section in ipairs(sections) do - out:write(elf.section.pack(section, header.data, header.class)) - end + local ok, werr = out:write(binary) + if not ok then die("write failed: %s", werr) end end return M -- cgit v1.3