diff options
Diffstat (limited to 'test/process.zig')
| -rw-r--r-- | test/process.zig | 444 |
1 files changed, 444 insertions, 0 deletions
diff --git a/test/process.zig b/test/process.zig index f797c063..3d74c72b 100644 --- a/test/process.zig +++ b/test/process.zig @@ -182,6 +182,128 @@ pub const Conn = struct { } return names.toOwnedSlice(gpa); } + + // fsb: + + /// `dial`, versioned at `size` (a client of small frames, at least + /// 217, cloud9's least). + pub fn dialSized(gpa: std.mem.Allocator, path: []const u8, size: u32) !*Conn { + var addr: libc.sockaddr.un = .{ .path = undefined }; + if (path.len >= addr.path.len) return error.NameTooLong; + @memset(&addr.path, 0); + @memcpy(addr.path[0..path.len], path); + return connectTo(gpa, libc.AF.UNIX, @ptrCast(&addr), @sizeOf(libc.sockaddr.un), size); + } + + /// A connection over TCP to `host` (numeric, v4 or v6) at `port`. + pub fn dialTcp(gpa: std.mem.Allocator, host: [:0]const u8, port: u16) !*Conn { + if (std.mem.indexOfScalar(u8, host, ':') != null) { + var addr: libc.sockaddr.in6 = .{ .port = std.mem.nativeToBig(u16, port), .flowinfo = 0, .addr = undefined, .scope_id = 0 }; + if (inet_pton(libc.AF.INET6, host, &addr.addr) != 1) return error.BadHost; + return connectTo(gpa, libc.AF.INET6, @ptrCast(&addr), @sizeOf(libc.sockaddr.in6), msize); + } + var addr: libc.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, port), .addr = undefined }; + if (inet_pton(libc.AF.INET, host, &addr.addr) != 1) return error.BadHost; + return connectTo(gpa, libc.AF.INET, @ptrCast(&addr), @sizeOf(libc.sockaddr.in), msize); + } + + fn connectTo(gpa: std.mem.Allocator, family: c_uint, addr: *const libc.sockaddr, len: libc.socklen_t, size: u32) !*Conn { + const c = try gpa.create(Conn); + errdefer gpa.destroy(c); + c.* = .{ .fd = -1, .cl = undefined }; + c.cl = c9.Client.init(.{ .in = &c.in, .out = &c.out }); + c.fd = libc.socket(family, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0); + if (c.fd < 0) return error.NoSocket; + errdefer _ = libc.close(c.fd); + if (libc.connect(c.fd, addr, len) != 0) return error.ConnectFailed; + _ = try c.call(.{ .version = .{ .msize = size } }); + _ = try c.call(.{ .attach = .{ .fid = 0, .uname = "test" } }); + return c; + } + + /// The frame size the server agreed to. + pub fn msizeAgreed(c: *const Conn) u32 { + return c.cl.msize; + } + + /// `data` written to `path` truncated first (`>`), in as many writes + /// as it takes. + pub fn replace(c: *Conn, path: []const u8, data: []const u8) !void { + const fid = try c.hold(path, 1 | 16); + var off: usize = 0; + while (off < data.len) { + const n = c.writeFid(fid, off, data[off..@min(data.len, off + c.cl.maxWrite())]) catch |err| { + c.clunk(fid); + return err; + }; + off += n; + } + _ = try c.call(.{ .clunk = .{ .fid = fid } }); + } + + /// A new pane, made by opening /pane/new; its serial. + pub fn newPane(c: *Conn, gpa: std.mem.Allocator) !u32 { + const got = try c.read(gpa, "/pane/new"); + defer gpa.free(got); + return std.fmt.parseInt(u32, std.mem.trim(u8, got, "\n"), 10); + } + + /// The serials /index lists, in its order. + pub fn serials(c: *Conn, gpa: std.mem.Allocator) ![]u32 { + const index = try c.read(gpa, "/index"); + defer gpa.free(index); + var out: std.ArrayList(u32) = .empty; + var rows = std.mem.tokenizeScalar(u8, index, '\n'); + while (rows.next()) |row| try out.append(gpa, try std.fmt.parseInt(u32, row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len], 10)); + return out.toOwnedSlice(gpa); + } + + /// A Look at `path` from pane `source`, or from a scratch pane removed + /// after; the one pane it answers (test/fs.py's look). + pub fn look(c: *Conn, gpa: std.mem.Allocator, path: []const u8, source: ?u32) !u32 { + const from = source orelse try c.newPane(gpa); + var buf: [64]u8 = undefined; + const line = try std.fmt.allocPrint(gpa, "{s}\n", .{path}); + defer gpa.free(line); + try c.write(try std.fmt.bufPrint(&buf, "/pane/{d}/look", .{from}), line); + const got = try c.read(gpa, "/look"); + defer gpa.free(got); + const answer = std.mem.trim(u8, got, "\n"); + const opened = std.fmt.parseInt(u32, answer, 10) catch { + std.debug.print("look {s}: answered {s}\n", .{ path, got }); + return error.NotOneLook; + }; + if (opened == from) return error.NotOneLook; + // A column holds only so many panes, each its tag and two rows. + if (source == null) try c.remove(try std.fmt.bufPrint(&buf, "/pane/{d}", .{from})); + return opened; + } + + /// Pane `n`'s `file` read whole. + pub fn pane(c: *Conn, gpa: std.mem.Allocator, n: u32, file: []const u8) ![]u8 { + var buf: [64]u8 = undefined; + return c.read(gpa, try std.fmt.bufPrint(&buf, "/pane/{d}/{s}", .{ n, file })); + } + + /// A line written to pane `n`'s exec, a middle click on it. + pub fn exec(c: *Conn, n: u32, line: []const u8) !void { + var buf: [64]u8 = undefined; + try c.write(try std.fmt.bufPrint(&buf, "/pane/{d}/exec", .{n}), line); + } + + /// An exec that fails: refused, its words holding `words`. + pub fn execRefused(c: *Conn, n: u32, line: []const u8, words: []const u8) !void { + if (c.exec(n, line)) |_| { + std.debug.print("{s}: taken\n", .{line}); + return error.Taken; + } else |err| if (err != error.Refused) return err; + try check(has(c.said, words), "{s}: refused {s}", .{ line, c.said }); + } + + pub fn removePane(c: *Conn, n: u32) !void { + var buf: [64]u8 = undefined; + try c.remove(try std.fmt.bufPrint(&buf, "/pane/{d}", .{n})); + } }; /// A running pardes's file tree, dialled by its pid or socket path. @@ -276,6 +398,18 @@ pub const Files = struct { pub fn at(f: *Files, comptime fmt: []const u8, args: anytype) []const u8 { return std.fmt.allocPrint(f.arena.allocator(), fmt, args) catch @panic("out of memory"); } + + // fsb: + + /// The ink /screen draws at a cell, as its JSON (`{"rgb":[1,2,3]}`). + pub fn fg(f: *Files, col: usize, row: usize) ![]const u8 { + const a = f.arena.allocator(); + const json = try std.json.parseFromSliceLeaky(std.json.Value, a, try f.read("/screen"), .{}); + const cols: usize = @intCast(json.object.get("cols").?.integer); + const cell = json.object.get("cells").?.array.items[row * cols + col]; + const style = json.object.get("styles").?.array.items[@intCast(cell.array.items[1].integer)]; + return std.json.Stringify.valueAlloc(a, style.object.get("fg").?, .{}); + } }; /// The files of the app a pty harness started. @@ -476,9 +610,319 @@ pub const Detached = struct { } d.pid = 0; } + + // fsb: + + /// Whether `rel` under the root is there (a dangling link is not). + pub fn exists(d: *const Detached, rel: []const u8) bool { + var buf: [4096]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d.root(), rel }, 0) catch return false; + return libc.access(path, 0) == 0; + } + + /// `rel` under the root, absolute, kept until deinit. + pub fn abs(d: *Detached, rel: []const u8) [:0]const u8 { + return std.fmt.allocPrintSentinel(d.files.arena.allocator(), "{s}/{s}", .{ d.root(), rel }, 0) catch @panic("out of memory"); + } + + /// Another session in this root, in a pty, as fs.py's tty sessions: + /// `pardes --tty --9p=<name> <args> <root>/<name>.txt` (holding + /// "initial\n"), back once its socket (`abs("pardes-9p-<name>.sock")`) + /// is there. + pub fn startTty(d: *Detached, exe: [:0]const u8, name: []const u8, args: []const [:0]const u8) !Child { + const a = d.files.arena.allocator(); + try d.put(try std.fmt.allocPrint(a, "{s}.txt", .{name}), "initial\n"); + var argv: std.ArrayList([:0]const u8) = .empty; + try argv.appendSlice(a, &.{ exe, "--tty", try std.fmt.allocPrintSentinel(a, "--9p={s}", .{name}, 0) }); + try argv.appendSlice(a, args); + try argv.append(a, d.abs(try std.fmt.allocPrint(a, "{s}.txt", .{name}))); + const env = try a.dupe([2][:0]const u8, &.{.{ "PARDES_DUMP", d.abs(try std.fmt.allocPrint(a, "{s}.dump.zon", .{name})) }}); + var c = try Child.spawn(argv.items, .{ .root = d.root(), .env = env, .pty = .{ .log = d.abs(try std.fmt.allocPrint(a, "{s}.pty", .{name})) } }); + errdefer c.deinit(); + try c.waitPath(d.abs(try std.fmt.allocPrint(a, "pardes-9p-{s}.sock", .{name})), 10_000); + return c; + } }; fn sleepMs(ms: u32) void { var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } + +// fsb: + +extern "c" fn readdir(dir: *libc.DIR) ?*libc.dirent; +extern "c" fn ioctl(fd: c_int, request: c_ulong, ...) c_int; +extern "c" fn openpty(master: *c_int, slave: *c_int, name: ?[*]u8, termp: ?*const anyopaque, winp: ?*const std.posix.winsize) c_int; +extern "c" fn signal(sig: c_int, handler: usize) usize; +extern "c" var environ: [*:null]?[*:0]u8; +extern "c" fn inet_pton(family: c_uint, src: [*:0]const u8, dst: *anyopaque) c_int; +extern "c" fn pipe2(fds: *[2]c_int, flags: c_int) c_int; +// shortcut: Linux's O_CLOEXEC, TIOCSCTTY and TCGETS, the only host these +// run on; take them from std for another. +const o_cloexec: c_int = 0o2000000; + +/// A program run as a shell in `root` would run it: the caller's +/// environment without a session's (PARDES_*, a PAGER), HOME and the +/// runtime and config directories the root, no daemon (PARDES_DAEMON=off: +/// the process is the session) and no language servers, unless `env` says +/// otherwise. Its stderr is kept (`said`). +pub const Child = struct { + pid: libc.pid_t, + err_fd: c_int, + status: ?c_int = null, + /// A pty's ends, when on one, and the process copying its output to + /// `Pty.log`. + master: c_int = -1, + slave: c_int = -1, + drain: libc.pid_t = 0, + + pub const Pty = struct { + /// Where everything the program draws goes. + log: [:0]const u8, + /// Made its controlling terminal; else a pty that is no one's. + ctty: bool = true, + }; + + pub const Options = struct { + /// HOME and the runtime and config directories; null: the caller's. + root: ?[]const u8 = null, + /// Where it runs; null: `root`, or here. + cwd: ?[]const u8 = null, + /// Set after the root's. + env: []const [2][:0]const u8 = &.{}, + /// Unset after that. + unset: []const [:0]const u8 = &.{}, + /// Its stdin, written whole and closed; null: /dev/null. + stdin: ?[]const u8 = null, + /// Started in a 24x80 pty, its stdin and stdout. + pty: ?Pty = null, + }; + + pub fn spawn(argv: []const [:0]const u8, opts: Options) !Child { + // A child gone before its stdin is written is EPIPE, not our end. + _ = signal(@intCast(@intFromEnum(libc.SIG.PIPE)), 1); + var args: [32:null]?[*:0]const u8 = @splat(null); + if (argv.len > args.len) return error.TooManyArgs; + for (argv, 0..) |a, i| args[i] = a; + var bufs: [4][4096]u8 = undefined; + // The build hands the binary over by a relative path, and the child + // runs elsewhere. + if (std.mem.indexOfScalar(u8, argv[0], '/') != null) args[0] = realpath(argv[0], &bufs[3]) orelse return error.NoBinary; + const root_z: ?[:0]const u8 = if (opts.root) |r| try std.fmt.bufPrintSentinel(&bufs[0], "{s}", .{r}, 0) else null; + const config = if (opts.root) |r| try std.fmt.bufPrintSentinel(&bufs[1], "{s}/config", .{r}, 0) else ""; + const cwd: ?[:0]const u8 = if (opts.cwd) |c| try std.fmt.bufPrintSentinel(&bufs[2], "{s}", .{c}, 0) else root_z; + // Close-on-exec, so a later child holds none of these. + var err_pipe: [2]c_int = undefined; + if (pipe2(&err_pipe, o_cloexec) != 0) return error.NoPipe; + var in_pipe: [2]c_int = .{ -1, -1 }; + if (opts.stdin != null and pipe2(&in_pipe, o_cloexec) != 0) return error.NoPipe; + var c: Child = .{ .pid = 0, .err_fd = err_pipe[0] }; + if (opts.pty != null) { + var ws: std.posix.winsize = .{ .row = 24, .col = 80, .xpixel = 0, .ypixel = 0 }; + if (openpty(&c.master, &c.slave, null, null, &ws) != 0) return error.NoPty; + for ([_]c_int{ c.master, c.slave }) |fd| _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)); // FD_CLOEXEC + } + const pid = libc.fork(); + if (pid < 0) return error.ForkFailed; + if (pid == 0) { + var i: usize = 0; + while (environ[i]) |kv| { + const entry = std.mem.span(kv); + const eq = std.mem.indexOfScalar(u8, entry, '=') orelse entry.len; + if (std.mem.startsWith(u8, entry, "PARDES_") or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) { + var name: [256]u8 = undefined; + const n = std.fmt.bufPrintSentinel(&name, "{s}", .{entry[0..@min(eq, 255)]}, 0) catch _exit(126); + _ = unsetenv(n); + i = 0; + } else i += 1; + } + if (root_z) |r| for ([_][2][*:0]const u8{ + .{ "HOME", r }, .{ "XDG_RUNTIME_DIR", r }, .{ "XDG_CONFIG_HOME", config }, .{ "PARDES_NOTIME", "1" }, + }) |kv| if (setenv(kv[0], kv[1], 1) != 0) _exit(126); + for ([_][2][*:0]const u8{ + .{ "PARDES_DAEMON", "off" }, .{ "PARDES_LSP_RS", "" }, .{ "PARDES_LSP_C", "" }, .{ "PARDES_LSP_GO", "" }, + .{ "PARDES_LSP_TS", "" }, .{ "PARDES_LSP_PY", "" }, + }) |kv| if (setenv(kv[0], kv[1], 1) != 0) _exit(126); + if (opts.pty != null and setenv("TERM", "xterm-256color", 1) != 0) _exit(126); + for (opts.env) |kv| if (setenv(kv[0], kv[1], 1) != 0) _exit(126); + for (opts.unset) |name| _ = unsetenv(name); + if (cwd) |d| if (libc.chdir(d) != 0) _exit(126); + _ = libc.setsid(); + if (opts.pty) |p| { + if (p.ctty) _ = ioctl(c.slave, 0x540E, @as(c_int, 0)); + _ = libc.dup2(c.slave, 0); + _ = libc.dup2(c.slave, 1); + } else { + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); + _ = libc.dup2(if (opts.stdin != null) in_pipe[0] else null_fd, 0); + _ = libc.dup2(null_fd, 1); + } + _ = libc.dup2(err_pipe[1], 2); + _ = execvp(args[0].?, &args); + _exit(127); + } + c.pid = pid; + _ = libc.close(err_pipe[1]); + if (opts.stdin) |bytes| { + _ = libc.close(in_pipe[0]); + var off: usize = 0; + while (off < bytes.len) { + const n = libc.write(in_pipe[1], bytes[off..].ptr, @min(bytes.len - off, 1 << 20)); + if (n <= 0) break; + off += @intCast(n); + } + _ = libc.close(in_pipe[1]); + } + if (opts.pty) |p| { + const drain = libc.fork(); + if (drain == 0) { + const fd = libc.open(p.log, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + var buf: [16 * 1024]u8 = undefined; + while (true) { + const n = libc.read(c.master, &buf, buf.len); + if (n <= 0) _exit(0); + _ = libc.write(fd, &buf, @intCast(n)); + } + } + c.drain = drain; + } + return c; + } + + /// Its wait(2) word once it has exited, waiting up to `ms`; null while it runs. + pub fn wait(c: *Child, ms: i64) ?c_int { + if (c.status) |s| return s; + const deadline = eh.nowMs() + ms; + while (true) { + var status: c_int = 0; + if (libc.waitpid(c.pid, &status, std.c.W.NOHANG) == c.pid) { + c.status = status; + return status; + } + if (eh.nowMs() >= deadline) return null; + sleepMs(1); + } + } + + /// Everything it wrote to stderr, read to its end (its exit, or every + /// process holding it gone). + pub fn said(c: *Child, gpa: std.mem.Allocator) ![]u8 { + var out: std.ArrayList(u8) = .empty; + var buf: [4096]u8 = undefined; + while (true) { + const n = libc.read(c.err_fd, &buf, buf.len); + if (n <= 0) break; + try out.appendSlice(gpa, buf[0..@intCast(n)]); + } + return out.toOwnedSlice(gpa); + } + + /// Waits up to `ms` for `path` (its socket) to be there; its stderr + /// said if it exits first. + pub fn waitPath(c: *Child, path: []const u8, ms: i64) !void { + var buf: [4096]u8 = undefined; + const z = try std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0); + const deadline = eh.nowMs() + ms; + while (libc.access(z, 0) != 0) { + if (c.wait(0)) |status| { + const words = c.said(std.heap.page_allocator) catch ""; + std.debug.print("exited, status {d}, before {s}: {s}\n", .{ status, path, words }); + return error.Exited; + } + if (eh.nowMs() > deadline) return error.Timeout; + sleepMs(5); + } + } + + pub fn kill(c: *const Child, sig: libc.SIG) void { + if (c.status == null) _ = libc.kill(c.pid, sig); + } + + /// Ended (SIGTERM, SIGKILL after 5 s) and its fds closed. + pub fn deinit(c: *Child) void { + if (c.wait(0) == null) { + _ = libc.kill(c.pid, libc.SIG.TERM); + if (c.wait(5_000) == null) { + _ = libc.kill(c.pid, libc.SIG.KILL); + _ = c.wait(5_000); + } + } + if (c.drain > 0) { + _ = libc.kill(c.drain, libc.SIG.KILL); + var st: c_int = 0; + _ = libc.waitpid(c.drain, &st, 0); + } + for ([_]c_int{ c.err_fd, c.master, c.slave }) |fd| if (fd >= 0) { + _ = libc.close(fd); + }; + } +}; + +/// What a run ended with: its exit code (a signal's is minus it, as +/// Python's returncode) and its stderr. +pub const Ran = struct { code: c_int, said: []u8 }; + +/// `argv` run to its end. +pub fn run(gpa: std.mem.Allocator, argv: []const [:0]const u8, opts: Child.Options) !Ran { + var c = try Child.spawn(argv, opts); + defer c.deinit(); + const words = try c.said(gpa); + var status: c_int = 0; + _ = libc.waitpid(c.pid, &status, 0); + c.status = status; + return .{ .code = code(status), .said = words }; +} + +/// A wait(2) word as an exit code, a signal's as minus it. +pub fn code(status: c_int) c_int { + const sig = status & 0x7f; + return if (sig != 0) -sig else (status >> 8) & 0xff; +} + +/// The names in directory `dir`, kept in `gpa`. +pub fn entries(gpa: std.mem.Allocator, dir: []const u8) ![]const []const u8 { + var buf: [4096]u8 = undefined; + const d = libc.opendir(try std.fmt.bufPrintSentinel(&buf, "{s}", .{dir}, 0)) orelse return error.NoDir; + defer _ = libc.closedir(d); + var names: std.ArrayList([]const u8) = .empty; + while (readdir(d)) |e| { + const name = std.mem.sliceTo(&e.name, 0); + if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue; + try names.append(gpa, try gpa.dupe(u8, name)); + } + return names.toOwnedSlice(gpa); +} + +/// Whether the line discipline of the terminal at `fd` is canonical. +pub fn canonical(fd: c_int) !bool { + var t: std.os.linux.termios = undefined; + if (ioctl(fd, 0x5401, &t) != 0) return error.NoTermios; // TCGETS + return t.lflag.ICANON; +} + +/// Monotonic milliseconds. +pub const nowMs = eh.nowMs; + +pub fn nap(ms: u32) void { + sleepMs(ms); +} + +pub fn has(hay: []const u8, needle: []const u8) bool { + return std.mem.indexOf(u8, hay, needle) != null; +} + +/// `ok`, or what is wrong said and the test failed. +pub fn check(ok: bool, comptime what: []const u8, args: anytype) !void { + if (ok) return; + std.debug.print(what ++ "\n", args); + return error.TestUnexpectedResult; +} + +/// Whether `exe` was built with QUIC (-Dquic=true): refused for that, or +/// for --attach's own reason, which comes after. +pub fn quicIncluded(gpa: std.mem.Allocator, exe: [:0]const u8) !bool { + const r = try run(gpa, &.{ exe, "--attach=work", "--9p-quic=quic!127.0.0.1!0" }, .{}); + defer gpa.free(r.said); + return !has(r.said, "QUIC is not included"); +} |
