local elf = require("elf") local ec = require("elf.constants") local function die(fmt, ...) io.stderr:write("mkelf: ", string.format(fmt, ...), "\n") os.exit(1, true) end local function usage() die("[-o output] input") end ---@param fn string|nil ---@return {header: Header, sections: Section[], segments: Segment[]} local function loadconfig(fn) local spec = {} local env = { -- Keep in sync with types/elf.d.lua Class = elf.Class, Endian = elf.Endian, Osabi = elf.Osabi, Type = elf.Type, Machine = elf.Machine, SegmentType = elf.SegmentType, SegmentFlags = elf.SegmentFlags, ELFVERSION = elf.VERSION, header = function(t) spec.header = t end, sections = function(t) spec.sections = t end, segments = function(t) spec.segments = t end, } -- TODO error check for multiple headers local chunk, err = loadfile(fn, "t", env) if not chunk then die("%s", err) end local ok, perr = pcall(chunk) if not ok then die("%s", perr) end return spec end local function main() local outfn, infn = "a.out", nil local i = 1 while arg[i] do if arg[i] == "-o" then i = i + 1 outfn = arg[i] or die("missing filename after -o") elseif infn then usage() else infn = arg[i] end i = i + 1 end local c = loadconfig(infn) c.header.phnum = #c.segments c.header.phentsize = (c.header.class == ec.Class.bit64) and 0x38 or 0x20 -- TODO write to a temp file and atomic rename to outfn. local out = assert(io.open(outfn, "wb")) out:write(elf.header.pack(c.header)) out:write(elf.segment.pack(c.segments, c.header.data, c.header.class)) -- TODO finish section.pack -- out:write(elf.section.pack(c.sections, c.header.data)) end main()