diff options
Diffstat (limited to 'dev/Ptys.zig')
| -rw-r--r-- | dev/Ptys.zig | 397 |
1 files changed, 397 insertions, 0 deletions
diff --git a/dev/Ptys.zig b/dev/Ptys.zig new file mode 100644 index 00000000..97c5cfde --- /dev/null +++ b/dev/Ptys.zig @@ -0,0 +1,397 @@ +//! A session's ptys: each terminal pane's shell (forked here, or adopted +//! from a session that died), its master and pid, and the reader that +//! posts what it says to the session's queue (Inbox). One table a session, +//! the session loop's (runtime/session.zig): the Host's pty calls are +//! answered here whatever the frontend (`Calls`), and a frontend draining +//! the queue hands the readers' posts back (`output`, `eof`). +const std = @import("std"); +const posix = std.posix; +const libc = std.c; +const pardes = @import("core"); +const daemon = @import("runtime").daemon; +const upgrade = @import("runtime").upgrade; +const host_io = @import("host_io.zig"); +const Inbox = host_io.Inbox; +const Ptys = @This(); + +const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); + +pub const Pty = struct { + fd: c_int, + pid: libc.pid_t, + /// Its reader, blocked in an Io read: `close` cancels it. + reader: ?std.Io.Future(void) = null, + /// A command pane's child, watched to its exit (host_io.watchExit); + /// the pty stays open until both its end of file and its exit. + cmd: host_io.CommandWatch = .{}, +}; + +slots: [pardes.MAX_PANES]?Pty = @splat(null), +/// Each slot's generation: a post of an older one is passed over. +gens: [pardes.MAX_PANES]u32 = @splat(0), +queue: *Inbox, +prompt_rcs: *const host_io.Shell.PromptFiles, +/// Shells a dead session left (Adopt), each waiting for the spawn of the +/// terminal pane made for it. +adoptions: host_io.Adoptions = .{}, +/// Readers run from the loop's start on (`start`): a shell spawned in the +/// first effects is read from then. +reading: bool = false, + +/// The Host's pty calls, for a host whose `ctx` is a `*Ctx` with the +/// fields `ptys: *Ptys` and `core: *Pardes`. +pub fn Calls(comptime Ctx: type) type { + return struct { + fn of(ctx: ?*anyopaque) *Ctx { + return @ptrCast(@alignCast(ctx.?)); + } + pub fn spawn(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void { + const s = of(ctx); + s.ptys.spawn(s.core, id, cwd); + } + pub fn write(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { + of(ctx).ptys.write(id, bytes); + } + pub fn resize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void { + const s = of(ctx); + s.ptys.resize(s.core, id, cols, rows); + } + pub fn signal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void { + of(ctx).ptys.signal(id, sig); + } + pub fn close(ctx: ?*anyopaque, id: pardes.Pane.Id) void { + of(ctx).ptys.close(id); + } + pub fn ttyTaken(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { + const pt = of(ctx).ptys.slots[id.index()] orelse return false; + return host_io.ttyTaken(pt.pid, pt.fd); + } + pub fn fgName(ctx: ?*anyopaque, id: pardes.Pane.Id, buf: []u8) ?[]const u8 { + const pt = of(ctx).ptys.slots[id.index()] orelse return null; + return host_io.foregroundName(pt.pid, pt.fd, buf); + } + pub fn killJob(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { + const pt = of(ctx).ptys.slots[id.index()] orelse return false; + return host_io.killJob(pt.pid, pt.fd); + } + pub fn adopt(ctx: ?*anyopaque, id: pardes.Pane.Id) void { + const s = of(ctx); + s.ptys.adoptions.ask(s.core, id.index()); + } + }; +} + +/// Pane `id`'s shell, in `cwd` (empty: where its pane's directory says), +/// or the adopted one waiting for it. +pub fn spawn(p: *Ptys, core: *pardes.Pardes, id: pardes.Pane.Id, cwd: []const u8) void { + const pane = id.index(); + if (p.adoptions.take(id)) |a| return p.take(core, pane, a); + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = p.slots[pane] != null; + const child = host_io.forkShell(core, pane, p.prompt_rcs, core.shellBin(), cwd, core.view().screen_h, core.view().screen_w) catch |err| { + if (running) return core.restartFailed(id, err); + return core.shellFailed(id, err); + }; + p.close(id); + p.gens[pane] +%= 1; + const command = if (core.panes[pane]) |pn| pn.command != null else false; + p.slots[pane] = .{ .fd = child.file.handle, .pid = child.pid, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and the frame's poll + // (`pollCwds`) says where it went from there. + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(id, wd); + p.read(core, pane); +} + +/// An adopted shell, running already, as pane `pane`'s: told the size +/// twice (a size it never had, then the pane's), which makes it redraw. +fn take(p: *Ptys, core: *pardes.Pardes, pane: u8, a: host_io.Adoption) void { + p.close(.at(pane)); + p.gens[pane] +%= 1; + p.slots[pane] = .{ .fd = a.fd, .pid = a.pid }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + core.acknowledgeShell(.at(pane), host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| core.setCwd(.at(pane), wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (core.panes[pane]) |pn| p.resize(core, .at(pane), @max(pn.cols, 1), @max(pn.rows, 1)); + p.read(core, pane); +} + +/// Pane `pane`'s reader, once readers run: the place of one stopped for +/// an Upgrade let go first. One that cannot start closes the pty and says +/// why in the pane. +fn read(p: *Ptys, core: *pardes.Pardes, pane: u8) void { + if (!p.reading) return; + const pt = &(p.slots[pane] orelse return); + p.queue.cancelReader(.at(pane), p.gens[pane]); + pt.reader = p.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, .at(pane), p.gens[pane]) catch |err| { + p.close(.at(pane)); + return core.reportError(.at(pane), "terminal reader", err); + }; +} + +/// The loop's start: every shell read from now on. +pub fn start(p: *Ptys, core: *pardes.Pardes) void { + p.reading = true; + for (0..p.slots.len) |pane| p.read(core, @intCast(pane)); +} + +pub fn write(p: *Ptys, id: pardes.Pane.Id, bytes: []const u8) void { + if (p.slots[id.index()]) |pt| _ = host_io.writeFd(pt.fd, bytes); +} + +pub fn resize(p: *Ptys, core: *const pardes.Pardes, id: pardes.Pane.Id, cols: u16, rows: u16) void { + const pt = p.slots[id.index()] orelse return; + const ws = host_io.ptyWinsize(core, cols, rows); + _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws)); +} + +pub fn signal(p: *Ptys, id: pardes.Pane.Id, sig: pardes.PtySignal) void { + // A command whose exit is recorded is reaped: its group may be + // another's by now. + if (p.slots[id.index()]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); +} + +/// The pane is gone, or its shell is: its reader out of the queue first +/// (which lets go one waiting for room there) and canceled; its pty hung +/// up, which the kernel passes on to the shell as SIGHUP; the daemon's +/// copy let go; the shell retired. +pub fn close(p: *Ptys, id: pardes.Pane.Id) void { + const pane = id.index(); + var pt = p.slots[pane] orelse return; + p.slots[pane] = null; + p.queue.cancelReader(id, p.gens[pane]); + if (pt.reader) |*r| r.cancel(p.queue.io); + _ = libc.close(pt.fd); + daemon.closed(pt.pid); + host_io.retireShell(pt.pid); +} + +/// A reader's read, off the queue (freed here). +pub fn output(p: *Ptys, core: *pardes.Pardes, o: @FieldType(Inbox.Msg, "output")) void { + defer p.queue.gpa.free(o.bytes); + if (p.gens[o.pane.index()] == o.gen) core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); +} + +/// A reader's end, off the queue: its pty's end of file, or a read that +/// failed. +pub fn eof(p: *Ptys, core: *pardes.Pardes, e: @FieldType(Inbox.Msg, "eof")) void { + const pane = e.pane.index(); + if (p.gens[pane] != e.gen) return; + if (e.failure) |err| { + p.close(e.pane); + return core.readerFailed(e.pane, err); + } + const pt = &(p.slots[pane] orelse return core.update(.{ .eof = .{ .pane = e.pane } })); + // A command's pty stays open until its child has exited: closing it + // would hang up one that runs on without it. Its exit, if it came + // first, is told now its output is in. + if (pt.cmd.watched) return host_io.commandEof(core, &p.slots, pane, p, closeWatched); + // Unwatched, a command's exit is read here, as its end, and a + // shell's, for a run waiting on it and the log. + const command = if (core.panes[pane]) |pn| pn.command != null else false; + const status = host_io.exitStatus(pt.pid, 100); + if (status != null) pt.pid = 0; // reaped: no shell to retire + p.close(e.pane); + if (command or status != null) core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); + core.update(.{ .eof = .{ .pane = e.pane } }); +} + +/// The command panes' exits, told once their output is in (host_io): +/// after an exit's wake and after each batch of output. +pub fn takeExits(p: *Ptys, core: *pardes.Pardes) void { + host_io.takeExits(core, &p.slots, p, closeWatched); +} + +fn closeWatched(p: *Ptys, id: usize) void { + p.close(.at(id)); +} + +/// Where each shell is now: its pane's directory (a frame's poll). +pub fn pollCwds(p: *Ptys, core: *pardes.Pardes) void { + for (p.slots, 0..) |slot, id| if (slot) |pt| { + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.ttyCwd(pt.pid, pt.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(.at(id), cwd); + }; +} + +/// An Upgrade's: the readers stopped, the ptys left open. What a reader +/// posted before its cancel is in the queue still, the frontend's to +/// take; one waiting for room has it once the queue is drained. +pub fn pause(p: *Ptys) void { + for (&p.slots) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| { + r.cancel(p.queue.io); + pt.reader = null; + }; +} + +/// After an Upgrade that did not happen: read on. +pub fn readOn(p: *Ptys, core: *pardes.Pardes) void { + for (p.slots, 0..) |slot, pane| if (slot) |pt| if (pt.reader == null) p.read(core, @intCast(pane)); +} + +/// The ptys an Upgrade hands to the next build. +pub fn record(p: *const Ptys, rec: *upgrade.Record) void { + for (p.slots, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.fd); +} + +/// An upgraded session's shells, running on: each its pane's pty again, +/// or, when its dump would not load (`fresh`), adopted as new panes. +pub fn resumeFrom(p: *Ptys, core: *pardes.Pardes, rec: *const upgrade.Record) void { + for (rec.ptys[0..rec.nptys]) |k| { + const pane = if (rec.fresh) null else core.panes[k.pane]; + if (pane == null or !pane.?.isTerminal()) { + p.adoptions.adoptShell(core, k.pid, k.fd); + continue; + } + p.slots[k.pane] = .{ .fd = k.fd, .pid = k.pid, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; + } +} + +/// Every pty closed and every generation moved on: a Restore's (the new +/// core's panes start shells of their own) and the session's end. +pub fn stop(p: *Ptys) void { + for (0..p.slots.len) |pane| p.close(.at(pane)); + for (&p.gens) |*gen| gen.* +%= 1; +} + +/// The session's end: every shell hung up and seen out (waitRetired), the +/// adopted ones no pane took let go. +pub fn deinit(p: *Ptys) void { + p.stop(); + for (p.adoptions.list[0..p.adoptions.len]) |a| _ = libc.close(a.fd); + p.adoptions.len = 0; + host_io.waitRetired(); +} + +/// A table over `queue` with shells of its own, readers running: the +/// tests' (each slot's generation 1). +fn testing(queue: *Inbox) Ptys { + const none = struct { + const rcs: host_io.Shell.PromptFiles = .{}; + }; + return .{ .queue = queue, .prompt_rcs = &none.rcs, .gens = @splat(1), .reading = true }; +} + +fn testShell(p: *Ptys, pane: u8) !libc.pid_t { + const child = try host_io.forkShell(null, pane, p.prompt_rcs, "/bin/sh", "", 24, 80); + p.slots[pane] = .{ .fd = child.file.handle, .pid = child.pid }; + p.slots[pane].?.reader = try p.queue.startReader(.{ .handle = child.file.handle, .flags = .{ .nonblocking = false } }, .at(pane), p.gens[pane]); + return child.pid; +} + +test "a reader delivers a real shell's tail before its end of file, and closing joins it" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var p = testing(&queue); + defer p.deinit(); + _ = try p.testShell(0); + const fd = p.slots[0].?.fd; + try std.testing.expect(host_io.writeFd(fd, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); + var bytes: std.ArrayList(u8) = .empty; + defer bytes.deinit(gpa); + var ended = false; + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (!ended and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + for (batch.slice()) |msg| switch (msg) { + .output => |o| { + try std.testing.expect(!ended); + try bytes.appendSlice(gpa, o.bytes); + }, + .eof => |e| { + try std.testing.expect(e.failure == null); + ended = true; + }, + else => return error.UnexpectedMessage, + }; + if (!ended) try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expect(ended); + try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); + p.close(.at(0)); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expect(p.slots[0] == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD)); +} + +test "a Restore's stop joins a real reader waiting for room in the queue" { + const gpa = std.testing.allocator; + var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + try pardes.dump.dumpState(core); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(.at(1), 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(1), .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); + var p = testing(&queue); + defer p.deinit(); + _ = try p.testShell(0); + const fd = p.slots[0].?.fd; + try std.testing.expect(host_io.writeFd(fd, "printf 'after-full'; exit\n")); + try host_io.PtyTests.waitBlocked(&queue); + const old_serial = core.panes[0].?.serial; + const replacement = try pardes.dump.restore(core, core.dump_out.?, "test"); + p.stop(); + core.deinit(); + core = replacement; + // The dump's pane, its serial too; its old shell stopped all the same. + try std.testing.expectEqual(old_serial, core.panes[0].?.serial); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD)); + queue.cancelReader(.at(1), 1); + queue.acceptReader(.at(0), p.gens[0]); + queue.push(.{ .eof = .{ .pane = .at(0), .gen = 1 } }); + try std.testing.expect(queue.pushOutput(.at(0), p.gens[0], try gpa.dupe(u8, "fresh"))); + 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("fresh", batch.items[0].output.bytes); +} + +test "a pane's removal closes its pty, joins its idle reader, and its shell is reaped by the end" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var p = testing(&queue); + defer p.deinit(); + while (core.nextEffect()) |_| {} + const pid = try p.testShell(0); + const fd = p.slots[0].?.fd; + try core.removePane(0, null); + // The core asks it closed (panes.retirePane): no pane outlives its pty. + while (core.nextEffect()) |e| if (e == .close_pty) p.close(e.close_pty.pane); + try std.testing.expect(p.slots[0] == null); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD)); + p.deinit(); + try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(pid, null, libc.W.NOHANG)); + try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); +} + +test "a post of an older generation is passed over" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer core.deinit(); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var p: Ptys = .{ .queue = &queue, .prompt_rcs = undefined }; + p.gens[0] = 2; + p.output(core, .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") }); + p.output(core, .{ .pane = .at(0), .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") }); + const text = try pardes.Term.scrollback(core.panes[0].?.terminal, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); + try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); +} |
