From 0ea23536cd0959ebcdb19b036310cdf455f4219d Mon Sep 17 00:00:00 2001 From: Sunil Nimmagadda Date: Wed, 4 Nov 2026 22:26:45 +0530 Subject: Pack first in memory and then write. --- mkelf.lua | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/mkelf.lua b/mkelf.lua index 3b80aec..6ab42e0 100644 --- a/mkelf.lua +++ b/mkelf.lua @@ -86,15 +86,19 @@ local function loadconfig(fn) return state.header, state.segments, state.sections end +---@param header Header +---@param segments Segment[] +---@param sections Section[] +---@return string local function elf_pack(header, segments, sections) - local binary = elf.header.pack(header) + local parts = { elf.header.pack(header) } for _, segment in ipairs(segments) do - binary = binary .. elf.segment.pack(segment, header.class, header.endian) + parts[#parts + 1] = elf.segment.pack(segment, header.data, header.class) end for _, section in ipairs(sections) do - binary = binary .. elf.section.pack(section, header.class, header.endian) + parts[#parts + 1] = elf.section.pack(section, header.data, header.class) end - return binary + return table.concat(parts) end local M = {} @@ -119,11 +123,12 @@ function M.main() -- TODO check against headerOptions not normalized header. -- if header.phnum == 0 then header.phnum = #segments end -- if header.shnum == 0 then header.shnum = #sections end + local ok, binary = pcall(elf_pack, header, segments, sections) + if not ok then die("packing failed: %s", binary) 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 - local ok, werr = out:write(binary) - if not ok then die("write failed: %s", werr) end + if out == nil then die("failed to open: %s", err) end + local wok, werr = out:write(binary) + if not wok then die("write failed: %s", werr) end end return M -- cgit v1.3