summaryrefslogtreecommitdiff
path: root/src/Addon.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/Addon.zig')
-rw-r--r--src/Addon.zig249
1 files changed, 212 insertions, 37 deletions
diff --git a/src/Addon.zig b/src/Addon.zig
index a2c46b35..16c38758 100644
--- a/src/Addon.zig
+++ b/src/Addon.zig
@@ -4,7 +4,9 @@
//! 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 `<prefix>/lib/pardes/addons` at start; the crash mark. An addon
+//! and `<prefix>/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
@@ -81,10 +83,21 @@ pub fn readLoaded(path: []const u8, words: *[64]LoadedWord, why: *Why) Loaded {
/// 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(path, &hash, why) orelse return .{ .path = path, .why = why.slice() };
+ 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;
@@ -107,47 +120,51 @@ fn read(data: []const u8, path: []const u8, words: *[64]LoadedWord, why: *Why) L
return .{ .name = name, .version = l.version, .abi = l.abi, .hash = hash, .path = path, .why = why.slice() };
}
-/// The library at `path` held: opened from a copy of its bytes in a
-/// memfd, 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), unless this
-/// process holds those very bytes already.
-fn hold(path: []const u8, hash: *[32]u8, why: *Why) ?*Lib {
- if (comptime compiled_in.len > 0 or @import("builtin").os.tag != .linux) return failNull(why, "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 failNull(why, "the path is too long", .{});
- const f = std.c.fopen(path_z, "r") orelse return failNull(why, "cannot read it", .{});
- defer _ = std.c.fclose(f);
- const gpa = std.heap.page_allocator;
- var bytes: std.ArrayList(u8) = .empty;
- defer bytes.deinit(gpa);
- var chunk: [64 << 10]u8 = undefined;
- while (true) {
- const n = std.c.fread(&chunk, 1, chunk.len, f);
- if (n == 0) break;
- bytes.appendSlice(gpa, chunk[0..n]) catch return failNull(why, "out of memory", .{});
- if (bytes.items.len > 256 << 20) return failNull(why, "it is over 256 MiB", .{});
- }
- std.crypto.hash.Blake3.hash(bytes.items, hash, .{});
- for (&libs) |*l| if (l.*) |*lib| if (std.mem.eql(u8, &lib.hash, hash)) {
+/// 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 free = for (&libs) |*l| {
- if (l.* == null) break l;
- } else return failNull(why, "this process holds 32 libraries already", .{});
+ 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/<n> 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: usize = 0;
- while (off < bytes.items.len) {
- const n = std.c.write(fd, bytes.items.ptr + off, bytes.items.len - off);
- if (n <= 0) {
+ 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 copy it", .{});
+ return failNull(why, "cannot read it", .{});
}
- off += @intCast(n);
+ 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 {
@@ -173,9 +190,48 @@ fn failNull(why: *Why, comptime fmt: []const u8, args: anytype) ?*Lib {
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
@@ -190,7 +246,8 @@ else
/// 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.
+/// 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;
@@ -205,15 +262,128 @@ pub fn scan() []const Loaded {
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;
@@ -247,7 +417,7 @@ fn scanDir(data: []const u8, dir: []const u8, crashed: []const u8) void {
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
- read(data, path, &found_words[nfound], &why);
+ 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];
@@ -382,8 +552,13 @@ pub fn plainOps(e: *const Kind.Entry) ?*const Kind.Ops {
// 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]) |l| 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))) return @ptrFromInt(l.ops);
+ 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;
}