aboutsummaryrefslogtreecommitdiff
path: root/mkelf.lua
blob: d350a8d10d4c72b09abb5c41ae704fec28cc2924 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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

local function setup_header(state)
    return function (t)
        if type(t) ~= "table" then
            error("header must be a table", 2)
        end
        if state.hopts ~= nil then
            error("multiple headers are disallowed", 2)
        end
        if not t.class then error("class is required in header", 2) end
        if not t.data then error("data is required in header", 2) end
        if not t.type then error("type is required in header", 2) end
        if not t.machine then error("machine is required in header", 2) end
        -- Can't pack without these values being valid.
        if t.class ~= ec.Class.bit32 and t.class ~= ec.Class.bit64 then
            error("class must be Class.bit32 or Class.bit64 in header", 2)
        end
        if t.data ~= ec.Endian.little and t.data ~= ec.Endian.big then
            error("data must be Endian.little or Endian.big in header", 2)
        end
        state.hopts = t
    end
end

local function setup_segments(state)
    return function (t)
        if type(t) ~= "table" then
            error("segments must be a table", 2)
        end
        for i, s in ipairs(t) do
            if type(s) ~= "table" then
                error(("segment #%d must be a table"):format(i), 2)
            end
            if not s.type then
                error(("type is required in segment #%d"):format(i), 2)
            end
            table.insert(state.sgopts, s)
        end
    end
end

local function setup_sections(state)
    return function (t)
        if type(t) ~= "table" then
            error("sections must be a table", 2)
        end
        for i, s in ipairs(t) do
            if type(s) ~= "table" then
                error(("section #%d must be a table"):format(i), 2)
            end
            if not s.name then
                error(("name is required in section #%d"):format(i), 2)
            end
            if not s.type then
                error(("type is required in section #%d"):format(i), 2)
            end
            if not s.flags then
                error(("flags required in section #%d"):format(i), 2)
            end
            table.insert(state.scopts, s)
        end
    end
end

local function setup_env(state)
    return setmetatable({}, {
        __index = {
            Class = ec.Class,
            Endian = ec.Endian,
            Osabi = ec.Osabi,
            Type = ec.Type,
            Machine = ec.Machine,
            SegmentType = ec.SegmentType,
            SegmentFlags = ec.SegmentFlags,
            SectionType = ec.SectionType,
            SectionFlags = ec.SectionFlags,
            ELFVERSION = ec.VERSION,
            header = setup_header(state),
            segments = setup_segments(state),
            sections = setup_sections(state),
        },
        __newindex = function (_, name)
            error(("may not define global %q"):format(name), 2)
        end,
        __metatable = false,
    })
end

---@param fn string | nil
---@return HeaderOptions, SegmentOptions[], SectionOptions[]
local function loadconfig(fn)
    local state = {
        ---@type HeaderOptions?
        hopts = nil,
        sgopts = {},
        scopts = {},
    }
    local env = setup_env(state)
    local chunk, err = loadfile(fn, "t", env)
    if not chunk then die("%s", err) end
    -- TODO sandbox against malformed configs
    local ok, perr = pcall(chunk)
    if not ok then die("%s", perr) end
    if not state.hopts then die("header missing") end
    return state.hopts, state.sgopts, state.scopts
end

---@param hopts  HeaderOptions
---@param sgopts SegmentOptions[]
---@param scopts SectionOptions[]
---@return Header, Segment[], Section[]
local function elf_layout(hopts, sgopts, scopts)
    -- TODO layout calculations with user config as first preference.
    ---@type Header?
    local header = nil
    ---@type Segment[]
    local segments = {}
    ---@type Section[]
    local sections = {}
    header = elf.header.normalize(hopts)
    for _, sgopt in ipairs(sgopts) do
        table.insert(segments, elf.segment.normalize(sgopt))
    end
    for _, scopt in ipairs(scopts) do
        table.insert(sections, elf.section.normalize(scopt))
    end
    return header, segments, sections
end

---@param header   Header
---@param segments Segment[]
---@param sections Section[]
---@return string
local function elf_pack(header, segments, sections)
    local parts = {}
    local ok, b = pcall(elf.header.pack, header)
    if not ok then error(("header: %s"):format(b), 0) end
    parts[#parts + 1] = b
    for i, sg in ipairs(segments) do
        local sgok, sgb = pcall(elf.segment.pack, sg, header.data, header.class)
        if not sgok then error(("segment #%d: %s"):format(i, sgb), 0) end
        parts[#parts + 1] = sgb
    end
    for i, sc in ipairs(sections) do
        local scok, scb = pcall(elf.section.pack, sc, header.data, header.class)
        if not scok then error(("section #%d: %s"):format(i, scb), 0) end
        parts[#parts + 1] = scb
    end
    return table.concat(parts)
end

local M = {}

function M.main()
    local outfn = "a.out"
    local infn
    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 == nil then
            infn = arg[i]
        else
            usage()
        end
        i = i + 1
    end
    local hopts, sgopts, scopts = loadconfig(infn)
    local header, segments, sections = elf_layout(hopts, sgopts, scopts)
    local ok, res
    ok, res = pcall(elf_pack, header, segments, sections)
    if not ok then die("packing failed: %s", res) end
    -- TODO write to tmp and atomic rename?
    local out, err = io.open(outfn, "wb")
    if not out then die("failed to open: %s", err) end
    ok, res = out:write(res)
    if not ok then die("write failed: %s", res) end
    ok, res = out:close()
    if not ok then die("failed to close %s:, res") end
end

return M