//! Addons: shared libraries that each bring a kind of pane (Kind.zig). //! //! The host's half: the libraries this process holds (each a copy of its //! file's bytes in a memfd, its BLAKE3, its head checked and its init //! run), shared by every core that took the same bytes and closed when no //! core and no job holds one; the scan of `$XDG_DATA_HOME/pardes/addons` //! and `/lib/pardes/addons` at start, which lists a library from //! the head it kept of it while its file is the same, and loads it at the //! first pane of its kind (`need`); the crash mark. An addon //! runs in this process: one that crashes takes the session with it. So a //! load is marked first (`addon-loading` in the data directory, holding //! its path) and unmarked after; a start that finds the mark moves it to //! `addon-crashed`, and skips that addon at every start until `Addon load` //! asks for it by path again. //! //! The core's half, deterministic: the `Addon` word, the `addon` event's //! update (the collisions, a reload's validate-then-swap, the panes that //! waited), unload, and /addons. Nothing there reads a host fact: what a //! library brought comes in the event, as data a replica's core takes too. const std = @import("std"); const Kind = @import("Kind.zig"); const dump = @import("dump.zig"); const pardes = @import("pardes.zig"); const tape = @import("tape.zig"); const Pardes = pardes.Pardes; const Why = Kind.Buf(160); /// What the effect asks: a library loaded (its path), loaded again for a /// kind's reload (the kind's path), or let go (its BLAKE3, the arg's bytes). pub const Op = enum { load, reload, release }; // ---- the libraries this process holds (the host's) ---- const Lib = struct { hash: [32]u8, handle: *anyopaque, ops: *const Kind.Ops, fd: c_int, refs: u32 = 1, jobs: u32 = 0 }; var libs: [32]?Lib = @splat(null); fn libOf(ops: *const Kind.Ops) ?*Lib { for (&libs) |*l| if (l.*) |*lib| if (lib.ops == ops) return lib; return null; } /// A job of `ops` under way (true), or answered: its library stays until /// the last of them, so no worker is unmapped under its own code. pub fn holdJob(ops: *const Kind.Ops, held: bool) void { const lib = libOf(ops) orelse return; if (held) lib.jobs += 1 else lib.jobs -|= 1; closeIdle(lib); } fn closeIdle(lib: *Lib) void { if (lib.refs > 0 or lib.jobs > 0) return; _ = std.c.dlclose(lib.handle); _ = std.c.close(lib.fd); for (&libs) |*l| if (l.*) |*x| if (x == lib) { l.* = null; }; } /// The host's side of the `addon` effect: the library read and checked, /// and what it brought (or why not) the core's `addon` event. pub fn perform(p: *Pardes, op: Op, pane: u8, arg: []const u8) void { if (op == .release) { for (&libs) |*l| if (l.*) |*lib| if (arg.len == 32 and std.mem.eql(u8, &lib.hash, arg)) { lib.refs -|= 1; return closeIdle(lib); }; return; } var words: [64]LoadedWord = undefined; var why: Why = .{}; const l = readLoaded(arg, &words, &why); p.update(.{ .addon = .{ .op = op, .pane = pane, .kind = &l } }); } /// What a load reads off the library at `path` (held): the `addon` /// event's, for a caller that steps its core itself (a replica's authority). pub fn readLoaded(path: []const u8, words: *[64]LoadedWord, why: *Why) Loaded { var data_buf: [4096]u8 = undefined; return read(dataDir(&data_buf), path, words, why); } /// The library at `path`, held (a second hold of the same bytes is the /// first's library) and checked: what it brings, or why not. fn read(data: []const u8, path: []const u8, words: *[64]LoadedWord, why: *Why) Loaded { if (comptime compiled_in.len > 0 or @import("builtin").os.tag != .linux) return .{ .path = path, .why = why.print("not on this platform: its addons are compiled in", .{}) }; var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return .{ .path = path, .why = why.print("the path is too long", .{}) }; const file = std.c.open(path_z, .{ .CLOEXEC = true }); if (file < 0) return .{ .path = path, .why = why.print("cannot read it", .{}) }; defer _ = std.c.close(file); return readOpen(data, path, file, words, why); } /// `read` of the library open at `file`. fn readOpen(data: []const u8, path: []const u8, file: c_int, words: *[64]LoadedWord, why: *Why) Loaded { mark(data, path); defer unmark(); var hash: [32]u8 = undefined; const lib = hold(file, &hash, false, why) orelse return .{ .path = path, .why = why.slice() }; const l = loadedOf(lib.ops, path, hash, words); const refused: ?[]const u8 = refused: { const h = &lib.ops.head; if (h.size < @sizeOf(Kind.c.pa_head)) break :refused "refused: its head is too short for this pardes"; if (h.abi >> 16 != Kind.abi_major) break :refused why.print("refused: wants abi {d}, this pardes speaks {d}", .{ h.abi >> 16, Kind.abi_major }); if (lib.ops.paint == null) break :refused "refused: it has no paint"; for (l.words) |w| if (w.opens == 0 and lib.ops.ctl == null) break :refused "refused: it has words for its panes and no ctl"; if ((lib.ops.job_run == null) != (lib.ops.job_done == null)) break :refused "refused: a job needs job_run and job_done"; if (h.nwords > words.len) break :refused "refused: no room for its words"; if (lib.ops.init) |init| if (init(&Kind.api) != Kind.c.PA_OK) break :refused "refused: its init failed"; break :refused null; }; const r = refused orelse return l; if (r.ptr != &why.bytes) why.set(r); // What is listed of it outlives its library: its name, in `words`. const name: []u8 = @as([*]u8, @ptrCast(words))[0..@min(15, l.name.len)]; @memcpy(name, l.name[0..name.len]); lib.refs -= 1; closeIdle(lib); return .{ .name = name, .version = l.version, .abi = l.abi, .hash = hash, .path = path, .why = why.slice() }; } /// The library open at `file` held: its bytes copied into a memfd (by the /// kernel), so a reload of a path already open is the file as it is now /// (dlopen hands back the handle it has for a path it has) and the file /// can be written over while it runs, unless this process holds those very /// bytes already. `hash` is their BLAKE3: computed here, or `known` (the /// start's, of a file the same since). fn hold(file: c_int, hash: *[32]u8, known: bool, why: *Why) ?*Lib { if (known) for (&libs) |*l| if (l.*) |*lib| if (std.mem.eql(u8, &lib.hash, hash)) { lib.refs += 1; return lib; }; const linux = std.os.linux; var st: linux.Statx = undefined; if (std.c.statx(file, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &st) != 0) return failNull(why, "cannot read it", .{}); if (st.size > 256 << 20) return failNull(why, "it is over 256 MiB", .{}); const size: usize = @intCast(st.size); // The fd stays open while its library is: /proc/self/fd/ of a closed // fd is the next load's path too, and dlopen would hand back this one. const fd = std.c.memfd_create("pardes-addon", 0); if (fd < 0) return failNull(why, "no memfd for it", .{}); var off: std.c.off_t = 0; while (off < size) if (std.c.sendfile(fd, file, &off, size - @as(usize, @intCast(off))) <= 0) { _ = std.c.close(fd); return failNull(why, "cannot copy it", .{}); }; if (!known) { const at = if (size == 0) null else std.c.mmap(null, size, .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0); if (at == std.c.MAP_FAILED) { _ = std.c.close(fd); return failNull(why, "cannot read it", .{}); } std.crypto.hash.Blake3.hash(if (at) |m| @as([*]const u8, @ptrCast(m))[0..size] else "", hash, .{}); if (at) |m| _ = std.c.munmap(@alignCast(m), size); for (&libs) |*l| if (l.*) |*lib| if (std.mem.eql(u8, &lib.hash, hash)) { _ = std.c.close(fd); lib.refs += 1; return lib; }; } const free = for (&libs) |*l| { if (l.* == null) break l; } else { _ = std.c.close(fd); return failNull(why, "this process holds 32 libraries already", .{}); }; var proc: [64]u8 = undefined; const at = std.fmt.bufPrintSentinel(&proc, "/proc/self/fd/{d}", .{fd}, 0) catch unreachable; const handle = std.c.dlopen(at, .{ .NOW = true }) orelse { _ = std.c.close(fd); return failNull(why, "{s}", .{if (std.c.dlerror()) |e| std.mem.span(e) else "cannot load it"}); }; const sym = std.c.dlsym(handle, "pardes_addon") orelse { _ = std.c.dlclose(handle); _ = std.c.close(fd); return failNull(why, "refused: it has no pardes_addon", .{}); }; free.* = .{ .hash = hash.*, .handle = handle, .ops = @ptrCast(@alignCast(sym)), .fd = fd }; return &free.*.?; } fn failNull(why: *Why, comptime fmt: []const u8, args: anytype) ?*Lib { _ = why.print(fmt, args); return null; } /// What the scan at start found, which every core this process makes /// starts with (Options.addons). var found: [Kind.max_kinds]Loaded = undefined; var found_words: [Kind.max_kinds][64]LoadedWord = undefined; var found_text: [Kind.max_kinds][2][4096]u8 = undefined; /// A library listed from its head and not loaded yet: its file, open since /// the scan (`need` loads it from there), else -1; and its head in `heads`. var found_file: [Kind.max_kinds]c_int = @splat(-1); var found_head: [Kind.max_kinds]?u8 = @splat(null); var nfound: usize = 0; var scanned = false; /// What a library brought at its last load, kept for the next start in the /// data directory's `addon-heads` (one after another, in this build's /// layout; the first line says which by pardes's version, not its commit, /// so an installed build and one being worked on share it; 16 at most, any /// prefix's). A library whose file is the same (device, inode, size, /// modification and change times) is listed from its head and loaded at the /// first pane of its kind (`need`); reading and hashing every library at /// every start was most of a start's work. A cache: a start without it, or /// with another version's, loads every library. const Head = struct { file: [5]i64, path: Kind.Buf(256), name: [16]u8, version: u32, abi: u32, hash: [32]u8, caps: Kind.Caps, exts: Kind.Buf(512), nwords: u8, words: [64]Kind.Word, }; const heads_line = std.fmt.comptimePrint("pardes addon heads {s} {d} {x}\n", .{ pardes.version, @sizeOf(Head), Kind.abi }); var heads: [Kind.max_kinds]Head = undefined; var nheads: usize = 0; var heads_changed = false; /// The file open at `fd` as a head keys it: its device, inode, size and /// times; null where it cannot be told. fn fileOf(fd: c_int) ?[5]i64 { const linux = std.os.linux; var st: linux.Statx = undefined; if (std.c.statx(fd, "", linux.AT.EMPTY_PATH, .{ .INO = true, .SIZE = true, .MTIME = true, .CTIME = true }, &st) != 0) return null; return .{ @as(i64, st.dev_major) << 32 | st.dev_minor, @bitCast(st.ino), @bitCast(st.size), st.mtime.sec * std.time.ns_per_s + st.mtime.nsec, st.ctime.sec * std.time.ns_per_s + st.ctime.nsec }; } /// The addons compiled in (`zig build static`, and any build off Linux): /// the image and pdf modules' `pardes_addon` declarations, which only a /// library exports. A static binary cannot dlopen, and the loader below /// is Linux's (a memfd): this is how either has image and PDF panes. /// A build with -Dpdf=false has the image addon alone. const compiled_in: []const *const Kind.Ops = if (!@import("builtin_addons").on) &.{} else if (@import("builtin_addons").pdf) &.{ &@import("image_addon").pardes_addon, &@import("pdf_addon").pardes_addon } else &.{&@import("image_addon").pardes_addon}; /// The addons compiled in, as if loaded (`builtin` their path); else every /// library of the two directories, in name order each, the user's first. A /// library that crashed at its last load is listed, not loaded; one whose /// head is kept is listed from it, loaded at its first use. pub fn scan() []const Loaded { if (scanned) return found[0..nfound]; scanned = true; for (compiled_in) |ops| { found[nfound] = loadedOf(ops, "builtin", @splat(0), &found_words[nfound]); if (ops.init) |init| if (init(&Kind.api) != Kind.c.PA_OK) { found[nfound].why = "refused: its init failed"; }; nfound += 1; } if (compiled_in.len > 0) return found[0..nfound]; var data_buf: [4096]u8 = undefined; const data = dataDir(&data_buf); const crashed = crashedPath(data); var heads_buf: [4096]u8 = undefined; const heads_path = if (data.len > 0) markPath(&heads_buf, data, "addon-heads") else null; if (heads_path) |at| if (std.c.fopen(at, "r")) |f| { var line: [heads_line.len]u8 = undefined; if (std.c.fread(&line, 1, line.len, f) == line.len and std.mem.eql(u8, &line, heads_line)) nheads = std.c.fread(@ptrCast(&heads), @sizeOf(Head), heads.len, f); _ = std.c.fclose(f); }; var dir_buf: [4096]u8 = undefined; if (data.len > 0) scanDir(data, std.fmt.bufPrint(&dir_buf, "{s}/addons", .{data}) catch "", crashed.slice()); var exe: [4096]u8 = undefined; const n = std.c.readlink("/proc/self/exe", &exe, exe.len); if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (std.Io.Dir.path.dirname(bin)) |prefix| scanDir(data, std.fmt.bufPrint(&dir_buf, "{s}/lib/pardes/addons", .{prefix}) catch "", crashed.slice()); // The heads kept, when one changed (other pardes builds' libraries // with them): written beside and renamed over, so a start reading it // meanwhile reads either. if (heads_path) |at| if (heads_changed) { var tmp_buf: [4096]u8 = undefined; const tmp = std.fmt.bufPrintSentinel(&tmp_buf, "{s}.{d}", .{ at, std.c.getpid() }, 0) catch return found[0..nfound]; const f = std.c.fopen(tmp, "w") orelse return found[0..nfound]; var ok = std.c.fwrite(heads_line.ptr, 1, heads_line.len, f) == heads_line.len; ok = ok and std.c.fwrite(@ptrCast(&heads), @sizeOf(Head), nheads, f) == nheads; ok = std.c.fclose(f) == 0 and ok; _ = if (ok) std.c.rename(tmp, at) else std.c.unlink(tmp); }; return found[0..nfound]; } /// The library at `path` listed: from its head, its file the same as when /// the head was kept, the file held open for its first use (`need`); else /// read now, and its head kept for the next start. fn listed(data: []const u8, path: []const u8, n: usize, why: *Why) Loaded { var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return read(data, path, &found_words[n], why); const file = std.c.open(path_z, .{ .CLOEXEC = true }); if (file < 0) return read(data, path, &found_words[n], why); const same = fileOf(file); if (same) |key| for (heads[0..nheads], 0..) |*h, i| if (std.mem.eql(i64, &h.file, &key) and std.mem.eql(u8, h.path.slice(), path)) { found_file[n] = file; found_head[n] = @intCast(i); const words = found_words[n][0..h.nwords]; for (h.words[0..h.nwords], words) |*w, *out| out.* = .{ .name = w.name.slice(), .leader = w.leader.slice(), .arg = w.arg, .opens = w.opens, .doc = w.doc.slice() }; return .{ .name = std.mem.sliceTo(&h.name, 0), .version = h.version, .abi = h.abi, .hash = h.hash, .caps = h.caps, .path = path, .exts = h.exts.slice(), .words = words }; }; defer _ = std.c.close(file); const l = readOpen(data, path, file, &found_words[n], why); const key = same orelse return l; // Kept only whole: a name, leader or path cut to fit would be listed // otherwise than its library's. if (l.why.len > 0 or path.len > 256 or l.exts.len > 512) return l; for (l.words) |w| if (w.name.len > 32 or w.leader.len > 8) return l; // In place of its path's old head, else a new one, else the last that // no library listed now uses. const at: usize = for (heads[0..nheads], 0..) |*old, i| { if (std.mem.eql(u8, old.path.slice(), path)) break i; } else if (nheads < heads.len) nheads else for (0..heads.len) |back| { if (std.mem.indexOfScalar(?u8, found_head[0..n], @intCast(heads.len - 1 - back)) == null) break heads.len - 1 - back; } else return l; const h = &heads[at]; h.* = .{ .file = key, .path = .{}, .name = @splat(0), .version = l.version, .abi = l.abi, .hash = l.hash, .caps = l.caps, .exts = .{}, .nwords = @intCast(l.words.len), .words = undefined }; h.path.set(path); @memcpy(h.name[0..l.name.len], l.name); h.exts.set(l.exts); // A doc is cut to the Word's room as a core's table cuts it. for (l.words, h.words[0..l.words.len]) |w, *out| { out.* = .{ .kind = 0, .arg = w.arg, .opens = w.opens }; out.name.set(w.name); out.leader.set(w.leader); out.doc.set(w.doc); } found_head[n] = @intCast(at); nheads = @max(nheads, at + 1); heads_changed = true; return l; } /// Kind `k`'s code, a session's (a replica's is `plainOps`'s or none): its /// library loaded at the first pane of its kind, from the file the start /// listed it from (`listed`); null, and why, when it will not load. pub fn need(r: *Kind.Registry, k: u8, why: *Why) ?*const Kind.Ops { if (r.ops[k] != null or tape.replaying()) return r.ops[k]; const e = &r.kinds[k]; for (found[0..nfound], 0..) |*l, i| if (l.why.len == 0 and std.mem.eql(u8, &l.hash, &e.hash) and std.mem.eql(u8, l.path, e.path.slice())) { if (l.ops == 0) l.ops = loadListed(i, why) orelse return null; r.ops[k] = @ptrFromInt(l.ops); return r.ops[k]; }; _ = why.print("addon {s} is not loaded", .{e.nameOf()}); return null; } /// The library `found[i]` listed from its head, loaded: from its file as /// the scan opened it, so a library renamed over since is still the one /// listed; one written over in place since is refused unless its bytes /// are the same. fn loadListed(i: usize, why: *Why) ?usize { if (comptime compiled_in.len > 0 or @import("builtin").os.tag != .linux) return null; const l = &found[i]; var data_buf: [4096]u8 = undefined; mark(dataDir(&data_buf), l.path); defer unmark(); const h = &heads[found_head[i].?]; const same = if (fileOf(found_file[i])) |key| std.mem.eql(i64, &key, &h.file) else false; var hash = l.hash; const lib = hold(found_file[i], &hash, same, why) orelse return null; const changed = !std.mem.eql(u8, &hash, &l.hash); const failed = !changed and if (lib.ops.init) |init| init(&Kind.api) != Kind.c.PA_OK else false; if (changed or failed) { if (changed) _ = why.print("{s} changed on disk since this session listed it: Addon reload {s}", .{ std.Io.Dir.path.basename(l.path), l.name }) else _ = why.print("{s}: refused: its init failed", .{l.name}); lib.refs -= 1; closeIdle(lib); return null; } _ = std.c.close(found_file[i]); found_file[i] = -1; return @intFromPtr(lib.ops); } fn scanDir(data: []const u8, dir: []const u8, crashed: []const u8) void { var z: [4096]u8 = undefined; const dz = std.fmt.bufPrintSentinel(&z, "{s}", .{dir}, 0) catch return; const d = std.c.opendir(dz) orelse return; defer _ = std.c.closedir(d); var names: [32][256]u8 = undefined; var lens: [32]usize = undefined; var count: usize = 0; while (std.c.readdir(d)) |e| { const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&e.name)), 0); if (!std.mem.endsWith(u8, name, ".so") or name.len > 255 or count == names.len) continue; @memcpy(names[count][0..name.len], name); lens[count] = name.len; count += 1; } var order: [32]usize = undefined; for (0..count) |i| order[i] = i; const Sort = struct { names: *const [32][256]u8, lens: *const [32]usize, fn lt(s: @This(), a: usize, b: usize) bool { return std.mem.lessThan(u8, s.names[a][0..s.lens[a]], s.names[b][0..s.lens[b]]); } }; std.mem.sort(usize, order[0..count], Sort{ .names = &names, .lens = &lens }, Sort.lt); for (order[0..count]) |i| { if (nfound == found.len) return; const text = &found_text[nfound]; const path = std.fmt.bufPrint(&text[0], "{s}/{s}", .{ dir, names[i][0..lens[i]] }) catch continue; var why: Why = .{}; found[nfound] = if (crashed.len > 0 and std.mem.eql(u8, path, crashed)) .{ .path = path, .why = "skipped: it crashed its last load (Addon load asks for it again)" } else listed(data, path, nfound, &why); const w = found[nfound].why; @memcpy(text[1][0..w.len], w); found[nfound].why = text[1][0..w.len]; nfound += 1; } } /// Where the crash mark goes: the data directory, none in a test (a /// test's loads are no user's). fn dataDir(buf: []u8) []const u8 { if (@import("builtin").is_test) return ""; return dump.defaultDirectory(buf) orelse ""; } // ---- the crash mark ---- var marked: [4096]u8 = undefined; var marked_len: usize = 0; fn markPath(buf: []u8, data: []const u8, comptime name: []const u8) ?[:0]const u8 { return std.fmt.bufPrintSentinel(buf, "{s}/" ++ name, .{data}, 0) catch null; } /// The load of `path` under way, on disk until `unmark`. fn mark(data: []const u8, path: []const u8) void { if (data.len == 0) return; var buf: [4096]u8 = undefined; const at = markPath(&buf, data, "addon-loading") orelse return; const f = std.c.fopen(at, "w") orelse return; _ = std.c.fwrite(path.ptr, 1, path.len, f); _ = std.c.fclose(f); @memcpy(marked[0..at.len], at); marked_len = at.len; // `Addon load` of the one that crashed asks for it again. var cbuf: [4096]u8 = undefined; const crashed = markPath(&cbuf, data, "addon-crashed") orelse return; if (std.mem.eql(u8, readSmall(crashed).slice(), path)) _ = std.c.unlink(crashed); } fn unmark() void { if (marked_len == 0) return; marked[marked_len] = 0; _ = std.c.unlink(@ptrCast(&marked)); marked_len = 0; } /// The library that crashed its session's load: a mark left by a start /// that never finished one becomes `addon-crashed`, which it stays. fn crashedPath(data: []const u8) Kind.Buf(4096) { var out: Kind.Buf(4096) = .{}; if (data.len == 0) return out; var lbuf: [4096]u8 = undefined; var cbuf: [4096]u8 = undefined; const loading = markPath(&lbuf, data, "addon-loading") orelse return out; const crashed = markPath(&cbuf, data, "addon-crashed") orelse return out; if (std.c.access(loading, 0) == 0) _ = std.c.rename(loading, crashed); out.set(readSmall(crashed).slice()); return out; } fn readSmall(path: [*:0]const u8) Kind.Buf(4096) { var out: Kind.Buf(4096) = .{}; const f = std.c.fopen(path, "r") orelse return out; defer _ = std.c.fclose(f); out.len = @intCast(std.c.fread(&out.bytes, 1, out.bytes.len, f)); return out; } // ---- the tail: what a library brings, and a core's tables of it ---- /// What a library brings, as the host read it off its head (or why it /// brought nothing): the `addon` event's, and the scan's at start. pub const Loaded = struct { name: []const u8 = "", version: u32 = 0, abi: u32 = 0, /// The library file's BLAKE3; zero for one never read. hash: [32]u8 = @splat(0), caps: Kind.Caps = .{}, path: []const u8 = "", /// Empty: taken; else why not ("refused: ..."). why: []const u8 = "", exts: []const u8 = "", words: []const LoadedWord = &.{}, /// Its `pa_ops` in this process; a replica's update reads none. ops: usize = 0, }; pub const LoadedWord = struct { name: []const u8, leader: []const u8 = "", arg: u8 = 0, opens: u8 = 0, doc: []const u8 = "" }; /// `ops`'s head as a `Loaded` (its words borrowed from it, in `words`). pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[64]LoadedWord) Loaded { const h = &ops.head; const head_words = if (h.nwords == 0 or h.words == null) &.{} else h.words[0..@min(h.nwords, words.len)]; for (head_words, words[0..head_words.len]) |*w, *out| out.* = .{ .name = if (w.name == null) "" else std.mem.span(w.name), .leader = if (w.leader == null) "" else std.mem.span(w.leader), .arg = w.arg, .opens = w.opens, .doc = if (w.doc == null) "" else std.mem.span(w.doc), }; return .{ .name = std.mem.sliceTo(&h.name, 0), .version = h.version, .abi = h.abi, .hash = hash, .path = path, .exts = if (h.exts == null) "" else std.mem.span(h.exts), .words = words[0..head_words.len], .ops = @intFromPtr(ops), .caps = .{ .tick = ops.tick != null, .key = ops.key != null, .mouse = ops.mouse != null, .ctl = ops.ctl != null, .jobs = ops.job_run != null, .load = ops.load != null, .search = ops.search != null, .address = ops.address != null, .view = ops.view != null, .pictures = h.flags & Kind.c.PA_PICTURES != 0, .plain = h.flags & Kind.c.PA_PLAIN != 0, }, }; } /// This process's code for a kind a session's core lists, which a client /// runs itself: PA_PLAIN, of the same name, version, ABI and functions (a /// compiled-in addon's library hash is 0: never by the hash), and not /// caught breaking its promise here (`distrust`). Null: its panes say so. pub fn plainOps(e: *const Kind.Entry) ?*const Kind.Ops { if (!e.caps.plain or e.refused) return null; // A client scans for its addons only when its session has a plain kind. _ = scan(); for (distrusted[0..ndistrusted]) |*d| if (std.mem.eql(u8, std.mem.sliceTo(d, 0), e.nameOf())) return null; for (found[0..nfound], 0..) |*l, i| if (l.why.len == 0 and std.mem.eql(u8, l.name, e.nameOf()) and l.version == e.version and l.abi == e.abi and @as(u16, @bitCast(l.caps)) == @as(u16, @bitCast(e.caps))) { var why: Why = .{}; if (l.ops == 0) l.ops = loadListed(i, &why) orelse return null; return @ptrFromInt(l.ops); }; return null; } /// Kinds a client found breaking PA_PLAIN: shown by the session's line /// from its next join on. var distrusted: [Kind.max_kinds][16]u8 = undefined; var ndistrusted: usize = 0; pub fn distrust(name: []const u8) void { if (ndistrusted == distrusted.len) return; distrusted[ndistrusted] = @splat(0); @memcpy(distrusted[ndistrusted][0..@min(15, name.len)], name[0..@min(15, name.len)]); ndistrusted += 1; } /// The kind that opens `path`, by its extension (any case). pub fn forPath(r: *const Kind.Registry, path: []const u8) ?u8 { const dot = std.mem.lastIndexOfScalar(u8, path, '.') orelse return null; if (std.mem.indexOfScalarPos(u8, path, dot, '/') != null) return null; for (r.exts[0..r.nexts]) |*e| if (std.ascii.eqlIgnoreCase(e.ext.slice(), path[dot..])) return e.kind; return null; } pub fn word(r: *const Kind.Registry, name: []const u8) ?*const Kind.Word { for (r.words[0..r.nwords]) |*w| if (std.mem.eql(u8, w.name.slice(), name)) return w; return null; } /// The word whose leader path is `keys`, or whether one has a path /// `keys` begins (`prefix`). pub fn leader(r: *const Kind.Registry, keys: []const u8) union(enum) { none, prefix, word: *const Kind.Word } { var begun = false; for (r.words[0..r.nwords]) |*w| { if (w.leader.len == 0) continue; if (std.mem.eql(u8, w.leader.slice(), keys)) return .{ .word = w }; if (std.mem.startsWith(u8, w.leader.slice(), keys)) begun = true; } return if (begun) .prefix else .none; } /// `l` taken in, its words and extensions with it, or listed refused, /// and why: collisions with the core's names and the kinds here /// (`except`'s own looked past, a reload's old one). pub fn take(r: *Kind.Registry, l: Loaded, except: []const u8) ?[]const u8 { if (r.n == Kind.max_kinds) return "refused: no room for another kind"; const e = &r.kinds[r.n]; e.* = .{ .version = l.version, .abi = l.abi, .hash = l.hash, .caps = l.caps }; @memcpy(e.name[0..@min(15, l.name.len)], l.name[0..@min(15, l.name.len)]); e.path.set(l.path); const why = if (l.why.len > 0) l.why else r.collides(l, except, &e.why); if (why) |w| { e.why.set(w); e.refused = true; r.n += 1; return e.why.slice(); } e.why.set("loaded"); // A client's: its own code for a plain kind, or none (the session's). r.ops[r.n] = if (tape.replaying()) plainOps(e) else @ptrFromInt(l.ops); for (l.words) |w| { r.words[r.nwords] = .{ .kind = r.n, .arg = w.arg, .opens = w.opens }; r.words[r.nwords].name.set(w.name); r.words[r.nwords].leader.set(w.leader); r.words[r.nwords].doc.set(w.doc); r.nwords += 1; } var it = std.mem.tokenizeScalar(u8, l.exts, ' '); while (it.next()) |ext| : (r.nexts += 1) { r.exts[r.nexts] = .{ .kind = r.n }; r.exts[r.nexts].ext.set(ext); } r.n += 1; return null; } pub fn collides(r: *const Kind.Registry, l: Loaded, except: []const u8, why: *Kind.Buf(128)) ?[]const u8 { const mine = struct { fn of(rr: *const Kind.Registry, k: u8, ex: []const u8) bool { return ex.len > 0 and std.mem.eql(u8, rr.kinds[k].nameOf(), ex); } }.of; if (l.name.len == 0 or l.name.len > 15) return "refused: its name is empty or longer than 15 bytes"; for (l.name) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '_' and ch != '-') return "refused: its name is not a word"; if (r.byName(l.name)) |k| if (!mine(r, k, except)) return why.print("refused: kind {s} is here already", .{l.name}); if (r.nwords + l.words.len > r.words.len) return "refused: no room for its words"; for (l.words, 0..) |w, i| { if (w.name.len == 0 or w.name.len > 32) return "refused: a word's name is empty or longer than 32 bytes"; if (coreWord(w.name)) return why.print("refused: word {s} is the core's", .{w.name}); if (r.word(w.name)) |o| if (!mine(r, o.kind, except)) return why.print("refused: word {s} is {s}'s", .{ w.name, r.kinds[o.kind].nameOf() }); for (l.words[0..i]) |before| if (std.mem.eql(u8, before.name, w.name)) return why.print("refused: word {s} twice", .{w.name}); if (w.leader.len > 8) return why.print("refused: leader SPC {s} is longer than 8 keys", .{w.leader}); if (w.leader.len > 0) { if (@import("keys.zig").leaderTaken(w.leader)) return why.print("refused: leader SPC {s} is taken", .{w.leader}); for (r.words[0..r.nwords]) |o| if (o.leader.len > 0 and !mine(r, o.kind, except) and (std.mem.startsWith(u8, w.leader, o.leader.slice()) or std.mem.startsWith(u8, o.leader.slice(), w.leader))) return why.print("refused: leader SPC {s} is taken", .{w.leader}); } } var it = std.mem.tokenizeScalar(u8, l.exts, ' '); var n: usize = 0; while (it.next()) |ext| : (n += 1) { if (ext.len < 2 or ext[0] != '.' or ext.len > 16) return why.print("refused: extension {s} is no .ext", .{ext}); if (r.forPath(ext)) |o| if (!mine(r, o, except)) return why.print("refused: extension {s} is {s}'s", .{ ext, r.kinds[o].nameOf() }); } if (r.nexts + n > r.exts.len) return "refused: no room for its extensions"; return null; } /// Kind `k` out, its words and extensions with it. pub fn drop(r: *Kind.Registry, k: u8) void { var n: u8 = 0; for (r.words[0..r.nwords]) |w| if (w.kind != k) { r.words[n] = w; if (w.kind > k) r.words[n].kind -= 1; n += 1; }; r.nwords = n; n = 0; for (r.exts[0..r.nexts]) |e| if (e.kind != k) { r.exts[n] = e; if (e.kind > k) r.exts[n].kind -= 1; n += 1; }; r.nexts = n; std.mem.copyForwards(Kind.Entry, r.kinds[k .. r.n - 1], r.kinds[k + 1 .. r.n]); std.mem.copyForwards(?*const Kind.Ops, r.ops[k .. r.n - 1], r.ops[k + 1 .. r.n]); r.n -= 1; r.ops[r.n] = null; } fn coreWord(name: []const u8) bool { const builtins = @import("builtins.zig"); return std.meta.stringToEnum(builtins.registry.Builtin(), name) != null or builtins.absentWhy(name) != null; } // ---- the core's half ---- /// `Addon load ` (relative to the pane's directory), `Addon unload /// ` (refused while a pane of its kind is open), `Addon reload /// ` (its panes kept through it, as their dumps); bare, the kinds /// this session has. pub fn run(p: *Pardes, id: usize, arg: ?[]const u8) void { const a = std.mem.trim(u8, arg orelse "", " \t"); var said: [256]u8 = undefined; if (a.len == 0) { var w: std.Io.Writer = .fixed(&said); w.writeAll("addons:") catch {}; for (p.kinds.kinds[0..p.kinds.n]) |*e| if (!e.refused) w.print(" {s} {d}", .{ e.nameOf(), e.version }) catch {}; return p.setMessage(id, w.buffered()); } const takes = "Addon takes load , unload or reload "; const sp = std.mem.indexOfAny(u8, a, " \t") orelse return p.reportFailure(id, takes); const op = std.meta.stringToEnum(enum { load, unload, reload }, a[0..sp]) orelse return p.reportFailure(id, takes); const rest = std.mem.trim(u8, a[sp..], " \t"); var target: [pardes.effect_path_cap]u8 = undefined; if (op == .load) { const dir = std.mem.trimEnd(u8, if (p.panes[id]) |pane| Pardes.paneDir(pane) else p.sessionDir(), "/"); const path = if (std.Io.Dir.path.isAbsolute(rest)) rest else std.fmt.bufPrint(&target, "{s}/{s}", .{ dir, rest }) catch return p.reportFailure(id, "Addon: that path is too long"); if (path.len > pardes.effect_path_cap) return p.reportFailure(id, "Addon: that path is too long"); return p.emit(.{ .addon = .{ .op = .load, .pane = @intCast(id), .arg = .from(path) } }); } const k = p.kinds.byName(rest) orelse return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: no addon brought kind {s}", .{ op, rest }) catch takes); const e = &p.kinds.kinds[k]; if (op == .reload and std.mem.eql(u8, e.path.slice(), "builtin")) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon reload: {s} is built into this pardes", .{rest}) catch takes); if (op == .reload) return p.emit(.{ .addon = .{ .op = .reload, .pane = @intCast(id), .arg = .from(e.path.slice()) } }); const n = openPanes(p, rest); if (n > 0) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon unload: {d} {s} pane{s} open", .{ n, rest, if (n == 1) " is" else "s are" }) catch takes); const hash = e.hash; const gone = std.fmt.bufPrint(&said, "Addon unload: {s} is gone", .{rest}) catch "Addon unload"; p.kinds.drop(k); release(p, hash); p.setMessage(id, gone); } fn release(p: *Pardes, hash: [32]u8) void { p.emit(.{ .addon = .{ .op = .release, .pane = 0, .arg = .from(&hash) } }); } pub fn openPanes(p: *const Pardes, name: []const u8) usize { var n: usize = 0; for (p.panes) |slot| if (slot) |pane| if (pane.addon) |s| if (s.live and s.is(name)) { n += 1; }; return n; } /// The `addon` event: what a library brought taken in (or listed /// refused), or a reload's swap; the panes that waited for it open. pub fn landed(p: *Pardes, op: Op, pane: u8, l: Loaded) void { const id = if (pane < p.panes.len and p.panes[pane] != null) pane else p.view().active; var said: [320]u8 = undefined; const base = std.Io.Dir.path.basename(l.path); if (op == .reload) { var why: Why = .{}; if (!swap(p, l, &why)) { if (l.why.len == 0) release(p, l.hash); return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon reload: {s}: {s}", .{ base, why.slice() }) catch "Addon reload: refused"); } const n = openPanes(p, l.name); return p.setMessage(id, std.fmt.bufPrint(&said, "Addon reload: {s} {d}, {d} pane{s}", .{ l.name, l.version, n, if (n == 1) "" else "s" }) catch "Addon reload"); } // A load of a path refused before tries it afresh. var i: u8 = 0; while (i < p.kinds.n) { if (p.kinds.kinds[i].refused and std.mem.eql(u8, p.kinds.kinds[i].path.slice(), l.path)) p.kinds.drop(i) else i += 1; } if (p.kinds.take(l, "")) |why| { if (l.why.len == 0) release(p, l.hash); return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon load: {s}: {s}", .{ base, why }) catch "Addon load: refused"); } const n = reopenWaiting(p, l.name); p.setMessage(id, std.fmt.bufPrint(&said, "Addon load: {s} {d}{s}", .{ l.name, l.version, if (n > 0) ", its panes back" else "" }) catch "Addon load"); } /// The panes of kind `name` that waited for it (placeholders), opened. pub fn reopenWaiting(p: *Pardes, name: []const u8) usize { if (p.kinds.byName(name) == null) return 0; var n: usize = 0; // Each from its file, as a Restore's (a file not here: it waits on). for (p.panes, 0..) |slot, id| if (slot) |pane| if (pane.addon) |s| if (!s.live and s.is(name)) { dump.reviveSlot(p, id, s); n += @intFromBool(s.live); }; return n; } /// `Addon reload`: the kind at `l.path` replaced by what `l` brought, or /// why not, nothing changed. Everything is checked first: its head (the /// host's), its collisions (its old self looked past), its name the same, /// and every open pane of the kind opened anew in a fresh arena from the /// old state's record (its `load`, else its place and its words); only /// then are the old states closed and the panes swapped, at a new /// generation (a job the old one asked for is dropped as it answers). fn swap(p: *Pardes, l: Loaded, why: *Why) bool { const k = for (p.kinds.kinds[0..p.kinds.n], 0..) |*e, i| { if (!e.refused and std.mem.eql(u8, e.path.slice(), l.path)) break @as(u8, @intCast(i)); } else return fail(why, "no addon was loaded from it", .{}); const name = p.kinds.kinds[k].nameOf(); if (l.why.len > 0) return fail(why, "{s}", .{l.why}); var scratch: Kind.Buf(128) = .{}; if (p.kinds.collides(l, name, &scratch)) |r| return fail(why, "{s}", .{r}); if (!std.mem.eql(u8, l.name, name)) return fail(why, "refused: its kind is now {s}, not {s}", .{ l.name, name }); const old_ops = p.kinds.ops[k]; const new_ops: ?*const Kind.Ops = if (tape.replaying()) null else @ptrFromInt(l.ops); const gen = p.kinds.kinds[k].gen +% 1; var fresh: [pardes.MAX_PANES]?*Kind.Slot = @splat(null); defer for (fresh) |f| if (f) |s| { const gpa = s.gpa; s.free(); gpa.destroy(s); }; for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |s| if (s.live and s.is(name)) { const n = s.gpa.create(Kind.Slot) catch return fail(why, "out of memory", .{}); // load receives the record's version, not the replacement library's. n.* = .{ .ops = new_ops, .live = true, .gpa = s.gpa, .arena = .init(s.gpa), .name = s.name, .version = s.version, .gen = gen, .art = s.art, .values = s.values }; fresh[id] = n; n.path = s.gpa.dupe(u8, s.path) catch return fail(why, "out of memory", .{}); // The old state's record, by the old library. if (old_ops) |o| { var place: [32]u8 = undefined; n.where_text.set(Kind.where(s, &place)); if (o.dump != null and l.caps.load) n.record = dump.slotRecord(s) catch return fail(why, "out of memory", .{}); } // From its file as it is, the record its small state. const bytes: ?[]u8 = if (new_ops != null and n.path.len > 0) @import("fs.zig").read(p, n.path) catch null else null; defer if (bytes) |b| p.gpa.free(b); if (!Kind.reopen(p, id, n, bytes)) return fail(why, "refused: a pane of it would not open again: {s}", .{n.refused.slice()}); }; // Every pane opened: the old states go, the new take their slots. for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |s| if (fresh[id]) |n| { if (old_ops) |o| if (o.close) |f| f(s.st); for (&s.jobs) |*j| if (j.*) |job| { s.gpa.free(job.in); j.* = null; }; s.arena.deinit(); s.arena = n.arena; n.arena = .init(n.gpa); if (@import("builtin").mode == .debug) std.mem.swap(@TypeOf(s.used), &s.used, &n.used); s.st = n.st; s.ops = new_ops; s.version = l.version; s.gen = gen; s.next_tick = n.next_tick; n.st = null; }; const old_hash = p.kinds.kinds[k].hash; p.kinds.drop(k); _ = p.kinds.take(l, ""); p.kinds.kinds[p.kinds.n - 1].gen = gen; release(p, old_hash); return true; } fn fail(why: *Why, comptime fmt: []const u8, args: anytype) bool { _ = why.print(fmt, args); return false; } /// /addons: ` /// loaded|refused: why` a line (`-` for no path, no hash). pub fn list(p: *const Pardes, out: *std.ArrayList(u8), gpa: std.mem.Allocator) !void { for (p.kinds.kinds[0..p.kinds.n]) |*e| { const name = if (e.nameOf().len > 0) e.nameOf() else std.Io.Dir.path.basename(e.path.slice()); try out.print(gpa, "{s} {d} {d}.{d} {d} {s} ", .{ name, e.version, e.abi >> 16, e.abi & 0xffff, if (e.refused) 0 else openPanes(p, name), if (e.path.len > 0) e.path.slice() else "-" }); if (std.mem.allEqual(u8, &e.hash, 0)) try out.append(gpa, '-') else try out.print(gpa, "{x}", .{e.hash}); try out.print(gpa, " {s}\n", .{e.why.slice()}); } } test "addon reload gives migration the old record version and saves the new version" { const Fake = struct { var state: u8 = 7; fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { return &state; } fn paint(_: ?*anyopaque, _: [*c]const Kind.c.pa_window, _: [*c]Kind.c.pa_paint) callconv(.c) void {} fn save(_: ?*anyopaque, out: [*c]u8, n: u32) callconv(.c) u32 { if (n > 0) out[0] = state; return 1; } fn load(_: ?*anyopaque, bytes: [*c]const u8, n: u32, version: u32) callconv(.c) c_int { return if (version == 1 and n == 1 and bytes[0] == 7) Kind.c.PA_OK else 1; } }; const p = try @import("ninep/testing.zig").withFile(std.testing.allocator, "x\n"); defer p.deinit(); var old = std.mem.zeroInit(Kind.Ops, .{ .head = std.mem.zeroInit(Kind.c.pa_head, .{ .size = @sizeOf(Kind.c.pa_head), .abi = Kind.abi, .version = 1 }), .open = Fake.open, .paint = Fake.paint, .dump = Fake.save, .load = Fake.load }); @memcpy(old.head.name[0..7], "migrate"); var words: [64]LoadedWord = undefined; try std.testing.expect(p.kinds.take(loadedOf(&old, "test.so", @splat(0), &words), "") == null); const pane = try Kind.open(p, 1, p.kinds.byName("migrate").?, null, null); var new = old; new.head.version = 2; var why: Why = .{}; try std.testing.expect(swap(p, loadedOf(&new, "test.so", @splat(1), &words), &why)); try std.testing.expectEqual(@as(u32, 2), pane.addon.?.version); try std.testing.expectEqual(@as(u32, 2), p.kinds.kinds[p.kinds.byName("migrate").?].version); // A saved v1 placeholder revived by v2 must also save future records as v2. const slot = pane.addon.?; slot.version = 1; slot.live = false; slot.record = try slot.gpa.dupe(u8, &.{7}); dump.reviveSlot(p, 1, slot); try std.testing.expect(slot.live); try std.testing.expectEqual(@as(u32, 2), slot.version); } test "a load that never finished is skipped at the next start, and every start after, until a load asks for it" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; const data = buf[0..try tmp.dir.realPath(std.testing.io, &buf)]; try tmp.dir.createDirPath(std.testing.io, "addons"); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "addons/crashy.so", .data = "not a library" }); var lib_buf: [4096]u8 = undefined; const lib = try std.fmt.bufPrint(&lib_buf, "{s}/addons/crashy.so", .{data}); // The mark a load leaves when its session dies in it. try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "addon-loading", .data = lib }); var dir_buf: [4096]u8 = undefined; const dir = try std.fmt.bufPrint(&dir_buf, "{s}/addons", .{data}); for (0..2) |_| { nfound = 0; scanDir(data, dir, crashedPath(data).slice()); try std.testing.expectEqualStrings(lib, found[0].path); try std.testing.expect(std.mem.startsWith(u8, found[0].why, "skipped: it crashed its last load")); } nfound = 0; // Asked for by name, it is tried again (and refused here for what it is). var words: [64]LoadedWord = undefined; var why: Why = .{}; const l = read(data, lib, &words, &why); try std.testing.expect(l.why.len > 0 and std.mem.indexOf(u8, l.why, "skipped") == null); try std.testing.expectError(error.FileNotFound, tmp.dir.access(std.testing.io, "addon-crashed", .{})); try std.testing.expectError(error.FileNotFound, tmp.dir.access(std.testing.io, "addon-loading", .{})); }