diff options
| author | Sunil Nimmagadda <sunil@nimmagadda.net> | 2026-11-04 22:01:47 +0530 |
|---|---|---|
| committer | Sunil Nimmagadda <sunil@nimmagadda.net> | 2026-11-04 22:01:47 +0530 |
| commit | c27026469be8c8ae3b947175bf0c4352e481f09e (patch) | |
| tree | f6c5bac21604595869234f7ddd10d1d96b5bbb25 | |
| parent | 2322f64295b6c02101e0327b3a03325715b73627 (diff) | |
Pack before opening the file for write.
Any pack errors shouldn't cause partial writes. Assemble binary in
memory before opening the out file.
| -rw-r--r-- | mkelf.lua | 21 |
1 files changed, 14 insertions, 7 deletions
@@ -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 <close>, 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 |
