diff --git a/btf.lua b/btf.lua index 8ad381f..029c132 100644 --- a/btf.lua +++ b/btf.lua @@ -98,21 +98,30 @@ function types:integer(name, size, bits) end --- --- A function and the prototype under it. Parameters are named, as the kernel's BTF checker --- expects of a prototype that names any of them. --- @function luaebpf.btf.types:func --- @tparam string name --- @tparam integer linkage one of `btf.linkage` +-- A function prototype. Parameters are named, as the kernel's BTF checker expects of a prototype +-- that names any of them. +-- @function luaebpf.btf.types:proto -- @tparam table signature `{result, params}`, the result's type id and a type id per parameter --- @treturn integer the `FUNC` type id -function types:func(name, linkage, signature) +-- @treturn integer the `FUNC_PROTO` type id +function types:proto(signature) local params = {} for i, id in ipairs(signature.params) do table.insert(params, string.pack(self.order .. "I4I4", self:string("a" .. i), id)) end - local proto = self:add(string.pack(self.order .. "I4I4I4", 0, typeinfo(KIND_FUNC_PROTO, #params), signature.result) + return self:add(string.pack(self.order .. "I4I4I4", 0, typeinfo(KIND_FUNC_PROTO, #params), signature.result) .. table.concat(params)) - return self:add(string.pack(self.order .. "I4I4I4", self:string(name), typeinfo(KIND_FUNC, linkage), proto)) +end + +--- +-- A function and the prototype under it. +-- @function luaebpf.btf.types:func +-- @tparam string name +-- @tparam integer linkage one of `btf.linkage` +-- @tparam table signature `{result, params}`, the result's type id and a type id per parameter +-- @treturn integer the `FUNC` type id +function types:func(name, linkage, signature) + return self:add(string.pack(self.order .. "I4I4I4", self:string(name), typeinfo(KIND_FUNC, linkage), + self:proto(signature))) end --- @@ -153,6 +162,25 @@ function types:struct(name, members) .. table.concat(fields)), size end +--- +-- A struct of `members`, each `{name, type, offset}` with `offset` a byte offset, of an explicit +-- `size`. Where `types:struct` lays its members one word apart, this takes a kernel struct's own +-- offsets and whole size, for a `.struct_ops` whose members libbpf matches to the kernel's by name. +-- @function luaebpf.btf.types:record +-- @tparam string name +-- @tparam table members +-- @tparam integer size in bytes +-- @treturn integer the `STRUCT` type id +function types:record(name, members, size) + local fields = {} + for _, member in ipairs(members) do + table.insert(fields, string.pack(self.order .. "I4I4I4", self:string(member.name), member.type, + member.offset * BYTE)) + end + return self:add(string.pack(self.order .. "I4I4I4", self:string(name), typeinfo(KIND_STRUCT, #members), size) + .. table.concat(fields)) +end + --- -- A variable of `id` allocated in a section. -- @function luaebpf.btf.types:var diff --git a/doc/guide/08-luaebpf.md b/doc/guide/08-luaebpf.md index 8b0cec1..7813f49 100644 --- a/doc/guide/08-luaebpf.md +++ b/doc/guide/08-luaebpf.md @@ -658,6 +658,51 @@ Each refusal reads `lunatik: :: `. | the map key -1 does not fit 'I4' | a key or a value outside its spec | a value its spec packs | | module 'byteorder' not found | `require` of a C module | a Lua module under `/lib/modules/lua/`, or the directory `--scripts` names | +## Schedulers + +A program file may declare a **scheduler** instead of a device program. A scheduler is a +`struct sched_ext_ops`, the kernel's `sched_ext` (`CONFIG_SCHED_CLASS_EXT`, Linux 6.12 and later) +registers as a unit: the functions it carries are its callbacks, each compiled to eBPF and run by +the kernel at a scheduling event, and its scalar fields configure it. `bpf.scx.scheduler` declares +one, and the object `lunatik bpf` writes carries a `.struct_ops` section rather than a program per +device hook. + +This first slice is the minimal scheduler, a `name` and an `init` callback that takes no argument +and returns `0` to let it load: + +```Lua +local scx = require("bpf.scx") + +return scx.scheduler{ + name = "minimal", + init = function() return 0 end, +} +``` + +```Shell +sudo lunatik bpf -o /usr/local/lib/bpf/luaebpf/minimal.bpf.o minimal.bpf.lua +sudo lunatik run minimal +``` + +A scheduler takes **no device**: the kernel attaches it to no interface, it registers its +`struct_ops` with `sched_ext` as a whole, and from then on it schedules every task. So `lunatik run` +takes no `--dev`, and one given a scheduler is refused, `minimal is a scheduler and takes no device`, +as a device program given no `--dev` is refused the missing one. The run registers the scheduler and +pins the link that holds it at `/sys/fs/bpf/lunatik/minimal/-link`, the way it pins a device +program's link, so the scheduler stays registered once the command has exited; `lunatik stop minimal` +unregisters it and the kernel's default scheduler takes over again. + +A scheduler names a kernel Lua script beside it as a device program does, `minimal.lua`, whose +runtime `lunatik run` starts before it registers the scheduler, for a callback that +[calls into it](#calls-into-a-kernel-lua-runtime); the minimal scheduler names none, so no runtime +starts and `lunatik list` does not name it. + +`lunatik bpf` reads the kernel's `sched_ext_ops` from its BTF, so it compiles a scheduler only where +that BTF carries the struct, a kernel built with `CONFIG_SCHED_CLASS_EXT`: elsewhere the file is +refused, `the kernel BTF has no struct 'sched_ext_ops'`. The members the object sets, `init` and +`name` here, libbpf matches to the kernel's struct by name, at the kernel's own byte offsets and +whole size, so the object carries only those and loads on any kernel of that layout. + ## How a program file becomes a program ``` diff --git a/emit/call.lua b/emit/call.lua index b791834..b3d4be5 100644 --- a/emit/call.lua +++ b/emit/call.lua @@ -59,13 +59,13 @@ end local function returnvalue(f, pc, state, i) local value = state[i] - if f.isprogram then + if f.isprogram and f.unit.verdict then checkverdict(f, pc, value) end f.rettype = f.rettype | value.t if f.drop ~= "verdict" then f.code:alu(insn.alu.MOV, insn.reg.R0, frame.getreg(f, pc, state, i, insn.reg.R0)) - if f.isprogram then + if f.isprogram and f.unit.verdict then testverdict(f, pc, value) end end diff --git a/emit/init.lua b/emit/init.lua index fa01d66..5cba9b8 100644 --- a/emit/init.lua +++ b/emit/init.lua @@ -265,7 +265,9 @@ end --- -- Compiles one program: its function, and every function that function reaches. -- @function luaebpf.emit.program --- @tparam table program `{name, fn, default, error, drop, names, places, context, kfunc, actions}` +-- @tparam table program `{name, fn, default, error, drop, names, places, context, kfunc, actions, +-- verdict, structops}`, `verdict` false and `structops` true for a struct_ops callback, which +-- returns a plain value and takes no context argument -- @treturn table the frames, the program's own first -- @raise `a program takes one argument, the context`, and `:: ` for every -- construct the subset refuses @@ -273,7 +275,7 @@ function emit.program(program) local unit = { functions = {}, order = {}, lowering = {}, names = program.names or {}, places = program.places, default = program.default, error = program.error, drop = program.drop, context = program.context, - kfunc = program.kfunc, actions = program.actions, + kfunc = program.kfunc, actions = program.actions, verdict = program.verdict ~= false, -- no lowering can require luaebpf.emit back; read here, after the body that may set them ran maygoto = emit.maygoto, unaligned = emit.unaligned, bigendian = emit.bigendian, -- read here, at each compile, so from the directory luaebpf.proto.scripts named for it @@ -281,11 +283,14 @@ function emit.program(program) subprogram = subprogram, } local read = proto.read(program.fn) - if read.numparams > 1 then - error(string.format("%s:%d: a program takes one argument, the context", - (read.source:gsub("^@", "")), read.linedefined), 0) + local params = program.structops and {} or {CTX} + if read.numparams > #params then + error(string.format("%s:%d: %s", + (read.source:gsub("^@", "")), read.linedefined, + program.structops and "a scheduler callback takes no argument yet" + or "a program takes one argument, the context"), 0) end - compile(unit, program.fn, read, program.name, {CTX}, true) + compile(unit, program.fn, read, program.name, params, true) return unit.order end diff --git a/init.lua b/init.lua index 170fae7..8c3c90d 100644 --- a/init.lua +++ b/init.lua @@ -38,8 +38,9 @@ local function fromlib(name) end package.preload["bpf.vmlinux"] = fromlib -local maps = require("luaebpf.maps") -local programs = require("luaebpf.programs") +local maps = require("luaebpf.maps") +local structops = require("luaebpf.structops") +local programs = require("luaebpf.programs") local proto = require("luaebpf.proto") local emit = require("luaebpf.emit") local writer = require("luaebpf.writer") @@ -107,6 +108,7 @@ function luaebpf.compile(path, btffile, scripts) local chunk = proto.load(path) programs.reset() maps.reset() + structops.reset() vmlinux.open(btffile) proto.scripts(scripts) local host, cpath, kept = package.path, package.cpath, modnames() diff --git a/lib/bpf/scx.lua b/lib/bpf/scx.lua new file mode 100644 index 0000000..0bd9b6b --- /dev/null +++ b/lib/bpf/scx.lua @@ -0,0 +1,66 @@ +-- +-- SPDX-FileCopyrightText: (c) 2026 Ashwani Kumar Kamal +-- SPDX-License-Identifier: MIT OR GPL-2.0-only +-- + +--- +-- Declares a sched_ext scheduler in a program file. +-- +-- A scheduler is a `struct sched_ext_ops` the kernel registers as a unit: the functions it carries +-- are its callbacks, each compiled to eBPF and run by the kernel at a scheduling event, and its +-- scalar fields configure it. `scheduler` takes those as a table and hands the callbacks to the +-- compiler; the object it writes carries a `.struct_ops` section libbpf makes a struct_ops map of, +-- which `lunatik run`, with no device, loads and registers with sched_ext through +-- `bpf_map__attach_struct_ops`, pinning the link that holds the scheduler until `lunatik stop` +-- unregisters it. libbpf matches each member the object sets to the kernel's `sched_ext_ops` by +-- name, so the object carries only the members the scheduler names, at the kernel's own byte +-- offsets and whole size. +-- +-- This first slice takes `name`, the scheduler's name, and `init`, a callback of no arguments that +-- returns `0` to let the scheduler load. The scheduler loads on a kernel built with +-- `CONFIG_SCHED_CLASS_EXT` (6.12 and later). +-- @module bpf.scx +-- @usage +-- local scx = require("bpf.scx") +-- +-- return scx.scheduler{ +-- name = "minimal", +-- init = function() return 0 end, +-- } + +local programs = require("luaebpf.programs") +local structops = require("luaebpf.structops") +local vmlinux = require("bpf.vmlinux") + +-- the ops struct the kernel registers; its members' offsets and whole size shift between releases, +-- so the compiler reads them from the target kernel's BTF rather than carrying one release's numbers +local STRUCT = "sched_ext_ops" + +local scx = {} + +--- +-- Declares a scheduler. +-- @function bpf.scx.scheduler +-- @tparam table opts `name`, the scheduler's name, cut to the bytes `sched_ext_ops.name` holds; +-- `init`, a callback of no arguments returning an `s32`, `0` where the scheduler is to load; and +-- `license`, the license the object declares, `Dual MIT/GPL` where it names none +-- @treturn table the declared `init` program +-- @raise `scx.scheduler takes a Lua function`, or `:: a scheduler callback takes no +-- argument yet`, `the kernel BTF has no struct 'sched_ext_ops'` on a kernel without sched_ext, or +-- `a scheduler is declared twice` +function scx.scheduler(opts) + local ops = vmlinux.members(STRUCT) + local init = assert(ops.members.init, "the kernel's sched_ext_ops has no init member") + local field = assert(ops.members.name, "the kernel's sched_ext_ops has no name member") + local program = programs.declare("scx.scheduler", opts.init, {section = "struct_ops/init", + verdict = false, structops = true, license = opts.license}) + local name = (opts.name or "scx"):sub(1, field.size - 1) + assert(structops.declare{name = name:gsub("[^%w_]", "_"), struct = STRUCT, size = ops.size, members = { + {name = "init", offset = init.offset, program = program, proto = {params = {}}}, + {name = "name", offset = field.offset, bytes = name .. ("\0"):rep(field.size - #name)}, + }}, "a scheduler is declared twice") + return program +end + +return scx + diff --git a/lib/bpf/vmlinux.lua b/lib/bpf/vmlinux.lua index 005e092..83bf81a 100644 --- a/lib/bpf/vmlinux.lua +++ b/lib/bpf/vmlinux.lua @@ -27,10 +27,12 @@ local TYPESIZE = 12 local MEMBER = 12 local BYTE = 8 local WIDEST = 8 -- bytes of the widest load +local POINTER = 8 -- a pointer is a word on the 64-bit kernels struct_ops runs on local NESTING = 16 -- qualifiers a member's type may be wrapped in, so a cycle ends -- uapi/linux/btf.h, BTF_KIND_* local INT = 1 +local PTR = 2 local ARRAY = 3 local STRUCT = 4 local UNION = 5 @@ -275,5 +277,59 @@ function vmlinux.layout(what) return {size = size, fields = fields, bitfields = bitfields} end +-- the byte size of a member's type: a pointer a word, an array its element's size times its count, +-- an integer, struct, union or enum the size its record carries, read through the qualifiers a +-- declaration may wrap it in +local function memsize(self, id) + for _ = 1, NESTING do + local at = self.offsets[id] + if at == nil then + return nil + end + local _, info, size = string.unpack(self.order .. "I4I4I4", self.bytes, at) + local kind = (info >> 24) & 0x1f + if kind == PTR then + return POINTER + elseif kind == ARRAY then + local elem, _, nelems = string.unpack(self.order .. "I4I4I4", self.bytes, at + TYPESIZE) + local esize = memsize(self, elem) + return esize and esize * nelems + elseif qualifiers[kind] then + id = size + else + return size + end + end + return nil +end + +--- +-- The byte offset and size of every member of a kernel struct, by name, and the struct's whole +-- size. Where `layout` reports only the integer members a `struct` codec reads, this reports every +-- member -- a function pointer and an array among them -- for a `.struct_ops` the compiler lays out +-- at the kernel's own offsets, which shift between releases. +-- @function bpf.vmlinux.members +-- @tparam string what the struct's name, as `bpftool btf dump` prints it +-- @treturn table `{size = bytes, members = { = {offset = bytes, size = bytes}, ...}}` +-- @raise `: `, when the BTF file cannot be read, and `the kernel BTF has no struct +-- ''` +function vmlinux.members(what) + local self = reader() + local id = self.structs[what] + if id == nil then + error(("the kernel BTF has no struct '%s'"):format(what), 0) + end + local at = self.offsets[id] + local _, info, size = string.unpack(self.order .. "I4I4I4", self.bytes, at) + local vlen, kflag = info & 0xffff, info >> 31 + local found = {} + for i = 0, vlen - 1 do + local nameoff, typeid, offset = string.unpack(self.order .. "I4I4I4", self.bytes, at + TYPESIZE + i * MEMBER) + local bit = kflag == 1 and offset & 0xffffff or offset + found[name(self, nameoff)] = {offset = bit // BYTE, size = memsize(self, typeid)} + end + return {size = size, members = found} +end + return vmlinux diff --git a/loader.c b/loader.c index 1a90567..04703a6 100644 --- a/loader.c +++ b/loader.c @@ -6,9 +6,10 @@ /* * luaebpf.loader: the libbpf half of `lunatik run`, a C module of the CLI's Lua. It opens a * script's compiled program, pins the maps the program declares under the script's root, attaches -* every program to a device and pins each link, which keeps the program attached once the command -* has exited, and reads back an entry of a pinned map. Every function answers nil and a message -* rather than raising, so the CLI decides what to undo. +* every program to a device and pins each link, or, where the program is a scheduler the kernel +* registers, registers each `struct_ops` map and pins its link rather than attaching to a device, +* which keeps the program attached once the command has exited, and reads back an entry of a pinned +* map. Every function answers nil and a message rather than raising, so the CLI decides what to undo. */ #include @@ -78,6 +79,12 @@ static inline int lualoader_istcx(const struct bpf_program *program) return strncmp(bpf_program__section_name(program), LUALOADER_TCX, strlen(LUALOADER_TCX)) == 0; } +/* a struct_ops map the kernel registers as a unit, a scheduler, which attaches to no device */ +static inline int lualoader_isstructops(const struct bpf_map *map) +{ + return bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS; +} + static struct bpf_link *lualoader_attachprogram(const struct bpf_program *program, int ifindex) { #if LUALOADER_HASTCX @@ -132,6 +139,9 @@ static int lualoader_load(lua_State *L) /* .data, which no script opens, and whose dotted name bpffs refuses */ else if (bpf_map__is_internal(map)) continue; + /* a scheduler's ops map is held by the link register pins, not pinned itself */ + else if (lualoader_isstructops(map)) + continue; else path = lua_pushfstring(L, "%s/%s", root, bpf_map__name(map)); if (bpf_map__set_pin_path(map, path) != 0) @@ -173,6 +183,51 @@ static int lualoader_attach(lua_State *L) return 1; } +/* whether the object carries a struct_ops map, a scheduler the CLI registers with no device */ +static int lualoader_scheduler(lua_State *L) +{ + lualoader_t *loader = luaL_checkudata(L, 1, LUALOADER_OBJECT); + struct bpf_map *map; + + bpf_object__for_each_map(map, loader->object) + if (lualoader_isstructops(map)) { + lua_pushboolean(L, 1); + return 1; + } + lua_pushboolean(L, 0); + return 1; +} + +/* registers every struct_ops map and pins its link, which holds the scheduler once the command has + * exited, the way attach pins a program's; the kernel attaches a scheduler to no device */ +static int lualoader_register(lua_State *L) +{ + lualoader_t *loader = luaL_checkudata(L, 1, LUALOADER_OBJECT); + const char *root = luaL_checkstring(L, 2); + struct bpf_map *map; + + bpf_object__for_each_map(map, loader->object) { + const char *name, *path; + struct bpf_link *link; + int err; + + if (!lualoader_isstructops(map)) + continue; + name = bpf_map__name(map); + path = lua_pushfstring(L, LUALOADER_LINK, root, name); + link = bpf_map__attach_struct_ops(map); + if (link == NULL) + return lualoader_fail(L, "couldn't register %s: %s", name, lualoader_strerror(errno)); + err = bpf_link__pin(link, path); + bpf_link__destroy(link); /* closes the link: its pin holds it, or the close unregisters it */ + if (err != 0) + return lualoader_fail(L, "couldn't pin %s: %s", path, lualoader_strerror(err)); + lua_pop(L, 1); + } + lua_pushboolean(L, 1); + return 1; +} + /* the release an unlinked pin leaves detaches from a work item (bpf_link_put), this in the call */ static int lualoader_detach(lua_State *L) { @@ -252,6 +307,8 @@ static int lualoader_lookup(lua_State *L) static const luaL_Reg lualoader_mt[] = { {"load", lualoader_load}, {"attach", lualoader_attach}, + {"scheduler", lualoader_scheduler}, + {"register", lualoader_register}, {"__gc", lualoader_gc}, {NULL, NULL} }; diff --git a/programs.lua b/programs.lua index 655ebb0..eb72195 100644 --- a/programs.lua +++ b/programs.lua @@ -73,9 +73,10 @@ end -- @function luaebpf.programs.declare -- @tparam string constructor the constructor the program file called, `xdp.program` or its peer -- @tparam function fn the program --- @tparam table program `{section, default, error, name, license, context, kfunc, actions}`, --- `actions` the verdicts of its type, `{first, last, name}`, and `license`, `Dual MIT/GPL` where --- it is nil +-- @tparam table program `{section, default, error, name, license, context, kfunc, actions, +-- verdict, structops}`, `actions` the verdicts of its type, `{first, last, name}`, `license`, +-- `Dual MIT/GPL` where it is nil, and `verdict` false for a struct_ops callback, which returns a +-- plain value rather than a verdict and so names no `default` or `actions` -- @treturn table the program, with `fn` -- @raise ` takes a Lua function`, or `:: 's default verdict -- is not an integer` or `is not `, or `:: 's license is @@ -85,9 +86,12 @@ function programs.declare(constructor, fn, program) if type(fn) ~= "function" or debug.getinfo(fn, "S").what == "C" then error(string.format("%s takes a Lua function", constructor), 2) -- each constructor tail-calls declare end - local expected = unmet(program) - if expected ~= nil then - refuse(constructor, fn, "default verdict is not " .. expected) + -- a struct_ops callback returns a plain value its kernel struct types, not a verdict + if program.verdict ~= false then + local expected = unmet(program) + if expected ~= nil then + refuse(constructor, fn, "default verdict is not " .. expected) + end end if program.license == nil then program.license = LICENSE diff --git a/structops.lua b/structops.lua new file mode 100644 index 0000000..2070f1c --- /dev/null +++ b/structops.lua @@ -0,0 +1,54 @@ +-- +-- SPDX-FileCopyrightText: (c) 2026 Ashwani Kumar Kamal +-- SPDX-License-Identifier: MIT OR GPL-2.0-only +-- + +--- +-- Where `bpf.scx` leaves the struct_ops object a program file's body declared. +-- +-- A struct_ops object is a kernel struct of function pointers and scalars the kernel registers as a +-- unit: `sched_ext_ops` is one. The file body hands its callbacks and attributes to `bpf.scx`, +-- which records them here; `luaebpf.writer` reads them back and writes the `.struct_ops` section +-- libbpf makes a map of. A member that carries a program names the program `luaebpf.programs` +-- holds, so the writer relocates the member to that program's entry once it has an address. +-- @module luaebpf.structops + +local declared = {} +local named = {} + +local structops = {} + +--- +-- Forgets what a previous compilation declared. +-- @function luaebpf.structops.reset +function structops.reset() + declared, named = {}, {} +end + +--- +-- Records one struct_ops object. +-- @function luaebpf.structops.declare +-- @tparam table ops `{name, struct, size, members}`: the name of its variable in the object, the +-- kernel struct it is an instance of, that struct's whole size in bytes, and the members it sets, +-- each `{name, offset}` with either a `program` and its `proto` `{result, params}`, or the +-- `bytes` of a scalar member +-- @treturn table|nil the same object, or `nil` when that name is already taken +function structops.declare(ops) + if named[ops.name] ~= nil then + return nil + end + named[ops.name] = ops + table.insert(declared, ops) + return ops +end + +--- +-- The struct_ops objects the file body declared, in order. +-- @function luaebpf.structops.declared +-- @treturn table +function structops.declared() + return declared +end + +return structops + diff --git a/writer.lua b/writer.lua index d768119..71dfe6c 100644 --- a/writer.lua +++ b/writer.lua @@ -18,6 +18,7 @@ -- @module luaebpf.writer local maps = require("luaebpf.maps") +local structops = require("luaebpf.structops") local emit = require("luaebpf.emit") local insn = require("luaebpf.insn") local elf = require("luaebpf.elf") @@ -27,6 +28,8 @@ local TEXT = ".text" local MAPS = ".maps" local KSYMS = ".ksyms" local DATA = ".data" +local STRUCTOPS = ".struct_ops" +local BYTE = 8 local PLACES = ".data.luaebpf_errors" local writer = {} @@ -156,6 +159,59 @@ local function maplayout(object, types, declared) return symbols end +-- a struct_ops object's bytes: the scalar members at their offsets in a buffer of the struct's +-- whole size, the member that carries a program left zero for the relocation to patch +local function record(size, blocks) + table.sort(blocks, function(a, b) return a.offset < b.offset end) + local out, at = {}, 0 + for _, block in ipairs(blocks) do + table.insert(out, ("\0"):rep(block.offset - at)) + table.insert(out, block.bytes) + at = block.offset + #block.bytes + end + table.insert(out, ("\0"):rep(size - at)) + return table.concat(out) +end + +-- The `.struct_ops` section libbpf makes a struct_ops map of: a VAR of the ops struct, allocated in +-- a DATASEC of that name, holding the members the scheduler set; libbpf matches each to the kernel's +-- struct by name (tools/lib/bpf/libbpf.c), so the struct carries only those, at the kernel's own +-- offsets and whole size. A member that carries a program is a pointer the writer relocates to that +-- program's entry, which is why this runs once the entries have addresses. Returns the var symbols +-- and the relocations, each naming the program entry it patches the member to. +local function structopslayout(object, types, declared) + if #declared == 0 then + return {}, {} + end + local char = types:integer("char", 1, BYTE) + local entries, symbols, section, relocations, at = {}, {}, {}, {}, 0 + for _, ops in ipairs(declared) do + local members, blocks = {}, {} + for _, member in ipairs(ops.members) do + local id + if member.program ~= nil then + id = types:pointer(types:proto{result = types.int, params = member.proto.params}) + table.insert(relocations, {at = at + member.offset, name = member.program.entryname, + type = elf.relocation.IMM64}) + else + id = types:array(char, #member.bytes) + table.insert(blocks, {offset = member.offset, bytes = member.bytes}) + end + table.insert(members, {name = member.name, type = id, offset = member.offset}) + end + local id = types:record(ops.struct, members, ops.size) + table.insert(entries, {type = types:var(ops.name, id), offset = at, size = ops.size}) + table.insert(symbols, {name = ops.name, section = STRUCTOPS, value = at, size = ops.size, + bind = elf.bind.GLOBAL, type = elf.type.OBJECT}) + table.insert(section, record(ops.size, blocks)) + at = at + ops.size + end + object:section{name = STRUCTOPS, type = elf.section.PROGBITS, flags = elf.flags.ALLOC | + elf.flags.WRITE, data = table.concat(section), align = 8} + types:datasec(STRUCTOPS, entries) + return symbols, relocations +end + -- each symbol of `list` in the object, under the name a relocation looks it up by local function named(object, indexes, list) for _, symbol in ipairs(list) do @@ -255,7 +311,9 @@ end local function reserve(names, declared) names[emit.ERRORS] = true for _, program in ipairs(declared) do - names[program.kfunc] = true + if program.kfunc ~= nil then -- a struct_ops callback names no runtime kfunc + names[program.kfunc] = true + end end end @@ -315,6 +373,7 @@ function writer.write(declared, hook) extern(externs, called, program, frame) constants(strings, kept, places, frame) if i == 1 then + program.entryname = frame.name -- a struct_ops member relocates to this symbol table.insert(order, {name = frame.name, section = program.section, value = at, size = frame.code:len() * insn.SIZE, bind = elf.bind.GLOBAL, type = elf.type.FUNC}) @@ -335,9 +394,11 @@ function writer.write(declared, hook) named(object, indexes, datasymbols) placelayout(object, indexes, places) for _, entry in ipairs(order) do - object:symbol(entry) + indexes[entry.name] = object:symbol(entry) -- a struct_ops member relocates to a program entry end named(object, indexes, mapsymbols) + local structsymbols, structrelocs = structopslayout(object, types, structops.declared()) + named(object, indexes, structsymbols) ksyms(object, types, externs, hook, indexes) for _, unit in ipairs(units) do local records = {} @@ -348,6 +409,13 @@ function writer.write(declared, hook) object:relocations(unit.name, records) end end + if #structrelocs > 0 then + local records = {} + for _, reloc in ipairs(structrelocs) do + table.insert(records, {at = reloc.at, symbol = indexes[reloc.name], type = reloc.type}) + end + object:relocations(STRUCTOPS, records) + end object:section{name = "license", type = elf.section.PROGBITS, flags = elf.flags.ALLOC | elf.flags.WRITE, data = declared[1].license .. "\0", align = 1}