diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 21:23:22 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 21:43:03 -0300 |
| commit | f9a3179542012ec1a700e2020ac9f616b819f972 (patch) | |
| tree | 73f4cb241876196331f7b28c9f773301bd341a7f /dev/host_io.zig | |
| parent | a75956bb3443aa8aac778d2ff12c42f5ef99e0e9 (diff) | |
| download | pardes-f9a3179542012ec1a700e2020ac9f616b819f972.tar.gz pardes-f9a3179542012ec1a700e2020ac9f616b819f972.zip | |
dev: the frontends (dev/tui, dev/gui, the macOS app's Swift and resources in dev/macos), host_io, file_watch, fonts, the lsp client and Scip, Art, jump_trail, glide and vaxis_input into dev/ (the reorganisation's tree, step 2b): module `dev` (dev/root.zig) beside the core and the runtime, each naming the others; the window wired into it, sketchbook's devices imported as `sketchbook` (its `dev` would be ours); pardes.zig keeps its re-exports (host_io, file_watch, glide, fonts) so every caller reads as before; core-test and shell-test run the devices' test program too, so the same tests run (the ledger, tui and gui); nothing else changes: frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'dev/host_io.zig')
| -rw-r--r-- | dev/host_io.zig | 4007 |
1 files changed, 4007 insertions, 0 deletions
diff --git a/dev/host_io.zig b/dev/host_io.zig new file mode 100644 index 00000000..d8b8bbb3 --- /dev/null +++ b/dev/host_io.zig @@ -0,0 +1,4007 @@ +const builtin = @import("builtin"); +const std = @import("std"); +const posix = std.posix; +/// libc: ptys, fork and exec, signals; and the leaf file calls (/proc, PATH, the prompt rc files), which run with no io: in a forked child, a signal handler, or for callers holding none. +const libc = std.c; +const pardes = @import("core"); +const selection_pipe = @import("core").selection_pipe; +const ninep_io = @import("runtime").ninep_io; +const filesystem = @import("core").filesystem; +const file_watch = @import("file_watch.zig"); +const replica = @import("core").replica; +const daemon = @import("runtime").daemon; +const panes = @import("core").panes; + +pub const Host = struct { + ctx: ?*anyopaque = null, + vtable: *const VTable = &.{}, + + pub const VTable = struct { + wait_input: ?*const fn (ctx: ?*anyopaque, timeout_ms: u32) void = null, + /// The shell's monotonic clock in ns: the only time the core sees. + /// Without one, core animation moves only by `.tick` events. + now: ?*const fn (ctx: ?*anyopaque) u64 = null, + present: ?*const fn (ctx: ?*anyopaque, surface: *const pardes.Surface) void = null, + post_present: ?*const fn (ctx: ?*anyopaque) void = null, + poll_frame: ?*const fn (ctx: ?*anyopaque) void = null, + /// Whether anyone sees a frame drawn now. A detached session with no + /// client attached draws none (a /screen read draws its own), and + /// the frame owed is drawn when one attaches. Absent: always. + watched: ?*const fn (ctx: ?*anyopaque) bool = null, + /// Detach: the terminal or window let go, the session left running + /// for the daemon to attach again (daemon.zig). + detach: ?*const fn (ctx: ?*anyopaque) void = null, + /// Adopt: the shells a dead session left, asked of the daemon. + adopt: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + /// Upgrade: this process exec'd as the pardes installed since, at + /// the step's end (upgrade.zig); `pane` hears why if it cannot be. + upgrade: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + /// Whether a newer pardes is installed at the path this process + /// started from, to be said once (upgrade.zig): asked at a focus-in. + newer_build: ?*const fn (ctx: ?*anyopaque) bool = null, + spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null, + pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null, + pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null, + pty_signal: ?*const fn (ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void = null, + close_pty: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + tty_taken: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null, + /// The name of the program holding the tty, when it is not the + /// shell (host_io.foregroundName), in `buf`. + fg_name: ?*const fn (ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 = null, + /// Answered at once, not queued as an effect: Kill asks while the + /// job it saw running is still the one in the tty (host_io.killJob). + kill_job: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null, + write_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void = null, + write_dump: ?*const fn (ctx: ?*anyopaque, bytes: []const u8) void = null, + watch_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, on: bool, mode: pardes.WatchMode) void = null, + watch_theme: ?*const fn (ctx: ?*anyopaque, generation: u32, on: bool) void = null, + dump_themes: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null, + read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null, + open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null, + /// A plumbing rule's program (Effect.start): every host's is + /// startDetached. Null once it runs, else why not. + start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null, + lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null, + pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null, + /// Start the streaming search of this generation on a worker + /// (pardes.Stream.start); absent, it runs on the loop. + search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null, + /// Carry the dump of handover `seq` to another window on a worker + /// (Handover.start), which answers through the inbox's `handed`. + hand_over: ?*const fn (ctx: ?*anyopaque, seq: u32, bytes: []const u8) void = null, + /// Run job `token` of the pane in slot `pane` (whose serial is + /// `serial`) on a worker (`KindJob`), answering with the `job` event; + /// absent, it runs on the loop. + job: ?*const fn (ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void = null, + }; +}; + +/// A kind's job (Effect.job), taken off its pane: its input, its kind's +/// `job_run` and generation; run on a worker (or here), its answer the +/// core's `job` event. Its library is held until it lands (Addon.holdJob). +/// A draw (api.draw, `draw`) is one of this process's alone: never an +/// event, its answer kept for the pane's next paint (Kind.landDraw). +pub const KindJob = struct { + gpa: std.mem.Allocator, + pane: u8, + serial: u32, + token: u32, + gen: u32, + ops: *const pardes.Kind.Ops, + in: []u8, + /// What the job allocates (`pa_out`), freed with it; `out` the last. + arena: std.heap.ArenaAllocator, + out: []u8 = &.{}, + id: u32 = 0, + /// A draw's: the core it was asked in. + draw: ?*const pardes.Pardes = null, + + pub fn take(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) ?*KindJob { + const pn = p.panes[pane] orelse return null; + const slot = pn.addon orelse return null; + const ops = slot.ops orelse return null; + if (pn.serial != serial or ops.job_run == null) return null; + const at = for (&slot.jobs) |*j| { + if (j.*) |job| if (job.token == token) break j; + } else return null; + const j = slot.gpa.create(KindJob) catch return null; + j.* = .{ .gpa = slot.gpa, .pane = pane, .serial = serial, .token = token, .gen = slot.gen, .ops = ops, .in = at.*.?.in, .arena = .init(slot.gpa) }; + at.* = null; + pardes.Addon.holdJob(ops, true); + return j; + } + + pub fn run(j: *KindJob) void { + const Out = struct { + fn alloc(out: [*c]pardes.Kind.c.pa_out, n: usize) callconv(.c) ?*anyopaque { + const job: *KindJob = @ptrCast(@alignCast(out.*.ctx)); + job.out = job.arena.allocator().alignedAlloc(u8, .@"16", n) catch &.{}; + return if (job.out.len == n) job.out.ptr else null; + } + }; + var out: pardes.Kind.c.pa_out = .{ .alloc = Out.alloc, .ctx = j }; + const n = j.ops.job_run.?(j.in.ptr, @intCast(j.in.len), &out); + j.out = j.out[0..@min(n, j.out.len)]; + } + + /// Its answer to the core, and it gone. + pub fn land(j: *KindJob, p: *pardes.Pardes) void { + if (j.draw != null) return pardes.Kind.landDraw(p, j); + p.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); + j.drop(); + } + + pub fn drop(j: *KindJob) void { + pardes.Addon.holdJob(j.ops, false); + j.gpa.free(j.in); + j.arena.deinit(); + j.gpa.destroy(j); + } + + /// On a worker of `io`, posting itself to `sink` done: a host's `job`. + pub fn start(io: std.Io, p: *pardes.Pardes, tasks: *selection_pipe.Tasks, pane: u8, serial: u32, token: u32, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) void { + const j = take(p, pane, serial, token) orelse return; + if (!go(io, tasks, j, ctx, sink)) here(j, p); + } + + /// `j` on a worker of `io`, posting itself to `sink` done; false when + /// none could take it. + pub fn go(io: std.Io, tasks: *selection_pipe.Tasks, j: *KindJob, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) bool { + next_id +%= 1; + j.id = next_id | 0x8000_0000; + const work = struct { + fn work(job: *KindJob, c: ?*anyopaque, s: *const fn (?*anyopaque, *KindJob) void) void { + job.run(); + s(c, job); + } + }.work; + if (tasks.full()) return false; + const future = io.concurrent(work, .{ j, ctx, sink }) catch return false; + _ = tasks.add(.{ .id = j.id, .future = future }); + return true; + } + + var next_id: u32 = 0; + + fn here(j: *KindJob, p: *pardes.Pardes) void { + j.run(); + j.land(p); + } + + /// No workers (a test, the fallback): it runs on the loop, at once. + pub fn runHere(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) void { + here(take(p, pane, serial, token) orelse return, p); + } +}; + +/// PARDES_TEST_CLOCK makes a shell's `Host.now` answer a virtual clock +/// instead of `std.Io.Clock.awake`, moved only when a timed wait runs out -- +/// straight to the core's next wake -- so the snapshot harness sees the same +/// frames whatever the machine's load. +pub fn testClock() ?u64 { + return if (libc.getenv("PARDES_TEST_CLOCK")) |v| (if (std.mem.span(v).len != 0) 0 else null) else null; +} + +/// The kitty images and syntax subsystems a frontend's session draws with, +/// on `allocs` (pardes.memory.init), and what kinds keep past a call (their +/// heap, `pa_api.heap`: the pdf addon's documents and pages). `stopWorkers` +/// is its defer. +pub fn startWorkers(allocs: pardes.memory.Allocators) void { + pardes.Term.start(allocs.image); + pardes.Kind.heap = allocs.addon; + pardes.syntax.start(allocs.tree_sitter); +} + +pub fn stopWorkers() void { + pardes.Term.stop(); + pardes.syntax.stop(); +} + +/// A Restore's new core, from the dump at `path` (core.takeRestore), or +/// null once why it is not is said. ponytail: a Restore replaces the core +/// its clients replicate; they are let go, and attach again. The old +/// core's panes and theme are no longer watched; the frontend lets go of +/// its ptys and pipes and swaps the new core in. ponytail: a restored +/// session is one view, the live one's (the tty's terminal, the window's +/// window): the others are let go, as a detach of each. +pub fn restoreCore(gpa: std.mem.Allocator, core: *pardes.Pardes, path: []const u8, peers: *replica.Peers, inotify_fd: c_int, watches: *file_watch.Table) ?*pardes.Pardes { + peers.dropAll(core); + const bytes = pardes.dump.restoreBytes(core, gpa, path) catch |err| { + core.reportError(core.view().active, "Restore", err); + return null; + }; + defer gpa.free(bytes); + const nc = pardes.dump.restore(core, bytes, path) catch |err| { + core.reportError(core.view().active, "Restore", err); + return null; + }; + file_watch.unwatchAll(inotify_fd, watches); + _ = file_watch.applyThemeEffect(core, gpa, inotify_fd, watches, 0, false); + return nc; +} + +/// A shell of a dead session the daemon handed this one (Adopt), and the +/// terminal pane made for it once there is one. +pub const Adoption = struct { pid: libc.pid_t, fd: c_int, pane: ?u8 }; + +/// The shells of dead sessions handed this one (Adopt), each waiting for +/// the spawn of the terminal pane made for it (`take`). +pub const Adoptions = struct { + list: [pardes.MAX_PANES]Adoption = undefined, + len: usize = 0, + /// Taken in since the last Adopt. + taken: usize = 0, + + /// Adopt: the daemon is asked for the shells of sessions that died + /// holding them; each comes back to `adoptShell`. + pub fn ask(a: *Adoptions, core: *pardes.Pardes, pane: u8) void { + if (!daemon.kept()) return core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); + a.taken = 0; + daemon.adopt(); + } + + /// One shell of a dead session (`pid` 0: the last of them was told): + /// a terminal pane made for it, as the Term word makes one, whose spawn + /// takes this pty instead of forking a shell (`take`). + pub fn adoptShell(a: *Adoptions, core: *pardes.Pardes, pid: libc.pid_t, fd: c_int) void { + if (pid == 0) { + var buf: pardes.Kind.Buf(96) = .{}; + return core.setMessage(core.view().active, if (a.taken == 0) "Adopt: no shell of a session that died is waiting" else buf.print("Adopt: {d} shell{s} taken in; what they showed is gone", .{ a.taken, if (a.taken == 1) "" else "s" })); + } + if (a.len < a.list.len) { + a.list[a.len] = .{ .pid = pid, .fd = fd, .pane = null }; + a.len += 1; + if (core.adoptShell()) |id| { + a.list[a.len - 1].pane = id; + a.taken += 1; + return; + } + a.len -= 1; + } + // No room for it: its master goes, and the shell with this session. + _ = libc.close(fd); + var buf: pardes.Kind.Buf(96) = .{}; + core.setMessage(core.view().active, buf.print("Adopt: no room for shell {d}; it ends with this session", .{pid})); + } + + /// The adopted shell pane `pane`'s spawn takes, off the list. + pub fn take(a: *Adoptions, pane: u8) ?Adoption { + for (a.list[0..a.len], 0..) |it, i| if (it.pane == pane) { + std.mem.copyForwards(Adoption, a.list[i .. a.len - 1], a.list[i + 1 .. a.len]); + a.len -= 1; + return it; + }; + return null; + } +}; + +pub const Fallback = struct { + pub const dump_path = "pardes.dump"; + + gpa: std.mem.Allocator, + files: std.StringHashMapUnmanaged([]u8) = .empty, + clipboard: std.ArrayListUnmanaged(u8) = .empty, + link: std.ArrayListUnmanaged(u8) = .empty, + /// The programs plumbing rules started, as Effect.start packs them, + /// one a line. + started: std.ArrayListUnmanaged(u8) = .empty, + spawned: [pardes.MAX_PANES]bool = @splat(false), + watched: [pardes.MAX_PANES]bool = @splat(false), + + pub fn deinit(f: *Fallback) void { + var it = f.files.iterator(); + while (it.next()) |entry| { + f.gpa.free(entry.key_ptr.*); + f.gpa.free(entry.value_ptr.*); + } + f.files.deinit(f.gpa); + f.clipboard.deinit(f.gpa); + f.link.deinit(f.gpa); + f.started.deinit(f.gpa); + } + + pub fn writeFile(f: *Fallback, path: []const u8, bytes: []const u8) bool { + const copy = f.gpa.dupe(u8, bytes) catch return false; + if (f.files.getEntry(path)) |entry| { + f.gpa.free(entry.value_ptr.*); + entry.value_ptr.* = copy; + return true; + } + const key = f.gpa.dupe(u8, path) catch { + f.gpa.free(copy); + return false; + }; + f.files.put(f.gpa, key, copy) catch { + f.gpa.free(key); + f.gpa.free(copy); + return false; + }; + return true; + } + + pub fn get(f: *const Fallback, path: []const u8) ?[]const u8 { + if (f.files.get(path)) |written| return written; + return filesystem.sourceBytes(path); + } + + pub fn setClipboard(f: *Fallback, text: []const u8) void { + f.clipboard.clearRetainingCapacity(); + f.clipboard.appendSlice(f.gpa, text) catch {}; + } + + pub fn setLink(f: *Fallback, url: []const u8) void { + f.link.clearRetainingCapacity(); + f.link.appendSlice(f.gpa, url) catch {}; + } + + pub fn start(f: *Fallback, line: []const u8) ?[]const u8 { + f.started.appendSlice(f.gpa, line) catch return "out of memory"; + f.started.append(f.gpa, '\n') catch return "out of memory"; + return null; + } +}; + +/// What a pixel host's loop takes from its workers, in order: each pane's +/// pty output (a reader waits while `output_capacity` is full, so output is +/// never dropped or reordered), its end of file, the language client's +/// answers and status and the `|` jobs' answers (those kept apart, so a +/// full output queue never holds them up), and file-watch news. Output and +/// end of file of a reader that was canceled or replaced, and an answer to +/// a language query since superseded, are dropped here. +pub const Inbox = struct { + pub const Msg = union(enum) { + output: struct { pane: u8, gen: u32, bytes: []u8 }, + eof: struct { pane: u8, gen: u32, failure: ?anyerror = null }, + lsp: struct { id: u32, rows: ?[]u8 }, + lsp_status: []u8, + pipe: selection_pipe.Response, + /// A streaming search's rows (pardes.Stream), of whatever generation: + /// the core drops a stale one. + search: pardes.Stream.Batch, + /// How a handover went (Handover.zig): `words` is where it went, or + /// why it did not; gpa-owned. + handed: struct { seq: u32, ok: bool, words: []u8 }, + /// A kind's job done on a worker (KindJob), never dropped. + kind_job: *KindJob, + files_changed, + fs_ready, + /// The daemon asks for the window again (`pardes-gui --attach`). + window, + /// A shell a dead session left, its pty's master (Adopt); pid 0 is + /// the last of them told. + adopted: struct { pid: libc.pid_t, fd: c_int }, + + pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void { + switch (m) { + .output => |o| gpa.free(o.bytes), + .lsp => |l| if (l.rows) |rows| lsp_allocator.free(rows), + .lsp_status => |t| lsp_allocator.free(t), + .pipe => |response_value| { + var response = response_value; + response.deinit(gpa); + }, + .search => |b| b.deinit(gpa), + .handed => |h| gpa.free(h.words), + .kind_job => |j| j.drop(), + .adopted => |a| if (a.fd >= 0) { + _ = libc.close(a.fd); + }, + .eof, .files_changed, .fs_ready, .window => {}, + } + } + }; + + pub const capacity = 512; + pub const output_capacity = capacity - pardes.MAX_PANES; + + pub const Batch = struct { + items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined, + len: usize = 0, + + pub fn slice(batch: *Batch) []Msg { + return batch.items[0..batch.len]; + } + }; + + gpa: std.mem.Allocator, + lsp_allocator: std.mem.Allocator, + /// The query in flight; the UI thread's alone (spawnLsp, teardown). + lsp_task: ?Lsp.Task = null, + /// Wakes the host's loop after a push from another thread: an SDL + /// event, a macOS runtime callback. Null: nobody to wake (tests). + wake_fn: ?*const fn (?*anyopaque) void = null, + wake_ctx: ?*anyopaque = null, + /// The process's Io: its terminal readers wait for space on `space`. + io: std.Io, + mutex: std.Io.Mutex = .init, + space: std.Io.Condition = .init, + items: [capacity]Msg = undefined, + head: usize = 0, + len: usize = 0, + closed: bool = false, + files_changed: bool = false, + readers: [pardes.MAX_PANES]?u32 = @splat(null), + waiting: usize = 0, + lsp_id: ?u32 = null, + completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined, + completion_len: usize = 0, + + pub fn lock(q: *Inbox) void { + q.mutex.lockUncancelable(q.io); + } + + pub fn unlock(q: *Inbox) void { + q.mutex.unlock(q.io); + } + + pub fn wake(q: *Inbox) void { + if (q.wake_fn) |f| f(q.wake_ctx); + } + + pub fn acceptReader(q: *Inbox, pane: u8, gen: u32) void { + q.lock(); + defer q.unlock(); + std.debug.assert(q.readers[pane] == null); + q.readers[pane] = gen; + } + + pub fn cancelReader(q: *Inbox, pane: u8, gen: u32) void { + q.lock(); + defer q.unlock(); + if (q.readers[pane] != gen) return; + q.readers[pane] = null; + var i: usize = 0; + while (i < q.len) { + const msg = q.items[(q.head + i) % q.items.len]; + const matches = switch (msg) { + .output => |o| o.pane == pane and o.gen == gen, + .eof => |e| e.pane == pane and e.gen == gen, + else => false, + }; + if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1; + } + q.space.broadcast(q.io); + } + + pub fn pushOutput(q: *Inbox, pane: u8, gen: u32, bytes: []u8) bool { + q.lock(); + while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) { + q.waiting += 1; + q.space.waitUncancelable(q.io, &q.mutex); + q.waiting -= 1; + } + if (q.closed or q.readers[pane] != gen) { + q.unlock(); + q.gpa.free(bytes); + return false; + } + q.items[(q.head + q.len) % q.items.len] = .{ .output = .{ .pane = pane, .gen = gen, .bytes = bytes } }; + q.len += 1; + q.unlock(); + q.wake(); + return true; + } + + fn removeAt(q: *Inbox, offset: usize) Msg { + const removed = q.items[(q.head + offset) % q.items.len]; + var i = offset; + while (i + 1 < q.len) : (i += 1) + q.items[(q.head + i) % q.items.len] = q.items[(q.head + i + 1) % q.items.len]; + q.len -= 1; + return removed; + } + + pub fn discardLsp(q: *Inbox) void { + for (q.completions[0..q.completion_len], 0..) |msg, i| if (msg == .lsp) { + msg.deinit(q.gpa, q.lsp_allocator); + q.completion_len -= 1; + std.mem.copyForwards(Msg, q.completions[i..q.completion_len], q.completions[i + 1 .. q.completion_len + 1]); + return; + }; + } + + pub fn push(q: *Inbox, m: Msg) void { + if (m == .output) { + _ = q.pushOutput(m.output.pane, m.output.gen, m.output.bytes); + return; + } + q.lock(); + if (q.closed) { + q.unlock(); + m.deinit(q.gpa, q.lsp_allocator); + return; + } + switch (m) { + .files_changed => q.files_changed = true, + .lsp, .pipe, .kind_job => { + if (m == .lsp) { + if (q.lsp_id != m.lsp.id) { + q.unlock(); + m.deinit(q.gpa, q.lsp_allocator); + return; + } + q.discardLsp(); + } + std.debug.assert(q.completion_len < q.completions.len); + q.completions[q.completion_len] = m; + q.completion_len += 1; + }, + else => { + if (m == .eof) { + if (q.readers[m.eof.pane] != m.eof.gen) { + q.unlock(); + return; + } + std.debug.assert(q.len < q.items.len); + } else if (q.len >= output_capacity) { + q.unlock(); + m.deinit(q.gpa, q.lsp_allocator); + return; + } + q.items[(q.head + q.len) % q.items.len] = m; + q.len += 1; + }, + } + q.unlock(); + q.wake(); + } + + pub fn take(q: *Inbox) Batch { + var batch: Batch = .{}; + q.takeInto(&batch); + return batch; + } + + /// `take` into a batch the caller keeps: an idle wakeup copies nothing + /// (the batch is some 20 KB, and was built and returned by value each + /// time). + pub fn takeInto(q: *Inbox, batch: *Batch) void { + batch.len = 0; + q.lock(); + defer q.unlock(); + if (q.len == 0 and !q.files_changed and q.completion_len == 0) return; + while (q.len > 0) { + batch.items[batch.len] = q.items[q.head]; + batch.len += 1; + q.head = (q.head + 1) % q.items.len; + q.len -= 1; + } + q.head = 0; + if (q.files_changed) { + batch.items[batch.len] = .files_changed; + batch.len += 1; + q.files_changed = false; + } + @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]); + batch.len += q.completion_len; + q.completion_len = 0; + q.space.broadcast(q.io); + } + + pub fn discardCompletions(q: *Inbox) void { + q.lock(); + defer q.unlock(); + q.lsp_id = null; + for (q.completions[0..q.completion_len]) |msg| msg.deinit(q.gpa, q.lsp_allocator); + q.completion_len = 0; + } + + pub fn close(q: *Inbox) void { + q.lock(); + q.closed = true; + q.files_changed = false; + q.readers = @splat(null); + q.space.broadcast(q.io); + q.unlock(); + q.discardCompletions(); + q.lock(); + defer q.unlock(); + while (q.len > 0) { + const m = q.items[q.head]; + m.deinit(q.gpa, q.lsp_allocator); + q.head = (q.head + 1) % q.items.len; + q.len -= 1; + } + q.head = 0; + } + + pub fn deinit(q: *Inbox) void { + q.close(); + std.debug.assert(q.waiting == 0); + } + + /// A pane's reader: its pty's output pushed as it comes, then its end + /// of file; canceled (closePty), it pushes nothing more. + pub fn startReader(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) !std.Io.Future(void) { + q.acceptReader(pane, gen); + errdefer q.cancelReader(pane, gen); + return q.io.concurrent(readPty, .{ q, pty, pane, gen }); + } + + fn readPty(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) void { + var buf: [0x10000]u8 = undefined; + var failure: ?anyerror = null; + while (true) { + const n = pty.readStreaming(q.io, &.{&buf}) catch |err| switch (err) { + // A pty whose child has gone answers EIO: its end of file. + error.EndOfStream, error.InputOutput => break, + error.Canceled => return, + else => { + failure = err; + break; + }, + }; + if (n == 0) continue; + const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| { + failure = err; + break; + }; + if (!q.pushOutput(pane, gen, bytes)) return; + } + q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } }); + } + + /// Starts `e`, its answer let in and every older one's turned away. + pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void { + q.lock(); + q.lsp_id = e.id; + q.discardLsp(); + q.unlock(); + // The old query's waits are cancelation points: its join is short, and + // what it still delivers carries an id the queue now rejects. + Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows); + } + + fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx orelse return)); + q.push(.{ .lsp = .{ .id = id, .rows = rows } }); + } + + /// The language client's status line (lsp.setStatusSink). + pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx orelse return)); + const copy = q.lsp_allocator.dupe(u8, text) catch return; + q.push(.{ .lsp_status = copy }); + } + + /// A `|` job's answer (selection_pipe.start's sink). + pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.push(.{ .kind_job = j }); + } + + pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.push(.{ .pipe = response }); + } + + /// A handover's end (Handover.Job.post). + pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + const copy = q.gpa.dupe(u8, words) catch return; + q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } }); + } + + /// A streaming search's batch (pardes.Stream.start's sink). Never + /// dropped for want of room, as output is not: the worker waits for + /// room, a wait its cancel ends (false: it stops). + pub fn pushSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.lock(); + while (!q.closed and q.len >= output_capacity) { + q.waiting += 1; + q.space.wait(q.io, &q.mutex) catch { + q.waiting -= 1; + q.unlock(); + batch.deinit(q.gpa); + return false; + }; + q.waiting -= 1; + } + if (q.closed) { + q.unlock(); + batch.deinit(q.gpa); + return false; + } + q.items[(q.head + q.len) % q.items.len] = .{ .search = batch }; + q.len += 1; + q.unlock(); + q.wake(); + return true; + } + + /// A watched child exited (setExitWake): wake the loop, which takes it. + pub fn wakeForExit(ctx: ?*anyopaque) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.wake(); + } +}; + +pub const Lsp = struct { + pub const Request = struct { + id: u32, + kind: pardes.lsp.Kind, + pane: u8, + offset: u32, + arg: []const u8, + }; + + pub const Task = struct { + id: u32, + future: std.Io.Future(void), + }; + + /// One language query, owned by the worker that runs it. + pub const Job = struct { + callstack_depth: u8 = pardes.lsp.callstack_default_depth, + dirty: bool = false, + id: u32, + kind: pardes.lsp.Kind, + offset: u32, + path: []u8, + source: [:0]u8, + arg: []u8, + root: []u8, + /// The other open files, for a query that can reach them. + others: []pardes.lsp.Doc = &.{}, + + pub fn free(job: *Job, gpa: std.mem.Allocator) void { + gpa.free(job.path); + gpa.free(job.source); + gpa.free(job.arg); + gpa.free(job.root); + for (job.others) |doc| { + gpa.free(doc.path); + gpa.free(doc.source); + } + gpa.free(job.others); + gpa.destroy(job); + } + }; + + // Copy before starting a worker; the editor may replace any source slice afterward. + pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request) !*Job { + if (req.pane >= core.panes.len) return error.NoPane; + const pane = core.panes[req.pane] orelse return error.NoPane; + const file = pane.file; + const job = try gpa.create(Job); + errdefer gpa.destroy(job); + const declared_path = if (file) |f| f.path else ""; + const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path); + errdefer gpa.free(path); + const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0); + errdefer gpa.free(source); + const arg = try gpa.dupe(u8, req.arg); + errdefer gpa.free(arg); + const declared_root = if (file) |f| pardes.panes.Dir.ofName(f.path) else pane.cwdSlice(); + const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root); + errdefer gpa.free(root); + job.* = .{ + .callstack_depth = core.settings.callstack_depth, + .dirty = pardes.tagline.dirty(pane), + .id = req.id, + .kind = req.kind, + .offset = req.offset, + .path = path, + .source = source, + .arg = arg, + .root = root, + }; + // ponytail: a copy of every open file per such query; a server + // already told of one is sent nothing more (syncDoc). + // Lspwhy too: the query it explains may be one of those, and its + // trace shows each file synced first. + if (pardes.lsp.reachesOtherFiles(req.kind) or req.kind == .explain) { + var others: std.ArrayList(pardes.lsp.Doc) = .empty; + errdefer { + for (others.items) |doc| { + gpa.free(doc.path); + gpa.free(doc.source); + } + others.deinit(gpa); + } + var copied: usize = 0; + for (core.panes, 0..) |slot, i| { + const other = slot orelse continue; + if (i == req.pane) continue; + const f = other.file orelse continue; + if (f.output != null) continue; + if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue; + copied += f.content.len; + const local = filesystem.localPath(f.path) orelse continue; + const other_path = try gpa.dupe(u8, local); + const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { + gpa.free(other_path); + return err; + }; + try others.append(gpa, .{ .path = other_path, .source = other_source }); + } + job.others = try others.toOwnedSlice(gpa); + } + return job; + } + + // Null is failure; the receiver frees non-null rows with the job's allocator. + pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void; + + /// Start `req` on a worker that hands its rows to `deliver`, the query + /// in `task` canceled first. One that cannot start is answered (no rows) + /// and reported here. + pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, task: *?Task, req: Request, ctx: ?*anyopaque, deliver: Deliver) void { + if (task.*) |*old| { + old.future.cancel(io); + task.* = null; + } + const job = snapshot(gpa, core, req) catch |err| { + core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + return core.reportError(req.pane, "lsp", err); + }; + const future = io.concurrent(work, .{ io, gpa, job, ctx, deliver }) catch |err| { + job.free(gpa); + core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + return core.reportError(req.pane, "lsp", err); + }; + task.* = .{ .id = req.id, .future = future }; + } + + pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { + defer job.free(gpa); + // The query's memory is the fixed region memory.zig reserved at + // startup: a hard bound, reused by each query in turn. + const region = pardes.memory.takeLspQuery() orelse { + deliver(ctx, job.id, null); + return; + }; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer pardes.memory.giveLspQuery(arena.end_index); + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + pardes.lsp.query(io, arena.allocator(), .{ + .kind = job.kind, + .path = job.path, + .source = job.source, + .offset = job.offset, + .arg = job.arg, + .root = job.root, + .others = job.others, + .callstack_depth = job.callstack_depth, + .dirty = job.dirty, + .budget = &arena, + }, &out.writer) catch { + deliver(ctx, job.id, null); + return; + }; + const rows = out.toOwnedSlice() catch { + deliver(ctx, job.id, null); + return; + }; + deliver(ctx, job.id, rows); + } + + test "a snapshot owns every byte the backend will read" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal pane's snapshot + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + + core.settings.callstack_depth = 16; + var needle: [6]u8 = "needle".*; + const job = try snapshot(gpa, core, .{ + .id = 7, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = &needle, + }); + defer job.free(gpa); + + core.settings.callstack_depth = 2; + try std.testing.expectEqual(@as(u8, 16), job.callstack_depth); + try std.testing.expectEqual(@as(u32, 7), job.id); + try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind); + try std.testing.expectEqualStrings("needle", job.arg); + try std.testing.expect(job.arg.ptr != &needle); + try std.testing.expectEqualStrings("", job.path); + try std.testing.expectEqual(@as(usize, 0), job.source.len); + try std.testing.expectEqual(@as(u8, 0), job.source[0]); + const pane = core.panes[core.view().active].?; + try std.testing.expectEqualStrings(pane.cwdSlice(), job.root); + if (job.root.len > 0) try std.testing.expect(job.root.ptr != pane.cwdSlice().ptr); + } + + test "LSP snapshot frees every partially copied field on allocation failure" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + _ = try core.setTestFile("const copied = true;\n"); + const Snapshot = struct { + fn check(gpa: std.mem.Allocator, p: *const pardes.Pardes) !void { + const job = try snapshot(gpa, p, .{ + .id = 7, + .kind = .hover, + .pane = @intCast(p.view().active), + .offset = 6, + .arg = "query", + }); + defer job.free(gpa); + try std.testing.expectEqualStrings("const copied = true;\n", job.source); + } + }; + try std.testing.checkAllAllocationFailures(std.testing.allocator, Snapshot.check, .{core}); + } + + test "LSP snapshots translate explicit OS paths once and retain virtual names" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("const value = true;\n"); + for ([_]struct { path: []const u8, native: []const u8 }{ + .{ .path = "/n/os/project/file.zig", .native = "/project/file.zig" }, + .{ .path = "/n/os/n/os/project/file.zig", .native = "/n/os/project/file.zig" }, + .{ .path = "/virtual/src/file.zig", .native = "/virtual/src/file.zig" }, + }) |case| { + const replacement = try gpa.dupe(u8, case.path); + gpa.free(pane.file.?.path); + pane.file.?.path = replacement; + const job = try snapshot(gpa, core, .{ .id = 1, .kind = .hover, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); + defer job.free(gpa); + try std.testing.expectEqualStrings(case.native, job.path); + try std.testing.expectEqualStrings(std.Io.Dir.path.dirname(case.native).?, job.root); + try std.testing.expectEqualStrings(case.path, pane.file.?.path); + } + } + + test "a pane that is gone yields no job rather than a null deref" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + + // The effect is drained after the core has moved on, so the pane it names + // may already have been deleted. Every shell open-coded this check. + const empty = for (core.panes, 0..) |slot, id| { + if (slot == null) break @as(u8, @intCast(id)); + } else return error.NoEmptyPane; + try std.testing.expectError(error.NoPane, snapshot(gpa, core, .{ + .id = 1, + .kind = .definition, + .pane = empty, + .offset = 0, + .arg = "", + })); + } + + test "work consumes the job and hands its rows to the sink" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + + const Sink = struct { + var seen_id: u32 = 0; + var seen_rows: ?[]u8 = null; + fn take(_: ?*anyopaque, id: u32, rows: ?[]u8) void { + seen_id = id; + seen_rows = rows; + } + }; + Sink.seen_id = 0; + Sink.seen_rows = null; + + const job = try snapshot(gpa, core, .{ + .id = 42, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = "", + }); + work(std.testing.io, gpa, job, null, Sink.take); + + // `status` is the one kind that answers with no file and no cursor, which + // is what makes it assertable here without a language server on the box. + try std.testing.expectEqual(@as(u32, 42), Sink.seen_id); + const rows = Sink.seen_rows orelse return error.SinkNeverCalled; + defer gpa.free(rows); + } + + test "LSP edit query failure leaves text and undo untouched before a successful retry" { + if (!pardes.lsp.supports.contains(.format)) return; + const Sink = struct { + core: *pardes.Pardes, + gpa: std.mem.Allocator, + calls: usize = 0, + failed: bool = false, + + fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { + const self: *@This() = @ptrCast(@alignCast(ctx.?)); + defer if (rows) |text| self.gpa.free(text); + self.calls += 1; + self.failed = rows == null; + self.core.update(.{ .lsp_resp = .{ .id = id, .rows = rows } }); + } + }; + const gpa = std.testing.allocator; + for ([_]pardes.lsp.Kind{ .format, .rename }) |kind| { + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("const value=1;\n"); + const path = try gpa.dupe(u8, "/file.zig"); + gpa.free(pane.file.?.path); + pane.file.?.path = path; + pane.body.cur_col = 6; + const revision = pane.file.?.revision; + const undo_len = pane.file.?.history.journal.done; + var failing = std.testing.FailingAllocator.init(gpa, .{}); + var sink: Sink = .{ .core = core, .gpa = failing.allocator() }; + for ([_]bool{ true, false }) |fail| { + failing.fail_index = std.math.maxInt(usize); + core.lspRequest(core.view().active, kind, "renamed"); + const job = try snapshot(failing.allocator(), core, .{ + .id = core.lsp_ask.wait.?.id, + .kind = kind, + .pane = @intCast(core.view().active), + .offset = 6, + .arg = "renamed", + }); + if (fail) failing.fail_index = failing.alloc_index; + work(std.testing.io, failing.allocator(), job, &sink, Sink.take); + try std.testing.expectEqual(fail, sink.failed); + try std.testing.expect(core.lsp_ask.wait == null); + if (fail) { + try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content); + try std.testing.expectEqual(revision, pane.file.?.revision); + try std.testing.expectEqual(undo_len, pane.file.?.history.journal.done); + } else { + try std.testing.expectEqualStrings(if (kind == .format) "const value = 1;\n" else "const renamed=1;\n", pane.file.?.content); + try std.testing.expectEqual(undo_len + 1, pane.file.?.history.journal.done); + } + } + try std.testing.expectEqual(@as(usize, 2), sink.calls); + } + } + + test "LSP work delivers failure when transferring result ownership cannot allocate" { + if (!pardes.lsp.supports.contains(.status)) return; + const TransferAllocator = struct { + failed: bool = false, + fail_copy: bool = false, + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.fail_copy) { + self.failed = true; + return null; + } + return std.testing.allocator.rawAlloc(len, alignment, ra); + } + fn resize(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { + return std.testing.allocator.rawResize(bytes, alignment, len, ra); + } + fn remap(ctx: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (len < bytes.len) { + self.fail_copy = true; + return null; + } + return std.testing.allocator.rawRemap(bytes, alignment, len, ra); + } + fn free(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, ra: usize) void { + std.testing.allocator.rawFree(bytes, alignment, ra); + } + }; + const Sink = struct { + calls: usize = 0, + id: u32 = 0, + rows: ?[]u8 = null, + fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { + const self: *@This() = @ptrCast(@alignCast(ctx.?)); + self.calls += 1; + self.id = id; + self.rows = rows; + } + }; + var allocator: TransferAllocator = .{}; + const gpa: std.mem.Allocator = .{ .ptr = &allocator, .vtable = &.{ + .alloc = TransferAllocator.alloc, + .resize = TransferAllocator.resize, + .remap = TransferAllocator.remap, + .free = TransferAllocator.free, + } }; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); + var sink: Sink = .{}; + work(std.testing.io, gpa, job, &sink, Sink.take); + if (sink.rows) |rows| gpa.free(rows); + try std.testing.expect(allocator.failed); + try std.testing.expectEqual(@as(usize, 1), sink.calls); + try std.testing.expectEqual(@as(u32, 37), sink.id); + try std.testing.expect(sink.rows == null); + } +}; + +pub const Shell = struct { + const X_OK: c_int = 1; + + extern "c" fn mkstemp(template: [*:0]u8) c_int; + extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + + const path_capacity = 4096; + const max_path_files = 64; + + // Repair only the system-only PATH inherited from a macOS GUI launch. + fn adoptSystemPath() void { + if (comptime builtin.os.tag != .macos) return; + var buf: [path_capacity]u8 = undefined; + var len: usize = 0; + collectSystemPath("/etc/paths", "/etc/paths.d", &buf, &len); + if (len == 0) return; + const system = buf[0..len]; + + const current: []const u8 = if (libc.getenv("PATH")) |p| std.mem.span(p) else ""; + if (!allEntriesWithin(current, system)) return; + if (std.mem.eql(u8, current, system)) return; + + var out: [path_capacity:0]u8 = undefined; + if (len >= out.len) return; + @memcpy(out[0..len], system); + out[len] = 0; + _ = setenv("PATH", out[0..len :0].ptr, 1); + } + + // Run in the parent before forking; children borrow the completed prompt files. + pub fn prepare() PromptFiles { + adoptSystemPath(); + if (comptime builtin.os.tag.isDarwin()) + _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1); + sweepDeadRcs(); + const rcs = PromptFiles.init(); + // A private file goes at a fatal signal too, not only at Exit. + for ([_]?[:0]const u8{ if (rcs.bash_owned) rcs.bashPath() else null, if (rcs.fish_owned) rcs.fishPath() else null }, 0..) |owned, i| { + const path = owned orelse continue; + @memcpy(fatal_rcs[i][0..path.len], path); + fatal_rcs[i][path.len] = 0; + fatal_rc_len[i] = path.len; + } + ninep_io.fatal_cleanup = unlinkOwnedRcs; + return rcs; + } + + /// This process's private prompt files, where a fatal signal's handler + /// can reach them (unlinkOwnedRcs). + var fatal_rcs: [2][rc_path_capacity:0]u8 = undefined; + var fatal_rc_len: [2]usize = .{ 0, 0 }; + + /// Removes this process's private prompt files. Async-signal-safe (two + /// unlinks): SIGTERM and SIGHUP call it before the signal's death. + pub fn unlinkOwnedRcs() void { + for (&fatal_rc_len, 0..) |*len, i| { + const n = len.*; + if (n == 0) continue; + len.* = 0; + _ = libc.unlink(fatal_rcs[i][0..n :0].ptr); + } + } + + /// Removes /tmp's `pardes-osc133-<shell>-<pid>-XXXXXX` files whose pid + /// is gone (kill(pid, 0) answers ESRCH): what a killed or crashed + /// editor left. A live pid's, one of another user's, or a name of + /// another shape is left alone. + fn sweepDeadRcs() void { + const dir = std.c.opendir("/tmp") orelse return; + defer _ = std.c.closedir(dir); + var dead: [64][64]u8 = undefined; + var dead_len: [64]usize = undefined; + var n: usize = 0; + while (std.c.readdir(dir)) |ent| { + const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); + const pid = rcPid(name) orelse continue; + // This pid's are this process's, but in an upgraded one: those + // were its old image's (upgrade.zig), and its own come after. + if (pid == std.c.getpid() and @import("runtime").upgrade.resumed == null) continue; + if (pid != std.c.getpid() and std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; + if (name.len >= 64 or n == dead.len) continue; + @memcpy(dead[n][0..name.len], name); + dead_len[n] = name.len; + n += 1; + } + for (dead[0..n], dead_len[0..n]) |*entry, len| { + var path_buf: [80:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "/tmp/{s}", .{entry[0..len]}, 0) catch continue; + const facts = ninep_io.statNoFollow(path) orelse continue; + if (facts.mode & 0o170000 != 0o100000 or facts.uid != libc.getuid()) continue; + _ = libc.unlink(path.ptr); + } + } + + /// The pid in `pardes-osc133-<shell>-<pid>-XXXXXX`, or null. + fn rcPid(name: []const u8) ?std.c.pid_t { + const head = "pardes-osc133-"; + if (!std.mem.startsWith(u8, name, head)) return null; + var fields = std.mem.splitScalar(u8, name[head.len..], '-'); + _ = fields.next() orelse return null; // the shell + const digits = fields.next() orelse return null; + const rest = fields.next() orelse return null; + if (fields.next() != null or rest.len != 6 or digits.len == 0 or digits.len > 10) return null; + for (digits) |c| if (!std.ascii.isDigit(c)) return null; + const pid = std.fmt.parseInt(std.c.pid_t, digits, 10) catch return null; + return if (pid > 0) pid else null; + } + + fn collectSystemPath(paths_file: [:0]const u8, paths_dir: []const u8, buf: []u8, len: *usize) void { + var file_buf: [path_capacity]u8 = undefined; + if (readSmall(paths_file, &file_buf)) |body| appendLines(buf, len, body); + + const io = std.Io.Threaded.global_single_threaded.io(); + var dir = std.Io.Dir.cwd().openDir(io, paths_dir, .{ .iterate = true }) catch return; + defer dir.close(io); + + var names: [max_path_files][256]u8 = undefined; + var name_lens: [max_path_files]usize = undefined; + var count: usize = 0; + var it = dir.iterate(); + while (count < names.len) { + const entry = (it.next(io) catch break) orelse break; + if (entry.kind == .directory) continue; + if (entry.name.len == 0 or entry.name.len > names[count].len) continue; + @memcpy(names[count][0..entry.name.len], entry.name); + name_lens[count] = entry.name.len; + count += 1; + } + var order: [max_path_files]usize = undefined; + for (0..count) |i| order[i] = i; + std.mem.sort(usize, order[0..count], Names{ .names = &names, .lens = &name_lens }, Names.lessThan); + + var path_buf: [512]u8 = undefined; + for (order[0..count]) |i| { + const name = names[i][0..name_lens[i]]; + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ paths_dir, name }, 0) catch continue; + if (readSmall(path, &file_buf)) |body| appendLines(buf, len, body); + } + } + + const Names = struct { + names: *const [max_path_files][256]u8, + lens: *const [max_path_files]usize, + + fn lessThan(self: Names, a: usize, b: usize) bool { + return std.mem.order(u8, self.names[a][0..self.lens[a]], self.names[b][0..self.lens[b]]) == .lt; + } + }; + + fn appendLines(buf: []u8, len: *usize, body: []const u8) void { + var lines = std.mem.splitScalar(u8, body, '\n'); + while (lines.next()) |raw| appendEntry(buf, len, std.mem.trim(u8, raw, " \t\r")); + } + + fn appendEntry(buf: []u8, len: *usize, entry: []const u8) void { + if (entry.len == 0) return; + if (hasEntry(buf[0..len.*], entry)) return; + const separator: usize = if (len.* == 0) 0 else 1; + if (len.* + separator + entry.len > buf.len) return; + if (separator == 1) { + buf[len.*] = ':'; + len.* += 1; + } + @memcpy(buf[len.*..][0..entry.len], entry); + len.* += entry.len; + } + + fn hasEntry(list: []const u8, entry: []const u8) bool { + var it = std.mem.tokenizeScalar(u8, list, ':'); + while (it.next()) |have| if (std.mem.eql(u8, have, entry)) return true; + return false; + } + + fn allEntriesWithin(candidate: []const u8, list: []const u8) bool { + var it = std.mem.tokenizeScalar(u8, candidate, ':'); + while (it.next()) |entry| if (!hasEntry(list, entry)) return false; + return true; + } + + fn readSmall(path: [:0]const u8, buf: []u8) ?[]const u8 { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return null; + defer _ = libc.close(fd); + var off: usize = 0; + while (off < buf.len) { + const n = libc.read(fd, buf[off..].ptr, buf.len - off); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + return null; + } + if (n == 0) break; + off += @intCast(n); + } + return buf[0..off]; + } + + test "the launchd PATH is replaced and a configured one is left alone" { + var buf: [256]u8 = undefined; + var len: usize = 0; + appendEntry(&buf, &len, "/usr/bin"); + appendEntry(&buf, &len, "/bin"); + appendEntry(&buf, &len, "/usr/bin"); // already there: dedup keeps the first + appendEntry(&buf, &len, ""); + try std.testing.expectEqualStrings("/usr/bin:/bin", buf[0..len]); + + try std.testing.expect(allEntriesWithin("/usr/bin:/bin", "/usr/bin:/bin:/sbin")); + try std.testing.expect(allEntriesWithin("", "/usr/bin")); + try std.testing.expect(!allEntriesWithin("/Users/x/.cargo/bin:/usr/bin", "/usr/bin:/bin")); + try std.testing.expect(!allEntriesWithin("/opt/homebrew/bin", "/usr/bin:/bin")); + } + + test "system path files are sorted and duplicate directories keep their first position" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths", .data = " /usr/bin \n/bin\n\n/usr/bin\n" }); + try tmp.dir.createDirPath(std.testing.io, "paths.d"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/20-last", .data = "/opt/local/bin\n/usr/bin\n" }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/10-first", .data = "/opt/homebrew/bin\n/bin\n" }); + var root_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const root = root_buf[0..try tmp.dir.realPath(std.testing.io, &root_buf)]; + var file_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const paths_file = try std.fmt.bufPrintSentinel(&file_buf, "{s}/paths", .{root}, 0); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const paths_dir = try std.fmt.bufPrint(&dir_buf, "{s}/paths.d", .{root}); + var buf: [path_capacity]u8 = undefined; + var len: usize = 0; + collectSystemPath(paths_file, paths_dir, &buf, &len); + try std.testing.expectEqualStrings("/usr/bin:/bin:/opt/homebrew/bin:/opt/local/bin", buf[0..len]); + } + + const Family = enum { bash, fish, none }; + + fn family(bin: []const u8) Family { + const slash = std.mem.lastIndexOfScalar(u8, bin, '/'); + const base = if (slash) |s| bin[s + 1 ..] else bin; + if (std.mem.startsWith(u8, base, "bash")) return .bash; + if (std.mem.startsWith(u8, base, "fish")) return .fish; + return .none; + } + + /// `family`, for a shell whose name does not say it (a renamed copy, a + /// link named otherwise): what it really is, by the name its links end + /// at, else by the program itself -- bash's carries BASH_VERSINFO, fish's + /// fish_prompt. ponytail: a string scan of at most 16 MiB, once a spawn + /// and only for a name that says nothing; a --version probe would fork. + fn familyOf(path: [*:0]const u8) Family { + const named = family(std.mem.span(path)); + if (named != .none) return named; + // A name a POSIX shell answers to is that shell, whatever the file: + // bash run as `sh` is sh, and reads no --rcfile. + const bin = std.mem.span(path); + const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; + for ([_][]const u8{ "sh", "dash", "zsh", "ksh", "mksh", "yash", "nu", "elvish", "xonsh", "tcsh", "csh" }) |known| + if (std.mem.eql(u8, base, known)) return .none; + var real: [std.Io.Dir.max_path_bytes]u8 = undefined; + if (libc.realpath(path, &real)) |r| { + const by_link = family(std.mem.span(@as([*:0]const u8, @ptrCast(r)))); + if (by_link != .none) return by_link; + } + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return .none; + defer _ = libc.close(fd); + var chunk: [64 * 1024]u8 = undefined; + var carry: usize = 0; + var total: usize = 0; + while (total < 16 << 20) { + const n = libc.read(fd, chunk[carry..].ptr, chunk.len - carry); + if (n <= 0) break; + const have = carry + @as(usize, @intCast(n)); + total += @intCast(n); + // A script is no binary: its interpreter is what runs. + if (total == have and std.mem.startsWith(u8, chunk[0..have], "#!")) return .none; + if (std.mem.indexOf(u8, chunk[0..have], "BASH_VERSINFO") != null) return .bash; + if (std.mem.indexOf(u8, chunk[0..have], "fish_prompt") != null) return .fish; + // Keep the tail, so a marker cut by the chunk is still seen. + carry = @min(have, 16); + std.mem.copyForwards(u8, chunk[0..carry], chunk[have - carry .. have]); + } + return .none; + } + + test "a bash under another name is still told as bash" { + const bash: [:0]const u8 = "/usr/bin/bash"; + if (libc.access(bash, X_OK) != 0) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, bash, std.testing.allocator, .limited(16 << 20)); + defer std.testing.allocator.free(bytes); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mysh", .data = bytes, .flags = .{ .permissions = .executable_file } }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path: [4200:0]u8 = undefined; + const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0); + try std.testing.expectEqual(Family.bash, familyOf(p.ptr)); + try std.testing.expectEqual(Family.none, familyOf("/bin/sh")); + } + + const bash_rc = + \\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc" + \\PS1='\[\e]133;A;cl=line;aid=pardes\a\]'"$PS1"'\[\e]133;B;aid=pardes\a\]' + \\PS2='\[\e]133;A;k=c;aid=pardes\a\]'"$PS2"'\[\e]133;B;aid=pardes\a\]' + \\PROMPT_COMMAND='printf "\e]133;D;%s;aid=pardes\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}" + \\if ((BASH_VERSINFO[0] * 100 + BASH_VERSINFO[1] >= 404)); then + \\ PS0='\e]133;C;aid=pardes\a'"$PS0" + \\else + \\ trap 'printf "\e]133;C;aid=pardes\a"' DEBUG + \\fi + \\ + ; + + // fish -C runs after config.fish; bash --rcfile must source .bashrc itself. + const fish_rc = + \\functions -c fish_prompt __pardes_user_prompt + \\function fish_prompt + \\ printf '\e]133;A;cl=line;aid=pardes\a' + \\ __pardes_user_prompt + \\ printf '\e]133;B;aid=pardes\a' + \\end + \\function __pardes_preexec --on-event fish_preexec + \\ printf '\e]133;C;aid=pardes\a' + \\end + \\function __pardes_postexec --on-event fish_postexec + \\ printf '\e]133;D;%s;aid=pardes\a' $status + \\end + \\ + ; + + const rc_path_capacity = 256; + + /// The prompt files a shell sources at start. Under $XDG_RUNTIME_DIR + /// (private to the user) there is one file per content, named by its + /// hash and shared by every pardes, so none is left behind by a pardes + /// that was killed: 72K of them piled up in /tmp when each host wrote + /// its own. Without that directory each host writes private mkstemp + /// files in /tmp and removes them at teardown, as before. + pub const PromptFiles = struct { + bash_path: [rc_path_capacity:0]u8 = @splat(0), + bash_len: u16 = 0, + bash_owned: bool = false, + fish_path: [rc_path_capacity:0]u8 = @splat(0), + fish_len: u16 = 0, + fish_owned: bool = false, + fish_command: [rc_path_capacity + "source ''".len:0]u8 = @splat(0), + fish_command_len: u16 = 0, + + pub fn init() PromptFiles { + var rcs: PromptFiles = .{}; + const bash = place(&rcs.bash_path, "bash", bash_rc); + rcs.bash_len = bash.len; + rcs.bash_owned = bash.owned; + const fish = place(&rcs.fish_path, "fish", fish_rc); + rcs.fish_len = fish.len; + rcs.fish_owned = fish.owned; + if (rcs.fishPath()) |path| { + // Quoted for fish; a path a quote would break is not used. + const command = if (std.mem.indexOfAny(u8, path, "'\\") != null) + error.NoSpaceLeft + else + std.fmt.bufPrintSentinel(&rcs.fish_command, "source '{s}'", .{path}, 0); + const ok = command catch { + if (rcs.fish_owned) _ = libc.unlink(path.ptr); + rcs.fish_len = 0; + return rcs; + }; + rcs.fish_command_len = @intCast(ok.len); + } + return rcs; + } + + pub fn deinit(rcs: *PromptFiles) void { + // Removed here, not again by a signal's handler. + for (&fatal_rc_len, 0..) |*len, i| for ([_]?[:0]const u8{ rcs.bashPath(), rcs.fishPath() }) |mine| { + if (mine) |path| if (len.* == path.len and std.mem.eql(u8, fatal_rcs[i][0..len.*], path)) { + len.* = 0; + }; + }; + if (rcs.bashPath()) |path| if (rcs.bash_owned) { + _ = libc.unlink(path.ptr); + }; + if (rcs.fishPath()) |path| if (rcs.fish_owned) { + _ = libc.unlink(path.ptr); + }; + rcs.bash_len = 0; + rcs.fish_len = 0; + rcs.fish_command_len = 0; + } + + fn bashPath(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.bash_len == 0) return null; + return rcs.bash_path[0..rcs.bash_len :0]; + } + + fn fishPath(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.fish_len == 0) return null; + return rcs.fish_path[0..rcs.fish_len :0]; + } + + fn fishCommand(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.fish_command_len == 0) return null; + return rcs.fish_command[0..rcs.fish_command_len :0]; + } + }; + + /// The shared file for `contents` under $XDG_RUNTIME_DIR, written + /// beside it and renamed into place when missing or different, so a + /// shell never reads half of one; failing that, a private /tmp file. + fn place(path_buf: *[rc_path_capacity:0]u8, name: []const u8, contents: []const u8) struct { len: u16, owned: bool } { + shared: { + const dir = std.mem.span(std.c.getenv("XDG_RUNTIME_DIR") orelse break :shared); + if (dir.len == 0 or dir[0] != '/') break :shared; + const final = std.fmt.bufPrintSentinel(path_buf, "{s}/pardes-osc133-{s}-{x:0>16}", .{ dir, name, std.hash.Wyhash.hash(0, contents) }, 0) catch break :shared; + var have: [2048]u8 = undefined; + if (readSmall(final, &have)) |got| if (std.mem.eql(u8, got, contents)) return .{ .len = @intCast(final.len), .owned = false }; + var tmp_buf: [rc_path_capacity:0]u8 = @splat(0); + var template_buf: [rc_path_capacity]u8 = undefined; + const tmp_template = std.fmt.bufPrint(&template_buf, "{s}.XXXXXX", .{final}) catch break :shared; + const n = stage(&tmp_buf, tmp_template, contents); + if (n == 0) break :shared; + if (libc.rename(tmp_buf[0..n :0].ptr, final.ptr) != 0) { + _ = libc.unlink(tmp_buf[0..n :0].ptr); + break :shared; + } + return .{ .len = @intCast(final.len), .owned = false }; + } + var tmp_template: [64]u8 = undefined; + // Its pid in the name: one a killed editor left is swept by the + // next (sweepDeadRcs). + const template = std.fmt.bufPrint(&tmp_template, "/tmp/pardes-osc133-{s}-{d}-XXXXXX", .{ name, @as(u32, @intCast(std.c.getpid())) }) catch return .{ .len = 0, .owned = false }; + return .{ .len = stage(path_buf, template, contents), .owned = true }; + } + + // Publish a path only after its private 0600 file is fully written and closed. + fn stage(path_buf: *[rc_path_capacity:0]u8, template: []const u8, contents: []const u8) u16 { + const path = std.fmt.bufPrintSentinel(path_buf, "{s}", .{template}, 0) catch return 0; + const fd = mkstemp(path.ptr); + if (fd < 0) return 0; + if (!writeFd(fd, contents)) { + _ = libc.close(fd); + _ = libc.unlink(path.ptr); + return 0; + } + if (libc.close(fd) != 0) { + _ = libc.unlink(path.ptr); + return 0; + } + return @intCast(path.len); + } + + test "shell family is the basename's prefix, and anything else runs unadorned" { + try std.testing.expectEqual(Family.fish, family("fish")); + try std.testing.expectEqual(Family.fish, family("/usr/bin/fish")); + try std.testing.expectEqual(Family.fish, family("/opt/homebrew/bin/fish")); + try std.testing.expectEqual(Family.bash, family("bash")); + try std.testing.expectEqual(Family.bash, family("/bin/bash")); + try std.testing.expectEqual(Family.bash, family("/usr/bin/bash-5.2")); + try std.testing.expectEqual(Family.fish, family("/usr/local/bin/fish-3.7")); + try std.testing.expectEqual(Family.none, family("/opt/fish/bin/nu")); + try std.testing.expectEqual(Family.none, family("/usr/bin/zsh")); + try std.testing.expectEqual(Family.none, family("/bin/sh")); + try std.testing.expectEqual(Family.none, family("nu")); + try std.testing.expectEqual(Family.none, family("")); + } + + const bin_dirs = [_][]const u8{ + "/usr/bin/", + "/bin/", + "/usr/local/bin/", + "/opt/homebrew/bin/", + "/opt/local/bin/", + "/usr/sbin/", + }; + + const fallbacks = [_][]const u8{ + if (builtin.os.tag == .linux) "/usr/bin/bash" else "/bin/bash", + "/bin/sh", + }; + + pub const Spawn = struct { + path: [*:0]const u8, + argv: [6:null]?[*:0]const u8, + }; + + // Resolve in the parent. The path buffer and prompt files must survive through exec. + pub fn resolve(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8, prompt_rcs: *const PromptFiles) Spawn { + const path = find(bin, buf) orelse fallback(buf); + const marks: [2]?[*:0]const u8 = switch (familyOf(path)) { + .bash => if (prompt_rcs.bashPath()) |rc| .{ "--rcfile", rc.ptr } else .{ null, null }, + .fish => if (prompt_rcs.fishCommand()) |command| .{ "-C", command.ptr } else .{ null, null }, + .none => .{ null, null }, + }; + return .{ .path = path, .argv = .{ path, marks[0], marks[1], null, null, null } }; + } + + /// A command pane's shell runs its one line with job control on, so a + /// job the line puts in the background has a process group of its own. + /// The shell leads the terminal's session, and when it exits the kernel + /// hangs up the terminal's foreground group: with job control off that + /// is the shell's own, the job's too, and the job died with the command + /// (nohup'd or not; only setsid got out, and not always in time). A + /// shell pardes does not know runs the line as it is. + pub fn commandArgv(path: [*:0]const u8, line: [*:0]const u8) [6:null]?[*:0]const u8 { + const bin = std.mem.span(path); + const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; + const posix_shells = [_][]const u8{ "bash", "sh", "dash", "zsh", "ksh", "mksh", "yash" }; + for (posix_shells) |name| if (std.mem.eql(u8, base, name)) + return .{ path, "-m", "-c", line, null, null }; + if (family(bin) == .fish) return .{ path, "-C", "status job-control full", "-c", line, null }; + return .{ path, "-c", line, null, null, null }; + } + + /// A shell by its path or its name in the usual directories, or null. + /// A path may be under a mount this editor serves: the turn goes out + /// with the lookups (pardes.Turn.yield). + pub fn find(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[*:0]const u8 { + if (bin.len == 0 or bin.len + 1 > buf.len) return null; + pardes.turn.yield(); + defer pardes.turn.back(); + if (std.mem.indexOfScalar(u8, bin, '/') != null) { + @memcpy(buf[0..bin.len], bin); + buf[bin.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + return if (libc.access(p, X_OK) == 0 and !isDirectory(p)) p else null; + } + for (bin_dirs) |dir| { + if (dir.len + bin.len + 1 > buf.len) continue; + @memcpy(buf[0..dir.len], dir); + @memcpy(buf[dir.len..][0..bin.len], bin); + buf[dir.len + bin.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + if (libc.access(p, X_OK) == 0) return p; + } + return null; + } + + /// A directory passes access(X_OK) (it can be searched): no shell. + pub fn isDirectory(path: [*:0]const u8) bool { + const d = libc.opendir(path) orelse return false; + _ = libc.closedir(d); + return true; + } + + /// Why `bin` is no shell, for the words that name one (Term, Shell); + /// null when it is one. + pub fn refusal(bin: []const u8, said: []u8) ?[]const u8 { + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + if (find(bin, &buf)) |found| { + // A script whose `#!` names a program that is not there: its + // exec fails ENOENT as a missing shell's does, so told apart. + var interp: [256]u8 = undefined; + const missing = missingInterpreter(found, &interp) orelse return null; + return std.fmt.bufPrint(said, "interpreter {s} not found", .{missing}) catch "interpreter not found"; + } + if (std.mem.indexOfScalar(u8, bin, '/') != null and bin.len < buf.len) { + @memcpy(buf[0..bin.len], bin); + buf[bin.len] = 0; + if (isDirectory(@ptrCast(&buf))) return std.fmt.bufPrint(said, "not a shell: {s} is a directory", .{bin}) catch "not a shell: a directory"; + // There, but no program: said so, not "not found". + if (libc.access(@ptrCast(&buf), 0) == 0) return std.fmt.bufPrint(said, "not a shell: {s} is not executable", .{bin}) catch "not a shell: not executable"; + } + // "not found": the words a mount reads as ENOENT. + return std.fmt.bufPrint(said, "shell \"{s}\" not found (a name on the usual paths, or a path to one)", .{bin}) catch "no such shell"; + } + + /// The program a script's `#!` line names, when it is not there to + /// run; null for a script whose interpreter is there, or no script. + pub fn missingInterpreter(path: [*:0]const u8, out: []u8) ?[]const u8 { + pardes.turn.yield(); + defer pardes.turn.back(); + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return null; + defer _ = libc.close(fd); + var head: [256]u8 = undefined; + const n = libc.read(fd, &head, head.len); + if (n < 2) return null; + const got = head[0..@intCast(n)]; + if (!std.mem.startsWith(u8, got, "#!")) return null; + const line = got[2 .. std.mem.indexOfScalar(u8, got, '\n') orelse got.len]; + var words = std.mem.tokenizeAny(u8, line, " \t\r"); + const interp = words.next() orelse return null; + if (interp.len + 1 > out.len) return null; + @memcpy(out[0..interp.len], interp); + out[interp.len] = 0; + if (libc.access(@ptrCast(out.ptr), X_OK) == 0) return null; + return out[0..interp.len]; + } + + test "a script whose #! names a program not there is told apart from a missing shell" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "bad", .data = "#!/no/such/interp -x\n", .flags = .{ .permissions = .executable_file } }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "good", .data = "#!/bin/sh\n", .flags = .{ .permissions = .executable_file } }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path: [4200]u8 = undefined; + var said: [320]u8 = undefined; + try std.testing.expectEqualStrings("interpreter /no/such/interp not found", refusal(try std.fmt.bufPrint(&path, "{s}/bad", .{dir}), &said).?); + try std.testing.expect(refusal(try std.fmt.bufPrint(&path, "{s}/good", .{dir}), &said) == null); + try std.testing.expect(std.mem.startsWith(u8, refusal(try std.fmt.bufPrint(&path, "{s}/none", .{dir}), &said).?, "shell \"")); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "plain", .data = "echo\n" }); + const plain = try std.fmt.bufPrint(&path, "{s}/plain", .{dir}); + try std.testing.expect(std.mem.endsWith(u8, refusal(plain, &said).?, "plain is not executable")); + } + + fn fallback(buf: *[std.Io.Dir.max_path_bytes]u8) [*:0]const u8 { + for (fallbacks) |f| { + @memcpy(buf[0..f.len], f); + buf[f.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + if (libc.access(p, X_OK) == 0) return p; + } + return @ptrCast(buf); + } + + test "a command pane's line runs with job control on in the shells that have it" { + const want = struct { + fn check(path: [*:0]const u8, words: []const []const u8) !void { + const argv = commandArgv(path, "sleep 9 &"); + for (words, 0..) |w, i| try std.testing.expectEqualStrings(w, std.mem.span(argv[i].?)); + try std.testing.expect(argv[words.len] == null); + } + }; + try want.check("/usr/bin/bash", &.{ "/usr/bin/bash", "-m", "-c", "sleep 9 &" }); + try want.check("/bin/sh", &.{ "/bin/sh", "-m", "-c", "sleep 9 &" }); + try want.check("/usr/bin/fish", &.{ "/usr/bin/fish", "-C", "status job-control full", "-c", "sleep 9 &" }); + try want.check("/usr/bin/nu", &.{ "/usr/bin/nu", "-c", "sleep 9 &" }); + } + + test "a path is taken at its word, a name is looked up, and both pick their own marks" { + if (builtin.os.tag == .windows) return; + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var prompt_rcs = PromptFiles.init(); + defer prompt_rcs.deinit(); + + const sh = resolve("/bin/sh", &buf, &prompt_rcs); + try std.testing.expectEqualStrings("/bin/sh", std.mem.span(sh.path)); + try std.testing.expect(sh.argv[1] == null); + + const bash = resolve("bash", &buf, &prompt_rcs); + try std.testing.expect(family(std.mem.span(bash.path)) == .bash); + try std.testing.expectEqualStrings("--rcfile", std.mem.span(bash.argv[1].?)); + try std.testing.expectEqualStrings(prompt_rcs.bashPath().?, std.mem.span(bash.argv[2].?)); + + const missing = resolve("zznosuchshell", &buf, &prompt_rcs); + try std.testing.expect(!std.mem.eql(u8, "zznosuchshell", std.mem.span(missing.path))); + try std.testing.expect(libc.access(missing.path, X_OK) == 0); + + const gone = resolve("/zz/no/such/shell", &buf, &prompt_rcs); + try std.testing.expect(libc.access(gone.path, X_OK) == 0); + } + + test "a private prompt file names its pid, and a dead pid's is swept while a live one's stays" { + if (builtin.os.tag == .windows) return; + const dead = "/tmp/pardes-osc133-bash-2147483647-AbCdEf"; + var live_buf: [80:0]u8 = undefined; + const live = try std.fmt.bufPrintSentinel(&live_buf, "/tmp/pardes-osc133-bash-{d}-AbCdEf", .{@as(u32, @intCast(std.c.getppid()))}, 0); + defer for ([_][:0]const u8{ dead, live }) |path| { + _ = libc.unlink(path.ptr); + }; + for ([_][:0]const u8{ dead, live }) |path| { + const fd = libc.open(path, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600)); + if (fd < 0) return error.SkipZigTest; + _ = libc.close(fd); + } + sweepDeadRcs(); + try std.testing.expect(libc.access(dead, 0) < 0); + try std.testing.expect(libc.access(live, 0) == 0); + // The pid is read only from that shape: an older name has none. + try std.testing.expectEqual(@as(?std.c.pid_t, 42), rcPid("pardes-osc133-fish-42-Xy12Zq")); + try std.testing.expectEqual(@as(?std.c.pid_t, null), rcPid("pardes-osc133-bash-01z3XK")); + } + + test "prompt files are one per content under the runtime dir, or private and cleaned up without it" { + if (builtin.os.tag == .windows) return; + var saved_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); + const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null; + defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR"); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); + const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf); + _ = setenv("XDG_RUNTIME_DIR", dir_buf[0..dir_len :0].ptr, 1); + + // Shared: the same file for every owner, left in place, rewritten + // whole when what is there is not its content. + var a = PromptFiles.init(); + var b = PromptFiles.init(); + const a_bash = a.bashPath() orelse return error.TempCreateFailed; + try std.testing.expectEqualStrings(a_bash, b.bashPath().?); + try std.testing.expect(std.mem.startsWith(u8, a_bash, dir_buf[0..dir_len])); + const fish_command = a.fishCommand() orelse return error.MissingFishCommand; + var want: [rc_path_capacity + 16]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "source '{s}'", .{a.fishPath().?}), fish_command); + var buf: [2048]u8 = undefined; + try std.testing.expectEqualStrings(bash_rc, readSmall(a_bash, &buf) orelse return error.ReadFailed); + try std.testing.expectEqualStrings(fish_rc, readSmall(a.fishPath().?, &buf) orelse return error.ReadFailed); + const stat = try @import("core").filesystem.statPath(std.testing.io, a_bash, .{}); + try std.testing.expectEqual(0, stat.permissions.toMode() & 0o077); + var kept: [rc_path_capacity:0]u8 = @splat(0); + @memcpy(kept[0..a_bash.len], a_bash); + a.deinit(); + b.deinit(); + try std.testing.expect(libc.access(&kept, 0) == 0); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = std.Io.Dir.path.basename(kept[0..a_bash.len]), .data = "half" }); + var c = PromptFiles.init(); + defer c.deinit(); + try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed); + + // No runtime dir: private files, one per owner, gone at teardown. + _ = testUnsetenv("XDG_RUNTIME_DIR"); + var d = PromptFiles.init(); + var e = PromptFiles.init(); + defer e.deinit(); + const d_bash = d.bashPath() orelse return error.TempCreateFailed; + try std.testing.expect(!std.mem.eql(u8, d_bash, e.bashPath().?)); + try std.testing.expect(std.mem.startsWith(u8, d_bash, "/tmp/pardes-osc133-bash-")); + try std.testing.expectEqual(@as(?std.c.pid_t, std.c.getpid()), rcPid(std.Io.Dir.path.basename(d_bash))); + @memcpy(kept[0..d_bash.len], d_bash); + kept[d_bash.len] = 0; + d.deinit(); + try std.testing.expect(libc.access(&kept, 0) < 0); + } +}; + +/// In a child between fork and exec: every signal back to its default and +/// none blocked, whatever this process ignores or blocks (the tty's SIGWINCH, +/// a SIGHUP nohup ignored). A handler resets at exec by itself; an ignored +/// signal and the mask do not. Async-signal-safe: sigaction and sigprocmask. +pub fn resetChildSignals() void { + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + var sig: u8 = 1; + while (sig < 65) : (sig += 1) { + if (sig == @backingInt(posix.SIG.KILL) or sig == @backingInt(posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); + } + const none = posix.sigemptyset(); + posix.sigprocmask(posix.SIG.SETMASK, &none, null); +} + +extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int; +extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn chdir(path: [*:0]const u8) c_int; +extern "c" fn _exit(status: c_int) noreturn; + +pub const Child = struct { + file: std.Io.File, + pid: posix.pid_t, +}; + +/// The environment a pty child is handed: everything this process carries, +/// with the terminal's own identity written over whatever the launcher left +/// behind. The child is talking to the bundled VT, never to the terminal +/// pardes itself was started from, and a macOS `.app` launch supplies no +/// `TERM` at all — which is exactly why `clear` fails there, why nothing +/// paints a colour, and why every cursor-addressing program falls back to a +/// dumb line-at-a-time mode. +pub const ChildEnv = struct { + /// Entries pardes owns. The name of each is read back out of its own + /// spelling, so there is one place to edit and no second list to drift. + const own = [_][*:0]const u8{ + "TERM=" ++ pardes.config.child_term, + "COLORTERM=" ++ pardes.config.child_colorterm, + "TERM_PROGRAM=" ++ pardes.config.child_term_program, + }; + + /// What this editor tells its children of itself (exportEnv, `$winid`), + /// kept here rather than set into this process's environment: std's Io read + /// that block at startup, and setenv/unsetenv rewrite it in place under it + /// (a spawn then scans a null inside it). `build` puts each exported one in + /// place of an inherited variable of its name; a cleared one hides it; one + /// never exported is inherited as it is. + pub const exported_names = [_][]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "winid" }; + var exported_state: [exported_names.len]enum { inherited, cleared, set } = @splat(.inherited); + var exported_line: [exported_names.len][pardes.memory.limits.host_path_cap + 64:0]u8 = undefined; + + /// Set (or, null, clear) what children are told for `var_name`. + pub fn exportVar(var_name: []const u8, value: ?[]const u8) void { + const i = exportedIndex(var_name).?; + const v = value orelse { + exported_state[i] = .cleared; + return; + }; + _ = std.fmt.bufPrintSentinel(&exported_line[i], "{s}={s}", .{ var_name, v }, 0) catch { + exported_state[i] = .cleared; + return; + }; + exported_state[i] = .set; + } + + /// What children are told for `var_name`, as `exportVar` left it; null + /// when cleared or never exported. + pub fn exported(var_name: []const u8) ?[]const u8 { + const i = exportedIndex(var_name) orelse return null; + if (exported_state[i] != .set) return null; + return std.mem.span(@as([*:0]const u8, &exported_line[i]))[var_name.len + 1 ..]; + } + + fn exportedIndex(var_name: []const u8) ?usize { + for (exported_names, 0..) |n, i| if (std.mem.eql(u8, n, var_name)) return i; + return null; + } + + /// Wide enough for any real environment; `build` answers null rather than + /// truncate, because a child missing half its variables is a worse bug + /// than one missing TERM, and the caller then execs with `environ` intact. + pub const Slots = [1024]?[*:0]const u8; + + fn name(entry: [*:0]const u8) []const u8 { + const line = std.mem.span(entry); + return line[0 .. std.mem.indexOfScalar(u8, line, '=') orelse line.len]; + } + + /// Which pager a child is given where the user's environment names none: + /// a command pane's one-shot shell `cat` (its output is a pane already), + /// a terminal's shell `pardes -` (a +Pager pane). + pub const Paging = enum { command, terminal }; + + pub fn build(slots: *Slots, paging: Paging) ?[*:null]const ?[*:0]const u8 { + var n: usize = 0; + var i: usize = 0; + while (libc.environ[i]) |entry| : (i += 1) { + const inherited = name(entry); + const shadowed = for (own) |mine| { + if (std.mem.eql(u8, inherited, name(mine))) break true; + } else false; + if (shadowed) continue; + if (exportedIndex(inherited)) |e| if (exported_state[e] != .inherited) continue; + if (n + own.len + exported_names.len + 1 > slots.len) return null; + slots[n] = entry; + n += 1; + } + // No pager to wait in (less holds a run at its first screen for + // ever): a command pane's output is read whole, through cat; a + // terminal's goes to a +Pager pane. Only where the inherited + // environment chose none. + const defaults: []const [*:0]const u8 = switch (paging) { + .command => &cat_pagers, + .terminal => pardesPagers(), + }; + for (defaults) |default| { + const set = for (libc.environ[0..i]) |entry| { + if (std.mem.eql(u8, name(entry.?), name(default))) break true; + } else false; + if (set) continue; + if (n + own.len + exported_names.len + 4 > slots.len) return null; + slots[n] = default; + n += 1; + } + for (&exported_line, exported_state) |*line, state| if (state == .set) { + slots[n] = line; + n += 1; + }; + for (own) |mine| { + slots[n] = mine; + n += 1; + } + slots[n] = null; + return @ptrCast(slots); + } + + const cat_pagers = [_][*:0]const u8{ "PAGER=cat", "GIT_PAGER=cat" }; + + /// `PAGER='<this pardes> -'`, its own path so no PATH lookup can find + /// another; plain `pardes -` where the path cannot be read or quoted. + fn pardesPagers() []const [*:0]const u8 { + const S = struct { + var pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; + var git_pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; + var systemd_pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; + var entries: [4][*:0]const u8 = undefined; + var ready = false; + }; + if (!S.ready) { + var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var quoted_buf: [std.Io.Dir.max_path_bytes + 2]u8 = undefined; + const n = if (comptime builtin.os.tag == .linux) libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len) else -1; + const exe: []const u8 = if (n > 0 and @as(usize, @intCast(n)) < exe_buf.len) exe_buf[0..@intCast(n)] else "pardes"; + const command = pagerCommand(exe, "ed_buf); + S.entries[0] = if (std.fmt.bufPrintSentinel(&S.pager, "PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "PAGER=pardes -"; + S.entries[1] = if (std.fmt.bufPrintSentinel(&S.git_pager, "GIT_PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "GIT_PAGER=pardes -"; + // systemd's tools (journalctl, systemctl) read their own, and + // in their secure mode run only less: this pager has no shell + // to escape to, so secure mode buys nothing. + S.entries[2] = if (std.fmt.bufPrintSentinel(&S.systemd_pager, "SYSTEMD_PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "SYSTEMD_PAGER=pardes -"; + S.entries[3] = "SYSTEMD_PAGERSECURE=0"; + S.ready = true; + } + return &S.entries; + } + + /// The pager's path as a command line takes it: as it is when it needs + /// no quoting (systemd splits on blanks and execs, never through sh), + /// in single quotes when it holds a blank or a shell character, plain + /// `pardes` when even that cannot hold it. + fn pagerCommand(exe: []const u8, buf: []u8) []const u8 { + const plain = for (exe) |c| { + if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "/._+-,@%=:", c) != null)) break false; + } else true; + if (plain) return exe; + if (std.mem.indexOfScalar(u8, exe, '\'') != null) return "pardes"; + return std.fmt.bufPrint(buf, "'{s}'", .{exe}) catch "pardes"; + } +}; + +extern "c" fn unsetenv(name: [*:0]const u8) c_int; + +/// For tests: unset `name` without compacting the environment block std +/// captured at startup (std.testing.environ and Io's spawns read it later). A +/// new variable first moves glibc's `environ` to a heap copy, which unsetenv +/// then compacts instead. Runtime code never changes this process's +/// environment (ChildEnv.exportVar). +pub fn testUnsetenv(name: [*:0]const u8) c_int { + _ = Shell.setenv("PARDES_TEST_ENVIRON_COPIED", "1", 1); + return unsetenv(name); +} + +/// The environment a pane's command is given (exportEnv, `$winid`, +/// ChildEnv), as `NAME=value` lines in `arena`, for a command that is not a +/// pane's: an Edit's filters, run from pane `serial`. +pub fn commandEnv(arena: std.mem.Allocator, serial: u32, adopts: bool) ![]const []const u8 { + ninep_io.exportEnv(serial, adopts); + exportWinid(serial); + var slots: ChildEnv.Slots = undefined; + const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; + var out: std.ArrayList([]const u8) = .empty; + var i: usize = 0; + while (envp[i]) |entry| : (i += 1) try out.append(arena, try arena.dupe(u8, std.mem.span(entry))); + return out.items; +} + +fn exportWinid(serial: u32) void { + var buf: [16]u8 = undefined; + ChildEnv.exportVar("winid", if (serial == 0) null else std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); // a u32 fits 16 +} + +/// The longest line a command pane runs (exec.zig refuses a longer one). +pub const exec_command_max = pardes.exec.command_max; + +/// A pane's pty size, in cells and in pixels: a program sizes its kitty +/// graphics by the pixels (yazi's previews; pardes nested in a pane). +pub fn ptyWinsize(core: ?*const pardes.Pardes, cols: u16, rows: u16) posix.winsize { + var ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; + if (core) |c| { + ws.xpixel = std.math.cast(u16, @as(u32, cols) * c.view().cell_pixels.w) orelse 0; + ws.ypixel = std.math.cast(u16, @as(u32, rows) * c.view().cell_pixels.h) orelse 0; + } + return ws; +} + +pub fn forkShell( + core: ?*pardes.Pardes, + pane: usize, + prompt_rcs: *const Shell.PromptFiles, + bin: []const u8, + cwd: []const u8, + rows: u16, + cols: u16, +) !Child { + const native_cwd = filesystem.localPath(cwd) orelse cwd; + if (std.mem.indexOfScalar(u8, native_cwd, 0) != null) return error.InvalidPath; + var cwd_buf: [4096]u8 = undefined; + const serial = if (core) |c| if (c.panes[pane]) |pn| pn.serial else 0 else 0; + const cwd_z: ?[:0]const u8 = if (native_cwd.len == 0) null else dir: { + const path = std.fmt.bufPrintSentinel(&cwd_buf, "{s}", .{native_cwd}, 0) catch return error.NameTooLong; + // A shell's directory may be inside a mount this editor serves. + pardes.turn.yield(); + defer pardes.turn.back(); + const stat = try @import("core").filesystem.statPath(std.Io.Threaded.global_single_threaded.io(), path, .{}); + if (stat.kind != .directory) return error.NotDir; + break :dir path; + }; + var master: c_int = -1; + var path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + // A terminal opened on a shell of its own (`Term fish`) runs that one, + // copied: looking it up gives the turn up, and the pane may go. + var own_buf: [256]u8 = undefined; + var own: ?[]const u8 = null; + if (core) |c| if (c.panes[pane]) |pn| if (pn.shell) |name| { + const n = @min(name.len, own_buf.len); + @memcpy(own_buf[0..n], name[0..n]); + own = own_buf[0..n]; + }; + var spawn = Shell.resolve(own orelse bin, &path_buf, prompt_rcs); + // The turn was given up for the stat and the lookup: a 9P client may + // have closed the pane, and another taken its slot, whose command this + // is not. + if (core) |c| if ((if (c.panes[pane]) |pn| pn.serial else 0) != serial) return error.PaneGone; + // A command pane's child is the shell running its one line, which has + // no prompt to mark (exec.zig runCommand). + const one_line = if (core) |c| if (c.panes[pane]) |pn| pn.command else null else null; + var command_buf: [exec_command_max + 1]u8 = undefined; + if (one_line) |line| { + if (line.len > exec_command_max or std.mem.indexOfScalar(u8, line, 0) != null) return error.InvalidCommand; + @memcpy(command_buf[0..line.len], line); + command_buf[line.len] = 0; + spawn.argv = Shell.commandArgv(spawn.path, command_buf[0..line.len :0].ptr); + } + ninep_io.exportEnv( + if (core) |c| (if (c.panes[pane]) |pn| pn.serial else 0) else 0, + if (core) |c| !c.opts.nested else false, + ); + // acme's `$winid`: the pane a command was run from, so a script it runs + // can address that pane; unset for a shell and a header tag's command. + exportWinid(if (core) |c| (if (c.panes[pane]) |pn| (if (pn.command != null) pn.command_from else 0) else 0) else 0); + // Built here and not after the fork: between fork and exec the child may + // not call setenv, whose malloc can deadlock against a pty reader thread + // that held the heap when the fork took its snapshot. + var env_slots: ChildEnv.Slots = undefined; + const pages = if (core) |c| if (c.panes[pane]) |pn| pn.command_pages else false else false; + const paging: ChildEnv.Paging = if (one_line != null and !pages) + .command + else + .terminal; + const envp = ChildEnv.build(&env_slots, paging); + const ws = ptyWinsize(core, cols, rows); + // The child says here why it could not become the shell (its chdir or + // its exec failed, as for a script whose interpreter is not there): the + // pipe closes on exec, so the parent reads nothing when the shell runs, + // and a reason when it did not, before anyone is told it started. + var told: [2]c_int = .{ -1, -1 }; + // pipe and then CLOEXEC, not pipe2, which macOS has not. + if (libc.pipe(&told) != 0) return error.PipeFailed; + ninep_io.setCloexec(told[0]); + ninep_io.setCloexec(told[1]); + const pid = forkpty(&master, null, null, &ws); + if (pid < 0) { + _ = libc.close(told[0]); + _ = libc.close(told[1]); + return error.ForkFailed; + } + if (pid == 0) { + resetChildSignals(); + if (cwd_z) |path| if (chdir(path.ptr) != 0) { + const why = [_]u8{ 'c', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; + _ = libc.write(told[1], &why, why.len); + _exit(126); + }; + if (envp) |env| _ = execve(spawn.path, &spawn.argv, env); + _ = execv(spawn.path, &spawn.argv); + const why = [_]u8{ 'x', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; + _ = libc.write(told[1], &why, why.len); + _exit(127); + } + _ = libc.close(told[1]); + const failed = failed: { + var why: [2]u8 = undefined; + pardes.turn.yield(); + defer pardes.turn.back(); + const n = libc.read(told[0], &why, why.len); + _ = libc.close(told[0]); + if (n != 2) break :failed null; + break :failed why; + }; + if (failed) |why| { + _ = libc.close(master); + _ = libc.waitpid(pid, null, 0); + const e: libc.E = @fromBackingInt(@intCast(why[1])); + if (why[0] == 'c') return if (e == .NOENT or e == .NOTDIR) error.FileNotFound else error.AccessDenied; + return switch (e) { + // Itself, or its script's interpreter: told apart by whether it + // is there. + .NOENT => if (libc.access(spawn.path, 0) == 0) error.InterpreterNotFound else error.ShellNotFound, + .ACCES, .PERM => error.ShellNotExecutable, + .NOEXEC => error.ShellNotExecutable, + else => error.ShellDidNotStart, + }; + } + ninep_io.setCloexec(master); + // The daemon keeps a dup: this session killed outright never hangs the + // shell up (daemon.zig). + @import("runtime").daemon.pty(pid, master); + if (core) |c| c.acknowledgeShell(pane, std.mem.span(spawn.path), one_line == null and spawn.argv[1] != null); + return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid }; +} + +pub fn writeFd(fd: c_int, data: []const u8) bool { + var off: usize = 0; + while (off < data.len) { + const n = libc.write(fd, data[off..].ptr, data.len - off); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + return false; + } + if (n == 0) return false; + off += @intCast(n); + } + return true; +} + +const vnode_info_path = extern struct { + vi: [152]u8 align(8), // struct vnode_info: vinfo_stat + type + pad + fsid + path: [1024]u8, // MAXPATHLEN +}; +const proc_vnodepathinfo = extern struct { + cdir: vnode_info_path, + rdir: vnode_info_path, +}; +const PROC_PIDVNODEPATHINFO: c_int = 9; +extern "c" fn proc_pidinfo(pid: c_int, flavor: c_int, arg: u64, buffer: *anyopaque, buffersize: c_int) c_int; + +/// Whether an adopted shell marks its prompts: one pardes started with its +/// prompt files (bash, zsh, fish), which a pane's runs wait on. +pub fn marksPrompts(pid: libc.pid_t) bool { + var buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const exe = std.Io.Dir.path.basename(processExe(pid, &buf) orelse return false); + for ([_][]const u8{ "bash", "zsh", "fish" }) |shell| if (std.mem.eql(u8, exe, shell)) return true; + return false; +} + +/// The program `pid` runs, where the system says (an adopted shell's, for +/// its pane's Term word); null elsewhere. +pub fn processExe(pid: libc.pid_t, buf: []u8) ?[]const u8 { + if (comptime builtin.os.tag == .freebsd) { + const n = kernProc(pid, 12, buf) orelse return null; // KERN_PROC_PATHNAME + return if (n > 1) buf[0 .. n - 1] else null; + } + if (comptime builtin.os.tag != .linux) return null; + var pbuf: [64]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/exe", .{pid}, 0) catch unreachable; // a pid fits 64 + const n = libc.readlink(path, buf.ptr, buf.len); + if (n <= 0 or n >= buf.len) return null; + return buf[0..@intCast(n)]; +} + +pub fn shellCwd(pid: libc.pid_t, buf: []u8) ?[]const u8 { + switch (builtin.os.tag) { + .linux => { + var pbuf: [64]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/cwd", .{pid}, 0) catch unreachable; // a pid fits 64 + const n = libc.readlink(path, buf.ptr, buf.len); + if (n <= 0 or n >= buf.len) return null; + const link = buf[0..@intCast(n)]; + // A directory removed under the shell reads `<path> (deleted)`: + // no directory to be named by, so the name it had stays, and a + // restart works there once it is back. + if (std.mem.endsWith(u8, link, " (deleted)")) { + _ = @import("core").filesystem.statPath(std.Io.Threaded.global_single_threaded.io(), link, .{}) catch return null; + } + return link; + }, + .macos, .ios, .tvos, .watchos, .visionos => { + var info: proc_vnodepathinfo = undefined; + const n = proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &info, @sizeOf(proc_vnodepathinfo)); + if (n < @as(c_int, @sizeOf(proc_vnodepathinfo))) return null; + const path = std.mem.sliceTo(&info.cdir.path, 0); + if (path.len == 0 or path.len == info.cdir.path.len or path.len > buf.len) return null; + @memcpy(buf[0..path.len], path); + return buf[0..path.len]; + }, + .freebsd => { + // A struct kinfo_file (sys/user.h), its last 1024 bytes the path. + var kf: [1392]u8 align(8) = undefined; + const n = kernProc(pid, 42, &kf) orelse return null; // KERN_PROC_CWD + if (n <= 368) return null; + const path = std.mem.sliceTo(kf[368..n], 0); + if (path.len == 0 or path.len >= buf.len) return null; + @memcpy(buf[0..path.len], path); + return buf[0..path.len]; + }, + else => return null, + } +} + +/// FreeBSD's kern.proc.<what>.<pid> into `buf`: the bytes it wrote. +fn kernProc(pid: libc.pid_t, what: c_int, buf: []u8) ?usize { + const mib = [_]c_int{ 1, 14, what, pid }; // CTL_KERN, KERN_PROC + var len: usize = buf.len; + if (libc.sysctl(&mib, mib.len, buf.ptr, &len, null, 0) != 0) return null; + return len; +} + +/// Where a terminal is. The process forked for it, while it still runs the +/// shell pardes started (`shell_exe`), as ever: a job it runs, in another +/// directory (`(cd sub && make)`, a nested pardes), never names the pane. +/// One that exec'd into something else is a wrapper whose own directory +/// never moves (fish's `exec 9ns --mntgen -- fish`): the shell is the +/// foreground group when that is the same shell, and while a job holds the +/// foreground there is no answer, the last one standing. +pub fn ttyCwd(shell_pid: libc.pid_t, master_fd: c_int, shell_exe: []const u8, buf: []u8) ?[]const u8 { + var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var shell_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const shell = realShell(shell_exe, &shell_buf) orelse return shellCwd(shell_pid, buf); + const exe = processExe(shell_pid, &exe_buf) orelse return shellCwd(shell_pid, buf); + if (std.mem.eql(u8, exe, shell)) return shellCwd(shell_pid, buf); + const fg = tcgetpgrp(master_fd); + if (fg <= 0 or fg == shell_pid) return null; + const fg_exe = processExe(fg, &exe_buf) orelse return null; + return if (std.mem.eql(u8, fg_exe, shell)) shellCwd(fg, buf) else null; +} + +/// `shell_exe` as /proc/<pid>/exe would read it: its links followed. +fn realShell(shell_exe: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[]const u8 { + var z: [std.Io.Dir.max_path_bytes:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&z, "{s}", .{shell_exe}, 0) catch return null; + const r = libc.realpath(path, buf) orelse return null; + return std.mem.span(@as([*:0]const u8, @ptrCast(r))); +} + +extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; + +const occ_max_depth: u8 = 8; +const occ_max_visited: usize = 32; + +/// Where `ttyTaken` answers from evidence rather than from `false`. The two +/// implementations are different walks over the same question, so they share +/// one suite rather than each asserting half of it. +const tty_probe_platform = switch (builtin.os.tag) { + .linux, .macos => true, + else => false, +}; + +const TtyProbe = struct { + self_exe: [std.Io.Dir.max_path_bytes]u8 = undefined, + exe: [std.Io.Dir.max_path_bytes]u8 = undefined, + blob: [4096]u8 = undefined, + pending: [occ_max_visited]Node = undefined, + + const Node = struct { pid: libc.pid_t, depth: u8 }; +}; + +pub fn ttyTaken(shell_pid: libc.pid_t, master_fd: c_int) bool { + switch (builtin.os.tag) { + .linux => { + var probe: TtyProbe = undefined; + const fg = tcgetpgrp(master_fd); + if (fg < 0) return false; + const self_exe = processExe(shell_pid, &probe.self_exe) orelse return false; + + var saw_fg = fg == shell_pid; + var pending: usize = 0; + var visited: usize = 0; + switch (pushChildren(&probe, &pending, shell_pid, 1)) { + .pushed => {}, + .unreadable => return false, + .full => return true, + } + + while (pending > 0) { + pending -= 1; + const node = probe.pending[pending]; + visited += 1; + if (visited > occ_max_visited) return true; + + const pgrp = procPgrp(node.pid, &probe.blob); + if (pgrp) |g| { + if (g == fg) saw_fg = true; + } + + const exe = processExe(node.pid, &probe.exe) orelse { + if (offTty(node.pid, &probe.blob)) continue; + // Exiting (its exe gone, not a zombie yet), or not ours + // to read: outside the foreground group it holds + // nothing, as a killed background job does for a moment. + if (pgrp) |g| if (g != fg) continue; + return true; + }; + if (!std.mem.eql(u8, exe, self_exe)) { + if (pgrp) |g| if (g == fg) return true; + continue; + } + if (node.depth >= occ_max_depth) return true; + switch (pushChildren(&probe, &pending, node.pid, node.depth + 1)) { + .pushed => {}, + .unreadable => {}, + .full => return true, + } + } + return !saw_fg; + }, + .macos => { + const fg = tcgetpgrp(master_fd); + if (fg <= 0) return false; + if (fg == shell_pid) return false; + return darwin.taken(shell_pid, fg); + }, + // ponytail: any foreground job but the shell's own group, so a + // nested interactive shell counts as taken; walk the group + // (KERN_PROC_PGRP) as darwin does if that matters. + .freebsd => { + const fg = tcgetpgrp(master_fd); + return fg > 0 and fg != shell_pid; + }, + else => return false, + } +} + +/// The same question the Linux walk asks, answered the way macOS can answer +/// it. There is no /proc to descend and no children list, but the tty's +/// foreground process group can be enumerated in one call — and "is anything +/// but the shell itself holding this terminal?" is exactly a statement about +/// the executables in that group. The test is the shell's own executable and +/// never its pid, which is what keeps a nested interactive shell a prompt, +/// and what still catches `bash -c 'sleep 30'`: the group holds `sleep` too. +/// +/// Until this existed, `ttyTaken` answered `false` on darwin for every pane, +/// so `exec.takesCommandLine` was permanently true and every bare Escape in +/// a raw terminal ran the `Last` builtin instead of reaching the child. +const darwin = struct { + const proc_pgrp_only: u32 = 2; + const proc_pidt_shortbsdinfo: c_int = 13; + const zombie_status: u32 = 5; // SZOMB + /// PROC_PIDPATHINFO_MAXSIZE. + const path_max = 4 * 1024; + /// A foreground group is a pipeline; anything larger is not a prompt. + const group_max = 64; + + const ShortBsdInfo = extern struct { + pid: u32, + ppid: u32, + pgid: u32, + status: u32, + comm: [16]u8, + flags: u32, + uid: u32, + gid: u32, + ruid: u32, + rgid: u32, + svuid: u32, + svgid: u32, + rfu: u32, + }; + + extern "c" fn proc_listpids(kind: u32, typeinfo: u32, buffer: ?*anyopaque, buffersize: c_int) c_int; + extern "c" fn proc_pidpath(pid: c_int, buffer: [*]u8, buffersize: u32) c_int; + + fn exe(pid: libc.pid_t, buf: *[path_max]u8) ?[]const u8 { + const got = proc_pidpath(pid, buf, buf.len); + if (got <= 0) return null; + return buf[0..@intCast(got)]; + } + + /// A pid with no readable path is either gone or not ours. Only a zombie + /// is provably harmless — it holds no tty — so everything else is taken. + fn zombie(pid: libc.pid_t) bool { + var info: ShortBsdInfo = undefined; + const got = proc_pidinfo(pid, proc_pidt_shortbsdinfo, 0, &info, @sizeOf(ShortBsdInfo)); + if (got != @sizeOf(ShortBsdInfo)) return false; + return info.status == zombie_status; + } + + fn taken(shell_pid: libc.pid_t, fg: libc.pid_t) bool { + var shell_buf: [path_max]u8 = undefined; + const shell_exe = exe(shell_pid, &shell_buf) orelse return false; + var group: [group_max]libc.pid_t = undefined; + const bytes = proc_listpids(proc_pgrp_only, @intCast(fg), &group, @sizeOf(@TypeOf(group))); + // An empty group is a group whose last member just exited: the shell + // is about to have its terminal back, and calling that taken would + // blink the prompt heuristic off for a frame every time a job ends. + if (bytes <= 0) return false; + const n = @as(usize, @intCast(bytes)) / @sizeOf(libc.pid_t); + if (n >= group.len) return true; + var exe_buf: [path_max]u8 = undefined; + for (group[0..n]) |pid| { + if (pid <= 0 or pid == shell_pid) continue; + const path = exe(pid, &exe_buf) orelse { + if (zombie(pid)) continue; + return true; + }; + if (!std.mem.eql(u8, path, shell_exe)) return true; + } + return false; + } +}; + +/// A program a plumbing rule starts (Effect.start), as Plan 9's plumber +/// starts one (match.c's startup): out of the editor's way, a session of +/// its own reaped by init, stdin, stdout and stderr /dev/null and no other +/// fd of the editor's, its argv exec'd (no shell: a rule that wants one +/// says `sh -c`) in its directory. `line` is its directory, then its argv, +/// each ended by a NUL. Null once it runs, else why not, as errno says it, +/// in `why` (as the tape replays a host's words): a pipe closed at the +/// exec carries the child's errno back. +pub fn startDetached(_: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 { + const words = startWords(line) orelse return null; + const n = @min(words.len, why.len); + @memcpy(why[0..n], words[0..n]); + return why[0..n]; +} + +fn startWords(line: []const u8) ?[]const u8 { + var buf: [pardes.effect_path_cap]u8 = undefined; + if (line.len == 0 or line.len > buf.len or line[line.len - 1] != 0) return "malformed"; + @memcpy(buf[0..line.len], line); + var argv: [64:null]?[*:0]const u8 = @splat(null); + var n: usize = 0; + var at: usize = 0; + var dir: [*:0]const u8 = undefined; + while (at < line.len) { + const end = std.mem.indexOfScalarPos(u8, line, at, 0).?; + const word: [*:0]const u8 = @ptrCast(&buf[at]); + if (at == 0) dir = word else if (n < argv.len) { + argv[n] = word; + n += 1; + } else return "more than 64 words"; + at = end + 1; + } + if (n == 0) return "no program"; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return "no pipe"; + for (fds) |fd| _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const first = libc.fork(); + if (first < 0) { + _ = libc.close(fds[0]); + _ = libc.close(fds[1]); + return "no fork"; + } + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + if (libc.fork() != 0) libc._exit(0); + resetChildSignals(); + // What failed, then errno: 'd' the directory, 'x' the exec. + const Fail = struct { + fn say(fd: c_int, what: u8) noreturn { + var said: [5]u8 = undefined; + said[0] = what; + std.mem.writeInt(u32, said[1..5], @intFromEnum(libc.errno(-1)), .little); + _ = libc.write(fd, &said, said.len); + libc._exit(127); + } + }; + const err_fd = libc.fcntl(fds[1], libc.F.DUPFD_CLOEXEC, @as(c_int, 3)); + if (err_fd < 0) libc._exit(127); + if (dir[0] != 0 and libc.chdir(dir) != 0) Fail.say(err_fd, 'd'); + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); + if (null_fd >= 0) for (0..3) |i| { + _ = libc.dup2(null_fd, @intCast(i)); + }; + // Every fd of the editor's but the errno pipe's gone: a pty's + // master held open would keep its terminal alive. + if (libc.dup2(err_fd, 3) < 0) libc._exit(127); + _ = libc.fcntl(3, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const shut = if (comptime builtin.os.tag == .linux) + std.os.linux.close_range(4, std.math.maxInt(i32), .{ .UNSHARE = false, .CLOEXEC = false }) == 0 + else + false; + if (!shut) { + var fd: c_int = 4; + while (fd < 1024) : (fd += 1) _ = libc.close(fd); + } + _ = execvp(argv[0].?, &argv); + Fail.say(3, 'x'); + } + _ = libc.close(fds[1]); + while (libc.waitpid(first, null, 0) < 0 and libc.errno(-1) == .INTR) {} + var said: [5]u8 = undefined; + var got: usize = 0; + while (got < said.len) { + const r = libc.read(fds[0], said[got..].ptr, said.len - got); + if (r < 0 and libc.errno(r) == .INTR) continue; + if (r <= 0) break; + got += @intCast(r); + } + _ = libc.close(fds[0]); + if (got < said.len) return null; + const code = std.mem.readInt(u32, said[1..5], .little); + const E = libc.E; + if (code == @intFromEnum(E.NOENT)) return if (said[0] == 'd') "its directory: no such directory" else "not found"; + if (code == @intFromEnum(E.ACCES)) return "permission denied"; + if (code == @intFromEnum(E.NOTDIR)) return "not a directory"; + if (code == @intFromEnum(E.NOEXEC)) return "not an executable"; + return if (said[0] == 'd') "its directory: cannot go there" else "cannot start it"; +} + +extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; + +/// A terminal pane's shell is done with (its pane gone, its pty closed or at +/// end of file): say hangup, for a shell that ignores the tty's, and see it +/// reaped, killed if it is still there 100 ms on. A thread does the waiting +/// so that no host loop needs a timer for it (macOS's has none); a thread +/// that cannot start kills and reaps it here. +/// ponytail: only the window waits for them at exit (waitRetired); the tui +/// and macOS leave a shell still inside its 100 ms to init, a waitRetired at +/// their exit if that matters. +pub fn retireShell(pid: libc.pid_t) void { + if (pid <= 0) return; + _ = libc.kill(pid, libc.SIG.HUP); + if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; + _ = retiring.fetchAdd(1, .monotonic); + const thread = std.Thread.spawn(.{}, reapRetiring, .{pid}) catch { + _ = retiring.fetchSub(1, .monotonic); + return reapShell(pid, 0); + }; + thread.detach(); +} + +/// retireShell's threads still waiting on a shell. +var retiring: std.atomic.Value(u32) = .init(0); + +fn reapRetiring(pid: libc.pid_t) void { + defer _ = retiring.fetchSub(1, .release); + reapShell(pid, 100); +} + +/// An exit's sweep: every shell retireShell still waits on is seen out, gone +/// on its hangup or killed at the end of its 100 ms, and reaped, rather than +/// left to init. +pub fn waitRetired() void { + while (retiring.load(.acquire) != 0) { + const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } +} + +// ---- a command pane's child, watched to its exit ---- +// +// A command pane's command is done when its process exits, not when its pty +// reaches end of file: a job it put in the background can hold the pty open +// after it has gone, and a command can close its terminal and run on. A +// thread per command waits for the exit without reaping (WNOWAIT), so the +// pid is still the child's -- no Kill can reach another process that took +// it -- until the host, told through `takeExited`, reaps it in its own loop +// with `exitStatus` and tells the core. + +const freebsd = builtin.os.tag == .freebsd; +const waitid_p_pid: c_int = if (freebsd) 0 else 1; +const waitid_wexited: c_int = if (freebsd) 16 else 4; +const waitid_wnowait: c_int = switch (builtin.os.tag) { + .linux => 0x01000000, + .freebsd => 8, + else => 0x20, +}; +// FreeBSD's id_t is 64 bits. +extern "c" fn waitid(idtype: c_int, id: if (freebsd) i64 else c_uint, infop: *anyopaque, options: c_int) c_int; + +var exited: [pardes.MAX_PANES * 2]std.atomic.Value(libc.pid_t) = @splat(.init(0)); +var exit_lock: libc.pthread_mutex_t = .{}; +var exit_wake: ?struct { ctx: ?*anyopaque, f: *const fn (?*anyopaque) void } = null; + +/// Who wakes the host's loop when a watched child exits; null at shutdown, +/// after which a watcher still waiting tells nobody. +pub fn setExitWake(ctx: ?*anyopaque, f: ?*const fn (?*anyopaque) void) void { + _ = libc.pthread_mutex_lock(&exit_lock); + defer _ = libc.pthread_mutex_unlock(&exit_lock); + exit_wake = if (f) |wake| .{ .ctx = ctx, .f = wake } else null; +} + +/// Watches a command pane's child; false when no thread could be started, +/// and the host then reads its exit at end of file instead. +pub fn watchExit(pid: libc.pid_t) bool { + const thread = std.Thread.spawn(.{}, watchChild, .{pid}) catch return false; + thread.detach(); + return true; +} + +fn watchChild(pid: libc.pid_t) void { + var info: [128]u8 align(16) = undefined; + while (waitid(waitid_p_pid, @intCast(pid), &info, waitid_wexited | waitid_wnowait) < 0 and libc.errno(-1) == .INTR) {} + // A cell for it, waiting for one if the host is slow to take them. + place: while (true) { + for (&exited) |*cell| if (cell.cmpxchgStrong(0, pid, .acq_rel, .acquire) == null) break :place; + const ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + wakeForExit(); +} + +fn wakeForExit() void { + _ = libc.pthread_mutex_lock(&exit_lock); + defer _ = libc.pthread_mutex_unlock(&exit_lock); + if (exit_wake) |wake| wake.f(wake.ctx); +} + +/// Where a host's command pane is between its child's exit and the end of +/// its output. The exit is told once the output before it is in: at the +/// pty's end of file; or, when something else still holds the pty (a job +/// the command left in the background), once nothing is waiting to be read +/// -- checked when the exit is seen and again after each chunk of output, +/// with no timer to miss. acme's waitthread tells an exit when it is +/// reaped (acme.c:587-700); a terminal also has output in flight. +pub const CommandWatch = struct { + watched: bool = false, + /// The master, to ask whether output is still waiting. + fd: c_int = -1, + eof: bool = false, + exited: bool = false, + told: bool = false, + status: ?u8 = null, + + /// Whether the exit is to be told now. + pub fn due(w: *const CommandWatch) bool { + if (!w.exited or w.told) return false; + if (w.eof) return true; + var pfd = [1]libc.pollfd{.{ .fd = w.fd, .events = libc.POLL.IN, .revents = 0 }}; + if (libc.poll(&pfd, 1, 0) < 0) return true; + // Every holder of its terminal gone: the end of file comes, after + // the rest of the output. + if (pfd[0].revents & libc.POLL.HUP != 0) return false; + return pfd[0].revents & libc.POLL.IN == 0; + } +}; + +/// A host's pty slot, whichever way it keeps it: an optional, or one whose +/// `fd` is -1 when empty. +fn SlotPty(comptime S: type) type { + return switch (@typeInfo(S)) { + .optional => |o| *o.child, + else => *S, + }; +} + +fn slotPty(slot: anytype) ?SlotPty(@TypeOf(slot.*)) { + return switch (@typeInfo(@TypeOf(slot.*))) { + .optional => if (slot.*) |*pt| pt else null, + else => if (slot.fd < 0) null else slot, + }; +} + +/// Each watched child that exited: reaped, and the core told once its +/// output is in, its pty closed (`close(ctx, id)`) if its end of file came +/// first. Every host runs this after an exit's wake and after each chunk +/// of a command's output; `ptys` is its slot array, each slot with a `pid` +/// and a `cmd`. +pub fn takeExits(core: *pardes.Pardes, ptys: anytype, ctx: anytype, comptime close: anytype) void { + while (takeExited()) |pid| for (ptys) |*slot| { + const pt = slotPty(slot) orelse continue; + if (!pt.cmd.watched or pt.pid != pid or pt.cmd.exited) continue; + pt.cmd.status = (reapExited(pid) orelse break).status; + pt.cmd.exited = true; + pt.pid = 0; // reaped: no signal or retire may reach whoever gets it next + break; + }; + for (ptys, 0..) |*slot, id| { + const pt = slotPty(slot) orelse continue; + if (!pt.cmd.watched or !pt.cmd.due()) continue; + pt.cmd.told = true; + const eof = pt.cmd.eof; + core.update(.{ .exited = .{ .pane = @intCast(id), .status = pt.cmd.status } }); + if (eof) close(ctx, id); + } +} + +/// A watched command's pty reached end of file: the core hears its output +/// is over; the pty is closed now if its exit was told, else when it is. +pub fn commandEof(core: *pardes.Pardes, ptys: anytype, id: usize, ctx: anytype, comptime close: anytype) void { + const pt = slotPty(&ptys[id]) orelse return; + pt.cmd.eof = true; + core.update(.{ .eof = .{ .pane = @intCast(id) } }); + if (pt.cmd.told) return close(ctx, id); + takeExits(core, ptys, ctx, close); +} + +/// Reaps `pid` if it has exited: its status (null: unknown, or not ours +/// to read), or null when it is still running -- a pid a watcher reported +/// may since have been reaped by another and taken by a new child. +pub fn reapExited(pid: libc.pid_t) ?struct { status: ?u8 } { + if (pid <= 0) return .{ .status = null }; + var status: c_int = 0; + const got = libc.waitpid(pid, &status, libc.W.NOHANG); + if (got == 0) return null; + if (got != pid) return .{ .status = null }; + return .{ .status = statusOf(status) }; +} + +/// A wait status as a shell says it: the exit code, or 128 and the signal +/// that ended it; null for neither. +fn statusOf(status: c_int) ?u8 { + const s: u32 = @bitCast(status); + if (libc.W.IFEXITED(s)) return @truncate(libc.W.EXITSTATUS(s)); + if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))); + return null; +} + +/// A watched child that has exited, not yet reaped, or null. +pub fn takeExited() ?libc.pid_t { + for (&exited) |*cell| { + const pid = cell.swap(0, .acq_rel); + if (pid != 0) return pid; + } + return null; +} + +/// A pane's child at its pty's end of file: reaped, and how it exited +/// (its code, or 128 and the signal that ended it), if it is gone within +/// `wait_ms`; null if it is still running (a job it left holds nothing +/// open, but the child itself may be a moment behind its pty), which the +/// caller then retires as it would any shell. +pub fn exitStatus(pid: libc.pid_t, wait_ms: u32) ?u8 { + if (pid <= 0) return null; + var waited: u32 = 0; + while (true) : (waited += 2) { + var status: c_int = 0; + const got = libc.waitpid(pid, &status, libc.W.NOHANG); + if (got == pid) return statusOf(status); + if (got < 0 or waited >= wait_ms) return null; + const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } +} + +fn reapShell(pid: libc.pid_t, grace_ms: u32) void { + var waited: u32 = 0; + while (waited < grace_ms) : (waited += 5) { + // Not 0 is reaped, or someone else reaped it: either way not ours. + if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; + const ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; + _ = libc.kill(pid, libc.SIG.KILL); + while (libc.waitpid(pid, null, 0) < 0 and libc.errno(-1) == .INTR) {} +} + +/// The tty's foreground job is signalled. A command pane's shell (`command`) +/// is its command too: its line runs with job control on, so the job +/// running is in a group of its own, and the shell's group goes as well, or +/// the rest of the line would run on after the job it was on. A stop (TERM +/// or KILL) of a command reaches its `&` jobs too, each in a group of its +/// own in the shell's session: Kill leaves nothing the line started. +/// The shell goes first: a job that died before it would let it run the +/// line's next command in the gap, and the gap is a scan of all of /proc +/// (signalSession), long once pids have wrapped below the old processes'. +pub fn signalTty(shell_pid: libc.pid_t, master_fd: c_int, which: pardes.PtySignal, command: bool) void { + const sig = switch (which) { + .int => libc.SIG.INT, + .term => libc.SIG.TERM, + .hup => libc.SIG.HUP, + .quit => libc.SIG.QUIT, + .kill => libc.SIG.KILL, + }; + const fg = tcgetpgrp(master_fd); + if (command and shell_pid > 0 and fg != shell_pid) _ = libc.kill(-shell_pid, sig); + if (command and shell_pid > 0 and (which == .term or which == .kill)) signalSession(shell_pid, sig); + if (fg > 0) _ = libc.kill(-fg, sig); + if (fg <= 0 and !command and shell_pid > 0) _ = libc.kill(shell_pid, sig); +} + +/// Every process group in the session `sid` leads, but its own (which the +/// caller signals last). forkpty made the shell the session's leader, and +/// job control moves a job to a new group, never out of the session. +// ponytail: Linux only (a /proc scan); elsewhere a `&` job outlives Kill, +// add sysctl KERN_PROC_SESSION on macOS if that matters. +fn signalSession(sid: libc.pid_t, sig: libc.SIG) void { + if (comptime builtin.os.tag != .linux) return; + const d = libc.opendir("/proc") orelse return; + defer _ = libc.closedir(d); + var buf: [4096]u8 = undefined; + while (libc.readdir(d)) |ent| { + const name = std.mem.sliceTo(&ent.name, 0); + const pid = std.fmt.parseInt(libc.pid_t, name, 10) catch continue; + var path_buf: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/stat", .{pid}, 0) catch unreachable; // a pid fits 64 + const ids = parseGroupSession(readProc(path, &buf) orelse continue) orelse continue; + if (ids.session == sid and ids.pgrp != sid) _ = libc.kill(-ids.pgrp, sig); + } +} + +fn parseGroupSession(stat: []const u8) ?struct { pgrp: libc.pid_t, session: libc.pid_t } { + const close = std.mem.lastIndexOfScalar(u8, stat, ')') orelse return null; + var fields = std.mem.tokenizeAny(u8, stat[close + 1 ..], " \t\n"); + _ = fields.next() orelse return null; // 3: state + _ = fields.next() orelse return null; // 4: ppid + const pgrp = std.fmt.parseInt(libc.pid_t, fields.next() orelse return null, 10) catch return null; + const session = std.fmt.parseInt(libc.pid_t, fields.next() orelse return null, 10) catch return null; + return .{ .pgrp = pgrp, .session = session }; +} + +/// Kill: SIGTERM to the job in the tty's foreground, never to the shell. +/// The shell leads its own group, and a job it runs has another; with job +/// control off (`set +m`, a shell run as `sh -c`) the job shares the shell's +/// group, and there is no job to signal apart from it: false. +pub fn killJob(shell_pid: libc.pid_t, master_fd: c_int) bool { + const fg = tcgetpgrp(master_fd); + if (fg <= 0 or fg == shell_pid) return false; + return libc.kill(-fg, libc.SIG.TERM) == 0; +} + +/// The command name of the tty's foreground job, when that is not the +/// shell: what `pty/run` says is running. /proc/<pgrp>/comm on Linux, the +/// program's name on FreeBSD. +pub fn foregroundName(shell_pid: libc.pid_t, master_fd: c_int, buf: []u8) ?[]const u8 { + if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) return null; + const fg = tcgetpgrp(master_fd); + if (fg <= 0 or fg == shell_pid) return null; + if (comptime builtin.os.tag == .freebsd) return std.Io.Dir.path.basename(processExe(fg, buf) orelse return null); + var name: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/comm", .{@as(u32, @intCast(fg))}, 0) catch unreachable; // a u32 fits 64 + const comm = std.mem.trimEnd(u8, readProc(path, buf) orelse return null, "\n"); + return if (comm.len > 0) comm else null; +} + +fn readProc(path: [*:0]const u8, buf: []u8) ?[]const u8 { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return null; + defer _ = libc.close(fd); + const got = libc.read(fd, buf.ptr, buf.len); + if (got <= 0) return null; + return buf[0..@intCast(got)]; +} + +fn procPgrp(pid: libc.pid_t, buf: *[4096]u8) ?libc.pid_t { + var name: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/stat", .{@as(u32, @intCast(pid))}, 0) catch unreachable; // a u32 fits 64 + return (parseGroupSession(readProc(path, buf) orelse return null) orelse return null).pgrp; +} + +fn offTty(pid: libc.pid_t, buf: *[4096]u8) bool { + var name: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/status", .{@as(u32, @intCast(pid))}, 0) catch unreachable; // a u32 fits 64 + const status = readProc(path, buf) orelse return true; + return parseZombie(status); +} + +fn parseZombie(status: []const u8) bool { + var lines = std.mem.splitScalar(u8, status, '\n'); + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, "State:")) continue; + const state = std.mem.trim(u8, line["State:".len..], " \t\r"); + return state.len > 0 and state[0] == 'Z'; + } + return false; +} + +const Pushed = enum { pushed, unreadable, full }; + +fn pushChildren(probe: *TtyProbe, pending: *usize, pid: libc.pid_t, depth: u8) Pushed { + var name: [96:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/task/{d}/children", .{ + @as(u32, @intCast(pid)), @as(u32, @intCast(pid)), + }, 0) catch unreachable; // two u32s fit 96 + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return .unreadable; + defer _ = libc.close(fd); + const got = libc.read(fd, &probe.blob, probe.blob.len); + if (got < 0) return .unreadable; + + var kids: [occ_max_visited]libc.pid_t = undefined; + const total = parseChildren(probe.blob[0..@intCast(got)], &kids); + if (total > kids.len or pending.* + total > probe.pending.len) return .full; + for (kids[0..total]) |kid| { + probe.pending[pending.*] = .{ .pid = kid, .depth = depth }; + pending.* += 1; + } + return .pushed; +} + +fn parseChildren(text: []const u8, out: []libc.pid_t) usize { + var total: usize = 0; + var it = std.mem.tokenizeAny(u8, text, " \t\n\r"); + while (it.next()) |tok| { + if (std.mem.indexOfNone(u8, tok, "0123456789") != null) continue; + const kid = std.fmt.parseInt(libc.pid_t, tok, 10) catch continue; + if (total < out.len) out[total] = kid; + total += 1; + } + return total; +} + +const test_shell = "/bin/bash"; +const test_prompt = "PZX> "; + +const TestShell = struct { + master: c_int, + pid: libc.pid_t, + tail: [8192]u8 = undefined, + tail_len: usize = 0, + + fn start() ?TestShell { + if (!haveFile(test_shell)) return null; + var master: c_int = undefined; + const ws = std.posix.winsize{ .row = 24, .col = 80, .xpixel = 0, .ypixel = 0 }; + const pid = forkpty(&master, null, null, &ws); + if (pid < 0) return null; + if (pid == 0) { + const argv: [3:null]?[*:0]const u8 = .{ test_shell, "--norc", "-i" }; + _ = execv(test_shell, &argv); + _exit(127); + } + var sh: TestShell = .{ .master = master, .pid = pid }; + sh.send("export PS1='PZ''X> '\n"); + if (!sh.waitText(test_prompt, 10_000)) { + sh.stop(); + return null; + } + sh.forget(); + return sh; + } + + fn send(sh: *TestShell, bytes: []const u8) void { + _ = libc.write(sh.master, bytes.ptr, bytes.len); + } + + fn forget(sh: *TestShell) void { + sh.tail_len = 0; + } + + fn drain(sh: *TestShell) void { + while (true) { + var fds = [1]libc.pollfd{.{ .fd = sh.master, .events = libc.POLL.IN, .revents = 0 }}; + if (libc.poll(&fds, 1, 0) <= 0) return; + if (fds[0].revents & libc.POLL.IN == 0) return; + var chunk: [4096]u8 = undefined; + const n = libc.read(sh.master, &chunk, chunk.len); + if (n <= 0) return; + sh.append(chunk[0..@intCast(n)]); + } + } + + fn append(sh: *TestShell, bytes: []const u8) void { + if (bytes.len >= sh.tail.len) { + @memcpy(&sh.tail, bytes[bytes.len - sh.tail.len ..]); + sh.tail_len = sh.tail.len; + return; + } + const room = sh.tail.len - sh.tail_len; + if (bytes.len > room) { + const drop = bytes.len - room; + std.mem.copyForwards(u8, sh.tail[0 .. sh.tail_len - drop], sh.tail[drop..sh.tail_len]); + sh.tail_len -= drop; + } + @memcpy(sh.tail[sh.tail_len..][0..bytes.len], bytes); + sh.tail_len += bytes.len; + } + + fn waitText(sh: *TestShell, needle: []const u8, ms: i64) bool { + const deadline = nowMs() + ms; + while (true) { + sh.drain(); + if (std.mem.indexOf(u8, sh.tail[0..sh.tail_len], needle) != null) return true; + if (nowMs() >= deadline) return false; + sleepMs(5); + } + } + + fn taken(sh: *TestShell) bool { + sh.drain(); + return ttyTaken(sh.pid, sh.master); + } + + fn waitTaken(sh: *TestShell, want: bool, ms: i64) bool { + const deadline = nowMs() + ms; + while (true) { + if (sh.taken() == want) return true; + if (nowMs() >= deadline) return false; + sleepMs(5); + } + } + + fn holdsTaken(sh: *TestShell, want: bool, ms: i64) bool { + const deadline = nowMs() + ms; + while (nowMs() < deadline) { + if (sh.taken() != want) return false; + sleepMs(5); + } + return true; + } + + fn stop(sh: *TestShell) void { + if (comptime builtin.os.tag == .linux) { + var probe: TtyProbe = undefined; + var pending: usize = 0; + var doomed: [occ_max_visited]libc.pid_t = undefined; + var n: usize = 0; + _ = pushChildren(&probe, &pending, sh.pid, 1); + while (pending > 0) { + pending -= 1; + const node = probe.pending[pending]; + if (n == doomed.len) break; + doomed[n] = node.pid; + n += 1; + if (node.depth < occ_max_depth) _ = pushChildren(&probe, &pending, node.pid, node.depth + 1); + } + _ = libc.kill(sh.pid, libc.SIG.KILL); + for (doomed[0..n]) |kid| { + _ = libc.kill(kid, libc.SIG.KILL); + _ = libc.kill(-kid, libc.SIG.KILL); + } + } else { + // No children list to descend. forkpty made the shell a session + // leader, so its own group plus whichever group currently holds + // the tty covers the job the test left running. + const fg = tcgetpgrp(sh.master); + if (fg > 0 and fg != sh.pid) _ = libc.kill(-fg, libc.SIG.KILL); + _ = libc.kill(-sh.pid, libc.SIG.KILL); + _ = libc.kill(sh.pid, libc.SIG.KILL); + } + _ = libc.waitpid(sh.pid, null, 0); + _ = libc.close(sh.master); + } +}; + +fn haveFile(path: [*:0]const u8) bool { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return false; + _ = libc.close(fd); + return true; +} + +fn nowMs() i64 { + return std.Io.Clock.awake.now(std.testing.io).toMilliseconds(); +} + +fn sleepMs(ms: i64) void { + std.testing.io.sleep(.fromMilliseconds(ms), .awake) catch {}; +} + +// ---- what every host's vtable does alike ---- + +/// A Save's write: the file written through the core's filesystem, the +/// pane's watch told the new text is the editor's own (so it is no outside +/// change), and "saved" said on the pane. +pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, path: []const u8, bytes: []const u8) void { + filesystem.write(core, path, bytes) catch |err| + return core.saveFailed(pane, path, err); + if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { + if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { + .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, + .kind => {}, + }; + }; + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); + // The init file, saved here (Config): its settings take effect now. + pardes.exec.reapplyInitFile(core, path, bytes); + // The plumbing file (Plumb): its rules in force now. + pardes.Plumb.saved(core, pane, path, bytes); +} + +/// A Dump's write: into the state file under a label of its own +/// (Db.putDump), or as a file of its own where `Dump export` names one or +/// $PARDES_DUMP does (verbatim: the snapshot harness pins it for its +/// goldens). +pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { + const to: ?[]const u8 = core.dump_export orelse if (std.c.getenv("PARDES_DUMP")) |p| std.mem.span(p) else null; + if (to) |path| { + filesystem.write(core, path, bytes) catch |err| return core.dumpFailed(path, err); + return core.setLastDump(path); + } + var stamp: [64]u8 = undefined; + var buf: [128]u8 = undefined; + const label = core.db.putDump(core, bytes, pardes.dump.label(&stamp), &buf) catch |err| { + var path: [4200]u8 = undefined; + // In the words a host reports failures in (tape.Failure). + const said: pardes.tape.Failure = switch (err) { + error.NoStateFile => error.NoDumpDirectory, + error.OutOfMemory => error.OutOfMemory, + error.NoSpaceLeft => error.NoSpaceLeft, + error.AccessDenied => error.AccessDenied, + else => error.InputOutput, + }; + return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); + }; + core.setLastDump(label); +} + +/// DumpThemes: the built-in themes written below the config directory. +pub fn dumpThemes(core: *pardes.Pardes, io: std.Io, gpa: std.mem.Allocator, pane: u8) void { + const config_dir = core.opts.config_dir orelse return; + const out_dir = pardes.config.User.dumpThemes(io, gpa, config_dir, pardes.themes) catch |err| { + core.reportError(pane, "dump themes", err); + return; + }; + defer gpa.free(out_dir); + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "dumped themes", out_dir)); +} + +pub const PtyTests = struct { + pub fn waitBlocked(queue: *Inbox) !void { + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + queue.lock(); + const waiting = queue.waiting; + queue.unlock(); + if (waiting != 0) return; + try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + return error.ReaderDidNotBlock; + } + + fn tail(queue: *Inbox, bytes: []u8) void { + if (queue.pushOutput(0, 1, bytes)) queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + } +}; + +test { + _ = Lsp; +} + +test "a child starts with every signal at its default and none blocked" { + var blocked = posix.sigemptyset(); + posix.sigaddset(&blocked, posix.SIG.WINCH); + posix.sigprocmask(posix.SIG.BLOCK, &blocked, null); + defer posix.sigprocmask(posix.SIG.UNBLOCK, &blocked, null); + const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; + var was: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, &ignore, &was); + defer posix.sigaction(posix.SIG.HUP, &was, null); + const pid = libc.fork(); + if (pid == 0) { + resetChildSignals(); + var now: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, null, &now); + var mask = posix.sigemptyset(); + posix.sigprocmask(posix.SIG.BLOCK, null, &mask); + const ok = now.handler.handler == posix.SIG.DFL and !posix.sigismember(&mask, posix.SIG.WINCH); + libc._exit(if (ok) 0 else 1); + } + var status: c_int = 0; + _ = libc.waitpid(pid, &status, 0); + try std.testing.expectEqual(@as(c_int, 0), status); +} + +test "the pager's path is quoted only when it needs it" { + var buf: [64]u8 = undefined; + try std.testing.expectEqualStrings("/usr/bin/pardes", ChildEnv.pagerCommand("/usr/bin/pardes", &buf)); + try std.testing.expectEqualStrings("'/opt/my apps/pardes'", ChildEnv.pagerCommand("/opt/my apps/pardes", &buf)); + try std.testing.expectEqualStrings("pardes", ChildEnv.pagerCommand("/odd'dir/pardes", &buf)); +} + +test "the child environment replaces the launcher's terminal identity exactly once" { + const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + if (t.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..t.len], t); + saved_buf[t.len] = 0; + break :blk saved_buf[0..t.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + + // A launcher TERM must be shadowed rather than duplicated, and the rest of + // the environment must arrive untouched. + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); + defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); + + var slots: ChildEnv.Slots = undefined; + // Where the user named no pager: a terminal's shell pages into a + // +Pager pane (`pardes -`); a command pane's through cat. A pager the + // user named is kept. + var shell_slots: ChildEnv.Slots = undefined; + const shell_envp = ChildEnv.build(&shell_slots, .terminal) orelse return error.EnvironmentTooLarge; + var said: usize = 0; + var systemd: usize = 0; + var j: usize = 0; + while (shell_envp[j]) |entry| : (j += 1) { + const line = std.mem.span(entry); + if (std.c.getenv("SYSTEMD_PAGER") == null and std.mem.startsWith(u8, line, "SYSTEMD_PAGER=")) systemd += 1; + if (std.c.getenv("SYSTEMD_PAGERSECURE") == null and std.mem.eql(u8, line, "SYSTEMD_PAGERSECURE=0")) systemd += 1; + if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { + try std.testing.expect(std.mem.endsWith(u8, line, " -")); + said += 1; + } + } + if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, 1), said); + // systemd's pager and its secure mode off, with ours only. + if (std.c.getenv("SYSTEMD_PAGER") == null and std.c.getenv("SYSTEMD_PAGERSECURE") == null) + try std.testing.expectEqual(@as(usize, 2), systemd); + const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; + var terms: usize = 0; + var colorterms: usize = 0; + var probes: usize = 0; + var dumb = false; + var pagers: usize = 0; + var git_pagers: usize = 0; + var pager_cat = false; + var git_pager_cat = false; + var i: usize = 0; + while (envp[i]) |entry| : (i += 1) { + const line = std.mem.span(entry); + if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; + if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; + if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; + if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; + if (std.mem.startsWith(u8, line, "PAGER=")) pagers += 1; + if (std.mem.startsWith(u8, line, "GIT_PAGER=")) git_pagers += 1; + if (std.mem.eql(u8, line, "PAGER=cat")) pager_cat = true; + if (std.mem.eql(u8, line, "GIT_PAGER=cat")) git_pager_cat = true; + } + // A pager only where the user named none: cat, so nothing waits in less. + try std.testing.expectEqual(@as(usize, 1), pagers); + try std.testing.expectEqual(@as(usize, 1), git_pagers); + if (std.c.getenv("PAGER") == null) try std.testing.expect(pager_cat); + if (std.c.getenv("GIT_PAGER") == null) try std.testing.expect(git_pager_cat); + try std.testing.expectEqual(@as(usize, 1), terms); + try std.testing.expectEqual(@as(usize, 1), colorterms); + try std.testing.expectEqual(@as(usize, 1), probes); + try std.testing.expect(!dumb); + // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it + // is a separate entry and never a second TERM. + try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); +} + +test "shell spawn rejects invalid directories before creating a child" { + const rcs: Shell.PromptFiles = .{}; + try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); + const too_long = @as([4096]u8, @splat('x')); + try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file", .data = "not a directory\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; + var path_buf: [4096]u8 = undefined; + const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); + const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); + const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); + try std.testing.expect(missing.len > 256); + try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); +} + +test "a forked shell is told which terminal it is talking to" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + // Whatever launched the test is the wrong answer, so make it a loud one. + const saved = libc.getenv("TERM"); + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + const span = std.mem.span(t); + if (span.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..span.len], span); + saved_buf[span.len] = 0; + break :blk saved_buf[0..span.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + _ = Shell.setenv("TERM", "dumb", 1); + + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + // The echoed command carries the unexpanded `$TERM`, so only the shell's + // own expansion can match this. + try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); + try std.testing.expect(sh.waitText( + "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, + 5_000, + )); +} + +test "shell spawn uses an explicit OS directory longer than 256 bytes" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(std.testing.io, sub_path); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; + try std.testing.expect(directory.len > 256); + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\nPARDES-CWD:'; pwd; exit\n")); + var expected_buf: [4096]u8 = undefined; + const expected = try std.fmt.bufPrint(&expected_buf, "PARDES-CWD:{s}", .{directory}); + try std.testing.expect(sh.waitText(expected, 5_000)); +} + +test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "start/a/b"); + var path_buf: [4096]u8 = undefined; + const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; + var inner_buf: [4096]u8 = undefined; + const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; + const rcs: Shell.PromptFiles = .{}; + var result: [4096]u8 = undefined; + // A wrapper exec'd over the shell (timeout standing in for 9ns) runs + // another, two directories down, in the foreground. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); + try std.testing.expect(sh.waitText("pardes-in-", 5_000)); + // printf runs before the inner shell takes the foreground. + var tries: usize = 0; + while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) + try std.testing.io.sleep(.fromMilliseconds(20), .awake); + try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } + // A job of the shell's own, gone into a/b, leaves the pane where the + // shell is. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); + try std.testing.expect(sh.waitText("pardes-job", 5_000)); + try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } +} + +test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(io, nested); + var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; + try std.testing.expect(directory.len > 1024); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + try std.testing.expect(shellCwd(child.pid, result[0..0]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..1024]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..directory.len]) == null); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, result[0 .. directory.len + 1]) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); +} + +test "a shell whose directory was removed is not named `... (deleted)`" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "gone"); + var path_buf: [4096]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [4096]u8 = undefined; + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try tmp.dir.deleteDir(io, "gone"); + try std.testing.expect(shellCwd(child.pid, &result) == null); +} + +test "the children blob parses to pids, and a garbage token never becomes one" { + var out: [8]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 0), parseChildren("", &out)); + try std.testing.expectEqual(@as(usize, 0), parseChildren(" ", &out)); + try std.testing.expectEqual(@as(usize, 1), parseChildren("991 ", &out)); + try std.testing.expectEqual(@as(libc.pid_t, 991), out[0]); + try std.testing.expectEqual(@as(usize, 3), parseChildren("7 8 9 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 7, 8, 9 }, out[0..3]); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12\n", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("5 -1 +7 0x3 abc 6 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 5, 6 }, out[0..2]); + var two: [2]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 4), parseChildren("1 2 3 4 ", &two)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 1, 2 }, two[0..2]); +} + +test "the process group comes off the last ')', not a comm-shifted stat field" { + const shifted = "1234 (sh (a b)) S 991 992 993 34816 992 4194560 " ++ + "1729 0 0 0 1 0 0 0 20 0 1 0 8244630 9887744 1131"; + try std.testing.expectEqual(@as(libc.pid_t, 992), parseGroupSession(shifted).?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 7), parseGroupSession("42 (bash) S 1 7 7 34816 7 4194304").?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 42), parseGroupSession("42 (sleep) S 7 42 7 0 -1").?.pgrp); + try std.testing.expect(parseGroupSession("") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991 notanumber") == null); + try std.testing.expect(parseGroupSession("no parens here at all") == null); +} + +test "the zombie state comes off its own status line" { + try std.testing.expect(parseZombie("Name:\tsh (a b)\nUmask:\t0022\nState:\tZ (zombie)\nTgid:\t1234\n")); + try std.testing.expect(parseZombie("State:\tZ (zombie)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tR (running)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tT (stopped)\n")); + try std.testing.expect(!parseZombie("Name:\tsh (State: Z)\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nSta")); + try std.testing.expect(!parseZombie("State:\t")); +} + +test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + try std.testing.expect(sh.holdsTaken(false, 200)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); +} + +test "Kill stops the foreground job, never the shell, and finds none with job control off" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + // At the prompt the shell is the foreground: there is nothing to stop. + try std.testing.expect(!killJob(sh.pid, sh.master)); + sleepMs(100); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.forget(); + try std.testing.expect(killJob(sh.pid, sh.master)); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + // Job control off: the job runs in the shell's own group. + sh.forget(); + sh.send("set +m; sleep 30\n"); + sleepMs(300); + try std.testing.expect(!killJob(sh.pid, sh.master)); + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +} + +test "a command pane's child is its shell running the one line, and its exit status is read at the end" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + var got: [256]u8 = undefined; + var n: usize = 0; + while (n < got.len) { + const r = libc.read(child.file.handle, got[n..].ptr, got.len - n); + if (r <= 0) break; // EIO once the child is gone: the pty's end + n += @intCast(r); + } + try std.testing.expect(std.mem.indexOf(u8, got[0..n], "said") != null); + try std.testing.expectEqual(@as(?u8, 7), exitStatus(child.pid, 2000)); +} + +test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const Case = struct { line: []const u8, status: u8 }; + // A job left in the background holds the pty open past the command's + // exit; a command that lets go of its terminal runs on past its end of + // file. Either way the exit is the process's. + for ([_]Case{ + .{ .line = "sleep 3 & exit 4", .status = 4 }, + .{ .line = "exec </dev/null >/dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, + }) |c| { + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", c.line); + while (core.nextEffect()) |_| {} + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + try std.testing.expect(watchExit(child.pid)); + var got: ?libc.pid_t = null; + var waited: i64 = 0; + while (got == null and waited < 5000) : (waited += 10) { + got = takeExited(); + if (got == null) sleepMs(10); + } + try std.testing.expectEqual(@as(?libc.pid_t, child.pid), got); + // Told before it is reaped: the pid is still the child's. + try std.testing.expectEqual(@as(?u8, c.status), reapExited(child.pid).?.status); + try core.removePane(id, null); + } +} + +test "a command's background job outlives it and its pty, and Kill stops its whole line, its & jobs too" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane + if (comptime !tty_probe_platform) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + const Case = struct { line: []const u8, kill: bool, made: bool }; + for ([_]Case{ + // The shell leads the pty's session; its exit hangs up only the + // foreground group, which the job, in a group of its own, is not. + .{ .line = "(sleep 0.4; touch left) & exit 0", .kill = false, .made = true }, + // The job running is in its own group; the shell goes too. + .{ .line = "sleep 0.4; touch killed", .kill = true, .made = false }, + // Kill stops the whole command, its `&` jobs as well. + .{ .line = "(sleep 0.4; touch killed) & sleep 5", .kill = true, .made = false }, + }) |c| { + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, dir, c.line); + while (core.nextEffect()) |_| {} + const child = try forkShell(core, id, &rcs, "/bin/sh", dir, 24, 80); + if (c.kill) { + sleepMs(150); + signalTty(child.pid, child.file.handle, .term, true); + } + _ = exitStatus(child.pid, 2000); + _ = libc.close(child.file.handle); // the pane closes: the pty hangs up + sleepMs(800); + const name = if (c.kill) "killed" else "left"; + const made = if (tmp.dir.statFile(std.testing.io, name, .{})) |_| true else |_| false; + try std.testing.expectEqual(c.made, made); + try core.removePane(id, null); + } +} + +test "a retired shell that ignores the hangup is killed and reaped, not left a zombie" { + const pid = libc.fork(); + if (pid == 0) { + const argv = [_:null]?[*:0]const u8{ "/bin/sh", "-c", "trap '' HUP; exec sleep 30" }; + const envp = [_:null]?[*:0]const u8{}; + _ = libc.execve("/bin/sh", &argv, &envp); + libc._exit(127); + } + try std.testing.expect(pid > 0); + sleepMs(100); // past the trap + retireShell(pid); + // A zombie still answers kill(pid, 0); only a reaped pid is gone. + var waited: i64 = 0; + while (libc.kill(pid, @fromBackingInt(@intCast(0))) == 0 and waited < 2000) : (waited += 10) sleepMs(10); + try std.testing.expect(libc.kill(pid, @fromBackingInt(@intCast(0))) != 0); + try std.testing.expect(waited >= 90); // it did ignore the hangup +} + +test "a background job is not the tty's owner" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + sh.send("sleep 30 &\n"); + try std.testing.expect(sh.waitText("[1]", 10_000)); + try std.testing.expect(sh.holdsTaken(false, 300)); + + sh.send("kill %1\n"); + try std.testing.expect(sh.holdsTaken(false, 300)); +} + +test "a nested interactive shell is still a prompt" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + sh.forget(); + sh.send("bash --norc -i\n"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expect(sh.holdsTaken(false, 300)); + + sh.forget(); + sh.send("bash --norc -i\n"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expect(sh.holdsTaken(false, 300)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); +} + +test "the walk reaches the leaf: bash -c 'sleep 30' takes the tty" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + sh.send("bash --norc -c 'sleep 30'\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); + + sh.send("bash --norc -c 'sleep 30; :'\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + + // Why the shallow answer is the wrong one, in each walk's own evidence: + // the wrapper between the shell and `sleep` wears the shell's executable, + // so a probe that stopped at it would report a prompt. + if (comptime builtin.os.tag == .linux) { + var probe: TtyProbe = undefined; + var pending: usize = 0; + try std.testing.expectEqual(Pushed.pushed, pushChildren(&probe, &pending, sh.pid, 1)); + try std.testing.expectEqual(@as(usize, 1), pending); + var wrapper_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var shell_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + try std.testing.expectEqualStrings( + processExe(sh.pid, &shell_buf).?, + processExe(probe.pending[0].pid, &wrapper_buf).?, + ); + } else { + const fg = tcgetpgrp(sh.master); + try std.testing.expect(fg > 0 and fg != sh.pid); + var leader_buf: [darwin.path_max]u8 = undefined; + var shell_buf: [darwin.path_max]u8 = undefined; + // The group's leader IS that wrapper, and it is the shell's binary. + try std.testing.expectEqualStrings( + darwin.exe(sh.pid, &shell_buf).?, + darwin.exe(fg, &leader_buf).?, + ); + // Taken all the same, because the rest of the group is not. + try std.testing.expect(darwin.taken(sh.pid, fg)); + } + + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); +} + +test "a full-screen program takes the tty until it quits" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + const cases = [_]struct { bin: [*:0]const u8, run: []const u8, quit: []const u8 }{ + .{ .bin = "/usr/bin/vim", .run = "vim -u NONE -i NONE\n", .quit = "\x1b:q!\r" }, + .{ .bin = "/usr/bin/less", .run = "env LESS= less /etc/hosts\n", .quit = "q" }, + }; + var ran: usize = 0; + for (cases) |c| { + if (!haveFile(c.bin)) continue; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + sh.send(c.run); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.forget(); + sh.send(c.quit); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + ran += 1; + } + if (ran == 0) return error.SkipZigTest; +} + +test "completion survives a full output queue" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 7 }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ + .pane = 0, + .gen = 1, + .bytes = try gpa.dupe(u8, "output"), + } }); + for (0..selection_pipe.Tasks.capacity) |id| queue.push(.{ .pipe = .{ + .id = @intCast(id), + .success = false, + .outputs = &.{}, + .failure = .{ .stderr = try gpa.dupe(u8, "pipe failure") }, + } }); + queue.push(.{ .lsp = .{ .id = 7, .rows = try gpa.dupe(u8, "completion") } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(Inbox.output_capacity + selection_pipe.Tasks.capacity + 1, batch.len); + for (batch.items[0..Inbox.output_capacity]) |msg| { + try std.testing.expect(msg == .output); + try std.testing.expectEqualStrings("output", msg.output.bytes); + } + for (batch.items[Inbox.output_capacity..][0..selection_pipe.Tasks.capacity], 0..) |msg, id| { + try std.testing.expect(msg == .pipe); + try std.testing.expectEqual(@as(u32, @intCast(id)), msg.pipe.id); + } + var found = false; + for (batch.slice()) |msg| if (msg == .lsp) { + try std.testing.expectEqual(@as(u32, 7), msg.lsp.id); + try std.testing.expectEqualStrings("completion", msg.lsp.rows.?); + found = true; + }; + try std.testing.expect(found); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); +} + +test "PTY backpressure retains byte order and tail before EOF" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); + const tail = try gpa.dupe(u8, "tail"); + var thread: ?std.Thread = std.Thread.spawn(.{}, PtyTests.tail, .{ &queue, tail }) catch |err| { + gpa.free(tail); + return err; + }; + defer { + queue.cancelReader(0, 1); + if (thread) |owned| owned.join(); + } + try PtyTests.waitBlocked(&queue); + queue.push(.files_changed); + queue.push(.files_changed); + var first = queue.take(); + defer for (first.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(Inbox.output_capacity + 1, first.len); + for (first.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); + try std.testing.expect(first.items[Inbox.output_capacity] == .files_changed); + thread.?.join(); + thread = null; + var last = queue.take(); + defer for (last.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 2), last.len); + try std.testing.expectEqualStrings("tail", last.items[0].output.bytes); + try std.testing.expect(last.items[1] == .eof); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); +} + +test "PTY backpressure cancellation and close release owned producers" { + const gpa = std.testing.allocator; + for ([_]bool{ false, true }) |close| { + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); + const tail = try gpa.dupe(u8, "cancelled"); + const thread = std.Thread.spawn(.{}, PtyTests.tail, .{ &queue, tail }) catch |err| { + gpa.free(tail); + return err; + }; + defer { + queue.cancelReader(0, 1); + thread.join(); + } + try PtyTests.waitBlocked(&queue); + if (close) queue.close() else queue.cancelReader(0, 1); + if (!close) { + queue.acceptReader(0, 2); + queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + try std.testing.expect(queue.pushOutput(0, 2, try gpa.dupe(u8, "replacement"))); + queue.push(.{ .eof = .{ .pane = 0, .gen = 2 } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 2), batch.len); + try std.testing.expectEqualStrings("replacement", batch.items[0].output.bytes); + try std.testing.expectEqual(@as(u32, 2), batch.items[1].eof.gen); + } else try std.testing.expectEqual(@as(usize, 0), queue.take().len); + } +} + +test "PTY EOF reserve cannot evict terminal output" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + for (0..pardes.MAX_PANES) |pane| queue.acceptReader(@intCast(pane), 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); + for (0..pardes.MAX_PANES) |pane| queue.push(.{ .eof = .{ .pane = @intCast(pane), .gen = 1 } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(Inbox.capacity, batch.len); + for (batch.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); + for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane); +} + +test "completions retain their arrival order across LSP and pipes" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 }; + defer queue.deinit(); + queue.push(.{ .pipe = .{ .id = 1, .success = true, .outputs = &.{} } }); + queue.push(.{ .lsp = .{ .id = 2, .rows = try gpa.dupe(u8, "second") } }); + queue.push(.{ .pipe = .{ .id = 3, .success = false, .outputs = &.{} } }); + queue.push(.{ .lsp = .{ .id = 1, .rows = try gpa.dupe(u8, "late") } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 3), batch.len); + try std.testing.expectEqual(@as(u32, 1), batch.items[0].pipe.id); + try std.testing.expectEqual(@as(u32, 2), batch.items[1].lsp.id); + try std.testing.expectEqual(@as(u32, 3), batch.items[2].pipe.id); +} + +test "completion reset frees queued payloads and rejects late LSP workers" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 9 }; + defer queue.deinit(); + queue.acceptReader(0, 1); + queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "retained") } }); + queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "current") } }); + queue.push(.{ .lsp = .{ .id = 8, .rows = try gpa.dupe(u8, "late old request") } }); + try std.testing.expectEqualStrings("current", queue.completions[0].lsp.rows.?); + for (0..selection_pipe.Tasks.capacity) |id| { + const outputs = try gpa.alloc([]u8, 1); + outputs[0] = try gpa.dupe(u8, "cancelled result"); + queue.push(.{ .pipe = .{ .id = @intCast(id), .success = true, .outputs = outputs } }); + } + queue.discardCompletions(); + queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "late before Restore") } }); + try std.testing.expectEqual(@as(usize, 0), queue.completion_len); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqualStrings("retained", batch.items[0].output.bytes); + + queue.lsp_id = 10; + queue.push(.{ .lsp = .{ .id = 10, .rows = null } }); + queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "late after Restore") } }); + var next = queue.take(); + defer for (next.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), next.len); + try std.testing.expectEqual(@as(u32, 10), next.items[0].lsp.id); + try std.testing.expect(next.items[0].lsp.rows == null); + + queue.push(.{ .lsp = .{ .id = 10, .rows = try gpa.dupe(u8, "closing result") } }); + queue.push(.{ .pipe = .{ + .id = 17, + .success = false, + .outputs = &.{}, + .failure = .{ .stderr = try gpa.dupe(u8, "closing failure") }, + } }); + queue.close(); + queue.push(.{ .lsp = .{ .id = 10, .rows = try gpa.dupe(u8, "late closed result") } }); + queue.push(.{ .pipe = .{ + .id = 18, + .success = false, + .outputs = &.{}, + .failure = .{ .stderr = try gpa.dupe(u8, "late closed failure") }, + } }); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); +} + +test "LSP query answers, and a newer one cancels it" { + const gpa = std.testing.allocator; + const io = std.testing.io; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + _ = try core.setTestFile("abc"); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + for (0..2) |_| { + core.lspRequest(core.view().active, .status, ""); + queue.startLsp(core, .{ .id = core.lsp_ask.wait.?.id, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); + } + const last = core.lsp_ask.wait.?.id; + queue.lsp_task.?.future.await(io); + queue.lsp_task = null; + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqual(last, batch.items[0].lsp.id); + try std.testing.expect(batch.items[0].lsp.rows != null); + core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); + try std.testing.expect(core.lsp_ask.wait == null); +} + +test "a plumbing rule's program starts detached, or says why not: a program not found, a directory not there" { + if (comptime builtin.os.tag != .linux) return; + var why: [64]u8 = undefined; + try std.testing.expect(startDetached(null, "/\x00true\x00", &why) == null); + try std.testing.expectEqualStrings("not found", startDetached(null, "/\x00no-such-program-x\x00", &why).?); + try std.testing.expectEqualStrings("its directory: no such directory", startDetached(null, "/no/such/dir\x00true\x00", &why).?); + try std.testing.expectEqualStrings("malformed", startDetached(null, "/\x00true", &why).?); +} |
