diff options
| -rw-r--r-- | 9agents/src/active.zig | 7 | ||||
| -rw-r--r-- | 9agents/src/main.zig | 4 | ||||
| -rw-r--r-- | 9agents/src/tree.zig | 50 | ||||
| -rw-r--r-- | 9ns/README.md | 2 | ||||
| -rw-r--r-- | 9ns/src/bridge.zig | 18 | ||||
| -rw-r--r-- | 9ns/src/fuse.zig | 20 | ||||
| -rw-r--r-- | 9ns/src/main.zig | 2 | ||||
| -rw-r--r-- | 9ns/src/nine.zig | 4 | ||||
| -rw-r--r-- | 9ns/src/ns.zig | 38 | ||||
| -rw-r--r-- | 9proc/README.md | 2 | ||||
| -rw-r--r-- | 9proc/build.zig | 2 | ||||
| -rw-r--r-- | 9proc/demo/main.zig | 8 | ||||
| -rw-r--r-- | 9proc/src/core.zig | 40 | ||||
| -rw-r--r-- | 9proc/src/linux/debug.zig | 16 | ||||
| -rw-r--r-- | 9proc/src/linux/probe.zig | 12 | ||||
| -rw-r--r-- | 9proc/src/linux/runtime.zig | 2 | ||||
| -rw-r--r-- | 9proc/src/vars.zig | 86 | ||||
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | build.zig | 6 | ||||
| -rw-r--r-- | build.zig.zon | 8 | ||||
| -rw-r--r-- | src/fs.zig | 4 | ||||
| -rw-r--r-- | src/post.zig | 48 | ||||
| -rw-r--r-- | src/quic.zig | 2 | ||||
| -rw-r--r-- | src/serve.zig | 10 | ||||
| -rw-r--r-- | src/transport.zig | 2 | ||||
| -rw-r--r-- | src/wire.zig | 44 | ||||
| -rw-r--r-- | web/main.zig | 4 |
27 files changed, 221 insertions, 222 deletions
diff --git a/9agents/src/active.zig b/9agents/src/active.zig index ebf7ed6..301e905 100644 --- a/9agents/src/active.zig +++ b/9agents/src/active.zig @@ -311,7 +311,6 @@ pub fn legalZmxName(name: []const u8) bool { return true; } - // ---- reading /proc and the harness stores ------------------------------------ /// Where the view reads from. Every path below is composed from these @@ -393,7 +392,7 @@ fn join(buf: []u8, parts: []const []const u8) ?[]const u8 { /// `<root>` of a harness, or null when it is not pinned. fn rootOf(s: Sources, k: Kind) ?[]const u8 { - const base = s.roots[@intFromEnum(k)]; + const base = s.roots[@backingInt(k)]; return if (base.len == 0) null else base; } @@ -872,7 +871,6 @@ fn sessionFile(kind: Kind, rel: []const u8) bool { }; } - // ---- fields derived when they are read --------------------------------------- /// The value of `key` in a NUL-separated environment block, as @@ -979,7 +977,6 @@ pub fn bootTime(io: Io, proc: []const u8) i64 { return 0; } - // ---- subagents ---------------------------------------------------------------- /// Longest subagent name answered. @@ -1168,7 +1165,7 @@ test "active: a zmx session name is checked before it is ever used" { try testing.expect(!legalZmxName("../escape")); try testing.expect(!legalZmxName("semi;colon")); try testing.expect(!legalZmxName("nul\x00byte")); - try testing.expect(!legalZmxName("x" ** 65)); + try testing.expect(!legalZmxName(&@as([65]u8, @splat('x')))); } test "active: a codex thread's rollout is found by the day its id was minted" { diff --git a/9agents/src/main.zig b/9agents/src/main.zig index 3e7c290..f564e4b 100644 --- a/9agents/src/main.zig +++ b/9agents/src/main.zig @@ -222,7 +222,7 @@ fn run(init: std.process.Init) !void { std.debug.print("9agents: unknown root {s} (claude, codex, omp, hermes, dsh)\n", .{name}); return error.Usage; }; - base_overrides[@intFromEnum(root)] = v[eq + 1 ..]; + base_overrides[@backingInt(root)] = v[eq + 1 ..]; } } else if (std.mem.eql(u8, a, "--help") or std.mem.eql(u8, a, "-h")) { std.debug.print("{s}", .{usage_text}); @@ -316,7 +316,7 @@ fn run(init: std.process.Init) !void { } switch (mode) { .unix => { - _ = try runner.listen(.{ .unix = try arena.dupeZ(u8, unix_path) }, 16); + _ = try runner.listen(.{ .unix = try arena.dupeSentinel(u8, unix_path, 0) }, 16); std.debug.print("9agents: listening on {s}\n", .{unix_path}); }, .tcp => { diff --git a/9agents/src/tree.zig b/9agents/src/tree.zig index 5e513f1..3c293ba 100644 --- a/9agents/src/tree.zig +++ b/9agents/src/tree.zig @@ -186,7 +186,7 @@ pub const Kind = enum(u8) { top = 0, path = 1, active = 2 }; comptime { // The derived view indexes the same pinned roots the mirror does. for (std.enums.values(Root)) |r| { - if (!std.mem.eql(u8, @tagName(r), @tagName(@as(active.Kind, @enumFromInt(@intFromEnum(r)))))) + if (!std.mem.eql(u8, @tagName(r), @tagName(@as(active.Kind, @fromBackingInt(@intCast(@backingInt(r))))))) @compileError("tree.Root and active.Kind must agree, index by index"); } } @@ -226,8 +226,8 @@ pub const AFile = enum(u8) { /// The fields of one entry, in listing order. A field with no value /// is not listed and does not resolve. pub const entry_files = [_]AFile{ - .pid, .ppid, .started, .cwd, .name, .title, - .session, .model, .via, .zmx, .status, .transcript, + .pid, .ppid, .started, .cwd, .name, .title, + .session, .model, .via, .zmx, .status, .transcript, }; pub const agent_files = [_]AFile{ .agent_model, .agent_transcript }; @@ -269,12 +269,12 @@ comptime { pub fn activeNode(a: Act) u64 { const arg: u48 = if (a.file == .message) a.msg else a.agent; const serial: u48 = switch (a.file) { - .harness_dir => @intFromEnum(a.kind), + .harness_dir => @backingInt(a.kind), else => @as(u48, a.slot) | (@as(u48, a.gen) << act_slot_bits) | (arg << (act_slot_bits + act_gen_bits)), }; return @bitCast(Node{ - .idx = @intFromEnum(a.file), - .kind = @intFromEnum(Kind.active), + .idx = @backingInt(a.file), + .kind = @backingInt(Kind.active), .serial = serial, }); } @@ -287,7 +287,7 @@ pub const Node = packed struct(u64) { }; pub fn topNode(t: Top) u64 { - return @bitCast(Node{ .idx = @intFromEnum(t), .kind = @intFromEnum(Kind.top) }); + return @bitCast(Node{ .idx = @backingInt(t), .kind = @backingInt(Kind.top) }); } pub const root: u64 = topNode(Top.root); @@ -315,8 +315,8 @@ fn serialOf(slot: u12, gen: u32) u48 { fn nodeOf(e: *const Entry, slot: u12) u64 { return @bitCast(Node{ - .idx = @intFromEnum(e.root), - .kind = @intFromEnum(Kind.path), + .idx = @backingInt(e.root), + .kind = @backingInt(Kind.path), .serial = serialOf(slot, e.gen), }); } @@ -516,15 +516,15 @@ pub const Harness = struct { } pub fn base(h: *const Harness, r: Root) ?[]const u8 { - if (!h.base_set[@intFromEnum(r)]) return null; - return h.base_buf[@intFromEnum(r)][0..h.base_len[@intFromEnum(r)]]; + if (!h.base_set[@backingInt(r)]) return null; + return h.base_buf[@backingInt(r)][0..h.base_len[@backingInt(r)]]; } // -- path table -- fn hashOf(r: Root, rel_path: []const u8) u64 { var hh = std.hash.Wyhash.init(0x6861_726e_6573_7300); // "harness" - hh.update(&.{@intFromEnum(r)}); + hh.update(&.{@backingInt(r)}); hh.update(rel_path); return hh.final(); } @@ -969,7 +969,7 @@ fn activePath(h: *Harness, a: Act) ?[]const u8 { /// that is not below the root is not opened at all. Non-blocking, so a /// fifo cannot park the daemon; the caller checks what it got. fn openAgentFile(h: *Harness, k: active.Kind, path: []const u8) ?Io.File { - const r: Root = @enumFromInt(@intFromEnum(k)); + const r: Root = @fromBackingInt(@intCast(@backingInt(k))); const b = h.base(r) orelse return null; if (path.len <= b.len + 1 or !std.mem.startsWith(u8, path, b) or path[b.len] != '/') return null; const fd = openIn(h, r, path[b.len + 1 ..], .{ .ACCMODE = .RDONLY, .NONBLOCK = true, .CLOEXEC = true }) orelse return null; @@ -1357,7 +1357,7 @@ fn spawnZmx(h: *Harness, l: *const active.Live, name: []const u8, resume_value: var argv: [9]?[*:0]const u8 = @splat(null); var n: usize = 0; const parts = [_][]const u8{ - h.zmx_buf[0..h.zmx_len], "run", name, "-d", + h.zmx_buf[0..h.zmx_len], "run", name, "-d", harness_argv0, resume_flag, resume_value, }; for (parts) |w| { @@ -1387,7 +1387,7 @@ fn spawnZmx(h: *Harness, l: *const active.Live, name: []const u8, resume_value: const child: i32 = @intCast(rc); var status: u32 = 0; for (0..post_ticks) |_| { - const w = linux.waitpid(child, &status, 1); // WNOHANG + const w = linux.waitpid(child, @ptrCast(&status), 1); // WNOHANG if (w == @as(usize, @intCast(child))) break; napOneTick(h); } @@ -1893,10 +1893,9 @@ const Rig = struct { var mk: [std.fs.max_path_bytes]u8 = undefined; // The five roots, pinned to the fake home. inline for ([_][]const u8{ - ".claude/projects/p1", ".claude/skills/revu", - ".codex/sessions/2026/09/21", - ".omp/agent", ".hermes/logs", - ".dsh/profiles", + ".claude/projects/p1", ".claude/skills/revu", + ".codex/sessions/2026/09/21", ".omp/agent", + ".hermes/logs", ".dsh/profiles", }) |sub| { try Io.Dir.cwd().createDirPath(io, try std.fmt.bufPrint(&mk, "{s}/{s}", .{ rig.home, sub })); } @@ -1948,7 +1947,6 @@ const Rig = struct { try file.writeStreamingAll(testing.io, bytes); } - fn del(rig: *Rig, rel_path: []const u8) !void { var buf: [std.fs.max_path_bytes]u8 = undefined; const path = try std.fmt.bufPrint(&buf, "{s}/{s}", .{ rig.home, rel_path }); @@ -1983,7 +1981,7 @@ const Rig = struct { const target = if (o.cwd.len > 0) o.cwd else rig.home; var link_buf: [std.fs.max_path_bytes]u8 = undefined; - const link = try std.fmt.bufPrintZ(&link_buf, "{s}/proc/{d}/cwd", .{ rig.home, o.pid }); + const link = try std.fmt.bufPrintSentinel(&link_buf, "{s}/proc/{d}/cwd", .{ rig.home, o.pid }, 0); Io.Dir.cwd().symLink(testing.io, target, link, .{}) catch {}; } @@ -2171,7 +2169,7 @@ test "tree: paths compose only from the pinned roots" { try expectNoent(rig.lookupName(2, topNode(.claude), "projects/\x00")); // A symlink inside a mirror is not served, whatever it points at. var buf: [std.fs.max_path_bytes]u8 = undefined; - const link = try std.fmt.bufPrintZ(&buf, "{s}/.claude/projects/p1/escape", .{rig.home}); + const link = try std.fmt.bufPrintSentinel(&buf, "{s}/.claude/projects/p1/escape", .{rig.home}, 0); try Io.Dir.cwd().symLink(testing.io, rig.home, link, .{}); const projects = rig.lookupName(3, topNode(.claude), "projects"); const p1 = rig.lookupName(4, projects.reply.attr.node, "p1"); @@ -2379,7 +2377,7 @@ test "tree: a name swapped for a symlink under an open handle serves nothing" { // The file becomes a symlink out of the tree while the handle is open. var link_buf: [std.fs.max_path_bytes]u8 = undefined; var target_buf: [std.fs.max_path_bytes]u8 = undefined; - const link = try std.fmt.bufPrintZ(&link_buf, "{s}/.claude/projects/p1/swap.txt", .{rig.home}); + const link = try std.fmt.bufPrintSentinel(&link_buf, "{s}/.claude/projects/p1/swap.txt", .{rig.home}, 0); const target = try std.fmt.bufPrint(&target_buf, "{s}/outside.txt", .{rig.home}); try rig.del(".claude/projects/p1/swap.txt"); try Io.Dir.cwd().symLink(testing.io, target, link, .{}); @@ -2415,7 +2413,7 @@ test "tree: a listing spanning several reads loses no entry" { const count = 200; var name_buf: [320]u8 = undefined; for (0..count) |i| { - const name = try std.fmt.bufPrint(&name_buf, ".dsh/{d:0>3}{s}", .{ i, "n" ** 200 }); + const name = try std.fmt.bufPrint(&name_buf, ".dsh/{d:0>3}{s}", .{ i, &@as([200]u8, @splat('n')) }); try rig.put(name, ""); } var seen: [count]bool = @splat(false); @@ -2686,7 +2684,7 @@ test "chat: a codex agent's rollout, found through the fd it holds" { var link_buf: [std.fs.max_path_bytes]u8 = undefined; var target_buf: [std.fs.max_path_bytes]u8 = undefined; try Io.Dir.cwd().createDirPath(testing.io, try std.fmt.bufPrint(&link_buf, "{s}/proc/1102/fd", .{rig.home})); - const link = try std.fmt.bufPrintZ(&link_buf, "{s}/proc/1102/fd/3", .{rig.home}); + const link = try std.fmt.bufPrintSentinel(&link_buf, "{s}/proc/1102/fd/3", .{rig.home}, 0); const target = try std.fmt.bufPrint(&target_buf, "{s}/{s}", .{ rig.home, rollout }); try Io.Dir.cwd().symLink(testing.io, target, link, .{}); @@ -2759,7 +2757,7 @@ test "chat: a fifo where the transcript should be never blocks the daemon" { const tr = try claudeTranscript(&rig, &rel); try rig.del(tr); var abs: [std.fs.max_path_bytes]u8 = undefined; - const path = try std.fmt.bufPrintZ(&abs, "{s}/{s}", .{ rig.home, tr }); + const path = try std.fmt.bufPrintSentinel(&abs, "{s}/{s}", .{ rig.home, tr }, 0); try testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.mknodat(linux.AT.FDCWD, path, linux.S.IFIFO | 0o600, 0))); for ([_][]const u8{ "title", "model", "transcript", "chat" }) |name| { const f = rig.lookupName(1, entry, name); diff --git a/9ns/README.md b/9ns/README.md index 236e0c4..35c1fb8 100644 --- a/9ns/README.md +++ b/9ns/README.md @@ -63,7 +63,7 @@ other directory. 9ns lives in the [cloud9](../) repository as `cloud9/9ns/`, beside the 9P2000 protocol library it is built on, and is wired into cloud9's `build.zig` through the fragment `9ns/build.zig`. Everything is run from -the cloud9 root with Zig 0.16: +the cloud9 root with Zig 0.17: ```sh zig build # zig-out/bin/{9ns,9proc-demo,9web,cloud9-probe} diff --git a/9ns/src/bridge.zig b/9ns/src/bridge.zig index b94ef78..c866238 100644 --- a/9ns/src/bridge.zig +++ b/9ns/src/bridge.zig @@ -1594,7 +1594,7 @@ const Mntgen = struct { /// Never blocks on the worker; allocation or a racing death reject the /// request with an errno reply instead. fn enqueue(mg: *Mntgen, m: *Mount, raw: []const u8) void { - const wants_reply = switch (@as(fuse.Opcode, @enumFromInt(std.mem.readInt(u32, raw[4..8], .little)))) { + const wants_reply = switch (@as(fuse.Opcode, @fromBackingInt(@intCast(std.mem.readInt(u32, raw[4..8], .little))))) { .forget, .batch_forget => false, else => true, }; @@ -1670,7 +1670,7 @@ const Mntgen = struct { var buf: [@sizeOf(fuse.InHeader) + @sizeOf(fuse.ForgetIn)]u8 = undefined; const hdr = fuse.InHeader{ .len = @sizeOf(fuse.InHeader) + @sizeOf(fuse.ForgetIn), - .opcode = @intFromEnum(fuse.Opcode.forget), + .opcode = @backingInt(fuse.Opcode.forget), .unique = unique, .nodeid = nodeid, .uid = 0, @@ -2155,7 +2155,7 @@ fn uniqueOf(raw: []const u8) u64 { /// Whether the kernel expects an answer to a raw request: everything but /// the forgets. fn wantsReply(raw: []const u8) bool { - return switch (@as(fuse.Opcode, @enumFromInt(std.mem.readInt(u32, raw[4..8], .little)))) { + return switch (@as(fuse.Opcode, @fromBackingInt(@intCast(std.mem.readInt(u32, raw[4..8], .little))))) { .forget, .batch_forget => false, else => true, }; @@ -2689,17 +2689,17 @@ test "attr mapping saturates hostile lengths instead of overflowing" { test "dirent names the kernel would reject are dropped from listings" { try testing.expect(validDirentName("a")); - try testing.expect(validDirentName("x" ** 1024)); + try testing.expect(validDirentName(&@as([1024]u8, @splat('x')))); try testing.expect(!validDirentName("")); try testing.expect(!validDirentName("a/b")); try testing.expect(!validDirentName("a\x00b")); try testing.expect(!validDirentName(".")); try testing.expect(!validDirentName("..")); - try testing.expect(!validDirentName("x" ** 1025)); + try testing.expect(!validDirentName(&@as([1025]u8, @splat('x')))); var buf: [4096]u8 = undefined; var n: usize = 0; - for ([_][]const u8{ ".", "..", "", "a/b", "keep", "x" ** 1025, "also" }) |name| { + for ([_][]const u8{ ".", "..", "", "a/b", "keep", &@as([1025]u8, @splat('x')), "also" }) |name| { n += (try cloud9.Stat.encode(testStat(name, 0o644, 1, 0x30), buf[n..])).len; } var list: DirList = .{}; @@ -2744,7 +2744,7 @@ test "interrupt source: INTERRUPT in flight → Tflush, other INTERRUPTs ignored // A FORGET arriving during a wait is copied into the stash, and the fd // stays watched: an INTERRUPT can still arrive behind it. var wire: [48]u8 = undefined; - const hdr = fuse.InHeader{ .len = 48, .opcode = @intFromEnum(fuse.Opcode.forget), .unique = 99, .nodeid = 5, .uid = 0, .gid = 0, .pid = 0, .total_extlen = 0, .padding = 0 }; + const hdr = fuse.InHeader{ .len = 48, .opcode = @backingInt(fuse.Opcode.forget), .unique = 99, .nodeid = 5, .uid = 0, .gid = 0, .pid = 0, .total_extlen = 0, .padding = 0 }; @memcpy(wire[0..40], std.mem.asBytes(&hdr)); @memcpy(wire[40..48], std.mem.asBytes(&fuse.ForgetIn{ .nlookup = 1 })); try testing.expectEqual(@as(usize, 48), linux.write(pi.write_end, &wire, wire.len)); @@ -2845,7 +2845,7 @@ const FakeKernel = struct { fn send(k: *FakeKernel, op: fuse.Opcode, unique: u64, nodeid: u64, parts: []const []const u8) !void { var len: usize = @sizeOf(fuse.InHeader); for (parts) |p| len += p.len; - const header = fuse.InHeader{ .len = @intCast(len), .opcode = @intFromEnum(op), .unique = unique, .nodeid = nodeid, .uid = 0, .gid = 0, .pid = 0, .total_extlen = 0, .padding = 0 }; + const header = fuse.InHeader{ .len = @intCast(len), .opcode = @backingInt(op), .unique = unique, .nodeid = nodeid, .uid = 0, .gid = 0, .pid = 0, .total_extlen = 0, .padding = 0 }; var wire: [512]u8 = undefined; @memcpy(wire[0..@sizeOf(fuse.InHeader)], std.mem.asBytes(&header)); var at: usize = @sizeOf(fuse.InHeader); @@ -2982,7 +2982,7 @@ test "serve: a parked READ holds up neither other READs nor metadata; its INTERR try k.send(.interrupt, 11, 0, &.{std.mem.asBytes(&fuse.InterruptIn{ .unique = 10 })}); var r = try k.recv(3000); try testing.expectEqual(@as(u64, 10), r.unique); - try testing.expectEqual(-@as(i32, @intFromEnum(linux.E.INTR)), r.err); + try testing.expectEqual(-@as(i32, @backingInt(linux.E.INTR)), r.err); try testing.expectEqual(@as(u32, 1), fs.flushes.load(.seq_cst)); try testing.expectEqual(hung_tag, fs.flush_oldtag.load(.seq_cst)); diff --git a/9ns/src/fuse.zig b/9ns/src/fuse.zig index 5f7b22a..b70365f 100644 --- a/9ns/src/fuse.zig +++ b/9ns/src/fuse.zig @@ -139,7 +139,7 @@ pub const InHeader = extern struct { padding: u16, pub fn op(h: InHeader) Opcode { - return @enumFromInt(h.opcode); + return @fromBackingInt(@intCast(h.opcode)); } }; @@ -254,7 +254,7 @@ pub const Kstatfs = extern struct { namelen: u32 = 0, frsize: u32 = 0, padding: u32 = 0, - spare: [6]u32 = [_]u32{0} ** 6, + spare: [6]u32 = @splat(0), }; pub const StatfsOut = extern struct { st: Kstatfs = .{} }; @@ -283,7 +283,7 @@ pub const InitOut = extern struct { flags2: u32 = 0, max_stack_depth: u32 = 0, request_timeout: u16 = 0, - unused: [11]u16 = [_]u16{0} ** 11, + unused: [11]u16 = @splat(0), }; /// Fixed 24-byte head of `fuse_dirent`; the name follows, padded to 8 bytes. @@ -395,7 +395,7 @@ pub fn reply(fd: i32, unique: u64, payloads: []const []const u8) Error!void { /// Error reply: an `OutHeader` carrying `-errno` and no payload. pub fn replyError(fd: i32, unique: u64, err: linux.E) Error!void { - const code: i32 = @intCast(@intFromEnum(err)); + const code: i32 = @intCast(@backingInt(err)); const header = OutHeader{ .len = @sizeOf(OutHeader), .@"error" = -code, .unique = unique }; var iov = [_]std.posix.iovec_const{.{ .base = @ptrCast(&header), .len = @sizeOf(OutHeader) }}; return writeAll(fd, &iov, 1, @sizeOf(OutHeader)); @@ -528,8 +528,8 @@ test "struct sizes match linux/fuse.h" { try testing.expectEqual(@as(usize, 40), @sizeOf(InHeader)); try testing.expectEqual(@as(usize, 64), @sizeOf(InitOut)); try testing.expectEqual(@as(usize, 24), @sizeOf(Dirent)); - try testing.expectEqual(@as(u32, 26), @intFromEnum(Opcode.init)); - try testing.expectEqual(Opcode.statx, @as(Opcode, @enumFromInt(52))); + try testing.expectEqual(@as(u32, 26), @backingInt(Opcode.init)); + try testing.expectEqual(Opcode.statx, @as(Opcode, @fromBackingInt(@intCast(52)))); } test "addDirent pads records to 8 bytes and refuses when full" { @@ -573,7 +573,7 @@ test "body/nameAfter/secondName on hand-built requests" { const name = "hello"; const hdr = InHeader{ .len = @intCast(@sizeOf(InHeader) + name.len + 1), - .opcode = @intFromEnum(Opcode.lookup), + .opcode = @backingInt(Opcode.lookup), .unique = 7, .nodeid = root_id, .uid = 1000, @@ -617,7 +617,7 @@ test "body/nameAfter/secondName on hand-built requests" { } test "initReply fields" { - var in = InitIn{ .major = 7, .minor = 45, .max_readahead = 131072, .flags = 0, .flags2 = 0, .unused = [_]u32{0} ** 11 }; + var in = InitIn{ .major = 7, .minor = 45, .max_readahead = 131072, .flags = 0, .flags2 = 0, .unused = @splat(0) }; const a = initReply(&in, 1 << 20); try testing.expectEqual(@as(u32, 7), a.major); try testing.expectEqual(@as(u32, 31), a.minor); @@ -696,7 +696,7 @@ test "replyError writes a negative errno" { try replyError(fds[1], 1, .NOSYS); try readExact(fds[0], &out); - try testing.expectEqual(-@as(i32, @intCast(@intFromEnum(linux.E.NOSYS))), std.mem.bytesToValue(OutHeader, &out).@"error"); + try testing.expectEqual(-@as(i32, @intCast(@backingInt(linux.E.NOSYS))), std.mem.bytesToValue(OutHeader, &out).@"error"); } test "readRequest parses one request from a pipe and rejects bad lengths" { @@ -705,7 +705,7 @@ test "readRequest parses one request from a pipe and rejects bad lengths" { defer _ = linux.close(fds[1]); var wire: [48]u8 align(8) = undefined; - const hdr = InHeader{ .len = 48, .opcode = @intFromEnum(Opcode.forget), .unique = 3, .nodeid = 2, .uid = 0, .gid = 0, .pid = 0, .total_extlen = 0, .padding = 0 }; + const hdr = InHeader{ .len = 48, .opcode = @backingInt(Opcode.forget), .unique = 3, .nodeid = 2, .uid = 0, .gid = 0, .pid = 0, .total_extlen = 0, .padding = 0 }; @memcpy(wire[0..40], std.mem.asBytes(&hdr)); @memcpy(wire[40..48], std.mem.asBytes(&ForgetIn{ .nlookup = 11 })); try testing.expectEqual(@as(usize, 48), linux.write(fds[1], &wire, wire.len)); diff --git a/9ns/src/main.zig b/9ns/src/main.zig index 86763a7..21c6bf4 100644 --- a/9ns/src/main.zig +++ b/9ns/src/main.zig @@ -464,7 +464,7 @@ pub fn main(init: std.process.Init) !u8 { var server: ?Server = null; var address: nine.Address = undefined; if (cfg.spawn_cmd) |cmd| { - const cmd_z = try arena.dupeZ(u8, cmd); + const cmd_z = try arena.dupeSentinel(u8, cmd, 0); server = spawnServer(cmd_z, envp) catch return own_failure; ns.watchServer(server.?.pid); address = .{ .fd = server.?.fd }; diff --git a/9ns/src/nine.zig b/9ns/src/nine.zig index 1eda9e2..6b48e7a 100644 --- a/9ns/src/nine.zig +++ b/9ns/src/nine.zig @@ -937,7 +937,7 @@ fn readSocket(fd: i32, buf: []u8) Session.Error!usize { /// Rerror text → errno, per docs/DESIGN.md (first match wins): cloud9's /// fs.enameErrno, which a server's own tests can ask too. pub fn enameToErrno(ename: []const u8) linux.E { - return @enumFromInt(cloud9.fs.enameErrno(ename)); + return @fromBackingInt(@intCast(cloud9.fs.enameErrno(ename))); } // -- transport ------------------------------------------------------------------ @@ -960,7 +960,7 @@ fn openTransport(address: Address) !i32 { .ip4 => |a| { const sa: linux.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, t.port), - .addr = @bitCast(a.bytes), + .addr = std.mem.bytesToValue(u32, &a.bytes), }; const fd = try newSocket(linux.AF.INET, linux.IPPROTO.TCP); errdefer _ = linux.close(fd); diff --git a/9ns/src/ns.zig b/9ns/src/ns.zig index db41eda..f7549ef 100644 --- a/9ns/src/ns.zig +++ b/9ns/src/ns.zig @@ -135,7 +135,7 @@ pub fn pathCandidates(gpa: Allocator, envp: [*:null]const ?[*:0]const u8, name: list.deinit(gpa); } if (std.mem.indexOfScalar(u8, name, '/') != null) { - try list.append(gpa, try gpa.dupeZ(u8, name)); + try list.append(gpa, try gpa.dupeSentinel(u8, name, 0)); return list.toOwnedSlice(gpa); } const path = getenv(envp, "PATH") orelse default_path; @@ -162,7 +162,7 @@ pub fn findInPath(gpa: Allocator, envp: [*:null]const ?[*:0]const u8, name: []co if (linux.errno(rc) != .SUCCESS) continue; if (stx.mode & linux.S.IFMT != linux.S.IFREG) continue; if (stx.mode & 0o111 == 0) continue; - return gpa.dupeZ(u8, c); + return gpa.dupeSentinel(u8, c, 0); } return error.FileNotFound; } @@ -208,7 +208,7 @@ fn freeEnvp(gpa: Allocator, envp: [:null]?[*:0]const u8) void { fn buildArgv(gpa: Allocator, argv: []const []const u8) ![:null]?[*:0]const u8 { const out = try gpa.allocSentinel(?[*:0]const u8, argv.len, null); - for (argv, 0..) |a, i| out[i] = (try gpa.dupeZ(u8, a)).ptr; + for (argv, 0..) |a, i| out[i] = (try gpa.dupeSentinel(u8, a, 0)).ptr; return out; } @@ -246,7 +246,7 @@ pub fn ensureMountpoint(gpa: Allocator, path: [:0]const u8) !void { while (true) { base = std.fs.path.dirname(base) orelse "/"; var base_buf: [path_max]u8 = undefined; - const base_z = std.fmt.bufPrintZ(&base_buf, "{s}", .{base}) catch { + const base_z = std.fmt.bufPrintSentinel(&base_buf, "{s}", .{base}, 0) catch { std.debug.print("9ns: mountpoint {s}: path too long\n", .{path}); return error.Mountpoint; }; @@ -278,7 +278,7 @@ pub fn ensureMountpoint(gpa: Allocator, path: [:0]const u8) !void { std.debug.print("9ns: mkdir {s}: E{t}; refusing to shadow {s} (pass --mount an existing directory)\n", .{ path, mk, base }); return error.Mountpoint; } - const base_z = try gpa.dupeZ(u8, base); + const base_z = try gpa.dupeSentinel(u8, base, 0); defer gpa.free(base_z); try shadowDirectory(gpa, base_z); switch (mkdirComponents(path, base.len, missing)) { @@ -311,7 +311,7 @@ fn mkdirComponents(path: []const u8, base_len: usize, missing: []const u8) E { var it = std.mem.tokenizeScalar(u8, missing, '/'); while (it.next()) |comp| { end += 1 + comp.len; - const prefix = std.fmt.bufPrintZ(&buf, "{s}", .{path[0..end]}) catch return .NAMETOOLONG; + const prefix = std.fmt.bufPrintSentinel(&buf, "{s}", .{path[0..end]}, 0) catch return .NAMETOOLONG; switch (linux.errno(linux.mkdirat(linux.AT.FDCWD, prefix, 0o755))) { .SUCCESS, .EXIST => {}, else => |e| return e, @@ -326,7 +326,7 @@ const FileType = enum { dir, symlink, other }; /// such as /proc/self/root) to the same inode. fn isSameDirectory(a: []const u8, b: [*:0]const u8) bool { var a_buf: [path_max]u8 = undefined; - const a_z = std.fmt.bufPrintZ(&a_buf, "{s}", .{a}) catch return false; + const a_z = std.fmt.bufPrintSentinel(&a_buf, "{s}", .{a}, 0) catch return false; var sa: linux.Statx = undefined; var sb: linux.Statx = undefined; if (linux.errno(linux.statx(linux.AT.FDCWD, a_z, 0, .{ .INO = true }, &sa)) != .SUCCESS) return false; @@ -384,7 +384,7 @@ fn listDir(gpa: Allocator, fd: i32, dirpath: []const u8) ![]Entry { linux.DT.UNKNOWN => fileType(fd, name_ptr, true) orelse .other, else => .other, }; - try list.append(gpa, .{ .name = try gpa.dupeZ(u8, name), .kind = kind }); + try list.append(gpa, .{ .name = try gpa.dupeSentinel(u8, name, 0), .kind = kind }); } } return list.toOwnedSlice(gpa); @@ -423,11 +423,11 @@ fn shadowDirectory(gpa: Allocator, parent: [:0]const u8) !void { var dst_buf: [path_max]u8 = undefined; var link_buf: [path_max]u8 = undefined; for (entries) |e| { - const src = std.fmt.bufPrintZ(&src_buf, "/proc/self/fd/{d}/{s}", .{ pfd, e.name }) catch { + const src = std.fmt.bufPrintSentinel(&src_buf, "/proc/self/fd/{d}/{s}", .{ pfd, e.name }, 0) catch { std.debug.print("9ns: shadow {s}/{s}: name too long (skipped)\n", .{ parent, e.name }); continue; }; - const dst = std.fmt.bufPrintZ(&dst_buf, "{s}/{s}", .{ parent, e.name }) catch { + const dst = std.fmt.bufPrintSentinel(&dst_buf, "{s}/{s}", .{ parent, e.name }, 0) catch { std.debug.print("9ns: shadow {s}/{s}: name too long (skipped)\n", .{ parent, e.name }); continue; }; @@ -509,7 +509,7 @@ pub fn spawn(gpa: Allocator, s: Spawn) !Child { return error.EmptyProgramName; } - const mountpoint = try gpa.dupeZ(u8, s.mountpoint); + const mountpoint = try gpa.dupeSentinel(u8, s.mountpoint, 0); defer gpa.free(mountpoint); const fuse_opts_prefix = try std.fmt.allocPrintSentinel(gpa, "rootmode=40000,user_id={d},group_id={d},max_read={d}", .{ s.uid, s.gid, s.max_read }, 0); defer gpa.free(fuse_opts_prefix); @@ -742,7 +742,7 @@ fn childMain(c: *const ChildArgs) noreturn { } const fd: i32 = @intCast(rc_open); var opts_buf: [256]u8 = undefined; - const opts = std.fmt.bufPrintZ(&opts_buf, "fd={d},{s}", .{ fd, c.fuse_opts_prefix }) catch unreachable; + const opts = std.fmt.bufPrintSentinel(&opts_buf, "fd={d},{s}", .{ fd, c.fuse_opts_prefix }, 0) catch unreachable; const rc = linux.mount("9ns", c.mountpoint, "fuse", linux.MS.NOSUID | linux.MS.NODEV, @intFromPtr(opts.ptr)); if (linux.errno(rc) != .SUCCESS) childFail(c, setup_failure_status, "mount fuse", linux.errno(rc), true); fuse_fd = fd; @@ -860,7 +860,7 @@ fn armWatchdog() void { .it_interval = .{ .sec = 0, .nsec = 0 }, .it_value = .{ .sec = exit_grace_seconds, .nsec = 0 }, }; - _ = linux.setitimer(@intFromEnum(linux.ITIMER.REAL), &t, null); + _ = linux.setitimer(@backingInt(linux.ITIMER.REAL), &t, null); } fn onAlarm(_: linux.SIG) callconv(.c) void { @@ -888,14 +888,14 @@ fn onChld(_: linux.SIG) callconv(.c) void { const srv = server_pid.load(.seq_cst); if (srv > 0) { var sst: u32 = 0; - const src = linux.waitpid(srv, &sst, linux.W.NOHANG); + const src = linux.waitpid(srv, @ptrCast(&sst), linux.W.NOHANG); if (linux.errno(src) == .SUCCESS and src != 0) server_pid.store(0, .seq_cst); } const p = child_pid_ptr orelse return; const pid = @atomicLoad(i32, p, .seq_cst); if (pid <= 0) return; var st: u32 = 0; - const rc = linux.waitpid(pid, &st, linux.W.NOHANG); + const rc = linux.waitpid(pid, @ptrCast(&st), linux.W.NOHANG); if (linux.errno(rc) != .SUCCESS or rc == 0) return; reaped_status.store(st, .release); reaped.store(true, .release); @@ -960,7 +960,7 @@ fn takeReaped() ?u32 { /// waitpid status → exit code (`128+sig` when killed by a signal). pub fn decodeStatus(st: u32) u8 { if (linux.W.IFEXITED(st)) return linux.W.EXITSTATUS(st); - if (linux.W.IFSIGNALED(st)) return 128 +% @as(u8, @truncate(@intFromEnum(linux.W.TERMSIG(st)))); + if (linux.W.IFSIGNALED(st)) return 128 +% @as(u8, @truncate(@backingInt(linux.W.TERMSIG(st)))); return 1; } @@ -969,7 +969,7 @@ pub fn waitChild(pid: i32) !u8 { while (true) { if (takeReaped()) |st| return decodeStatus(st); var st: u32 = 0; - const rc = linux.waitpid(pid, &st, 0); + const rc = linux.waitpid(pid, @ptrCast(&st), 0); switch (linux.errno(rc)) { .SUCCESS => return decodeStatus(st), .INTR => continue, @@ -989,7 +989,7 @@ pub fn waitChild(pid: i32) !u8 { pub fn reapIfExited(pid: i32) ?u8 { if (takeReaped()) |st| return decodeStatus(st); var st: u32 = 0; - const rc = linux.waitpid(pid, &st, linux.W.NOHANG); + const rc = linux.waitpid(pid, @ptrCast(&st), linux.W.NOHANG); switch (linux.errno(rc)) { .SUCCESS => return if (rc == 0) null else decodeStatus(st), .CHILD => return if (takeReaped()) |s| decodeStatus(s) else null, @@ -1000,7 +1000,7 @@ pub fn reapIfExited(pid: i32) ?u8 { /// Reap any child (used for the `--spawn` server at exit). Non-blocking. pub fn reapAny(pid: i32) void { var st: u32 = 0; - _ = linux.waitpid(pid, &st, linux.W.NOHANG); + _ = linux.waitpid(pid, @ptrCast(&st), linux.W.NOHANG); } // --------------------------------------------------------------------------- diff --git a/9proc/README.md b/9proc/README.md index 15177d7..1b4d6c1 100644 --- a/9proc/README.md +++ b/9proc/README.md @@ -1,6 +1,6 @@ # 9proc -A 9P2000 debug/introspection server as a Zig 0.16 library, built on +A 9P2000 debug/introspection server as a Zig 0.17 library, built on [cloud9](../): a debugger-shaped interface where the protocol is just files. Anything that can read a filesystem (a shell, an agent, an editor, `9p`, [9ns](../9ns)) can inspect a running program: build facts, comptime diff --git a/9proc/build.zig b/9proc/build.zig index 670ea27..43176d7 100644 --- a/9proc/build.zig +++ b/9proc/build.zig @@ -50,7 +50,7 @@ pub fn add(b: *std.Build, ctx: Context) Artifacts { // directory `zig build` was invoked from. const build_options = b.addOptions(); var code: u8 = 0; - const repo = b.build_root.path orelse "."; + const repo = b.fmt("{f}", .{b.root}); const change_id = b.runAllowFail(&.{ "jj", "-R", repo, "log", "--no-graph", "-r", "@", "-T", "change_id.short()", "--ignore-working-copy" }, &code, .ignore) catch "unknown"; build_options.addOption([]const u8, "change_id", std.mem.trim(u8, change_id, " \n\r\t")); const stamp = b.runAllowFail(&.{ "date", "-u", "+%Y-%m-%dT%H:%M:%SZ" }, &code, .ignore) catch "unknown"; diff --git a/9proc/demo/main.zig b/9proc/demo/main.zig index df06369..c26dfeb 100644 --- a/9proc/demo/main.zig +++ b/9proc/demo/main.zig @@ -175,13 +175,13 @@ inline fn napMs(ms: u64) void { switch (builtin.cpu.arch) { .x86_64 => _ = asm volatile ("syscall" : [ret] "={rax}" (-> usize), - : [number] "{rax}" (@intFromEnum(linux.SYS.nanosleep)), + : [number] "{rax}" (@backingInt(linux.SYS.nanosleep)), [arg1] "{rdi}" (@intFromPtr(&req)), [arg2] "{rsi}" (@as(usize, 0)), : .{ .rcx = true, .r11 = true, .memory = true }), .aarch64 => _ = asm volatile ("svc #0" : [ret] "={x0}" (-> usize), - : [number] "{x8}" (@intFromEnum(linux.SYS.nanosleep)), + : [number] "{x8}" (@backingInt(linux.SYS.nanosleep)), [arg1] "{x0}" (@intFromPtr(&req)), [arg2] "{x1}" (@as(usize, 0)), : .{ .memory = true }), @@ -260,7 +260,7 @@ pub fn main(init: std.process.Init) !void { fn run(init: std.process.Init) !void { // Transparent huge pages would back the first touched page of every // client buffer with 2 MiB. Best effort: ignore failure. - _ = linux.prctl(@intFromEnum(linux.PR.SET_THP_DISABLE), 1, 0, 0, 0); + _ = linux.prctl(@backingInt(linux.PR.SET_THP_DISABLE), 1, 0, 0, 0); const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); @@ -390,7 +390,7 @@ test "ctl commands" { const shared = shared_mem.get(); var a: App = .{ .info = .{}, .probe = probe, .shared = shared }; probe.thread_tid = .init(0); - probe.serving = .initEmpty(); + probe.serving = .empty; probe.nested = 0; var buf: [128]u8 = undefined; var w: Writer = .fixed(&buf); diff --git a/9proc/src/core.zig b/9proc/src/core.zig index 12ecff9..bdeb715 100644 --- a/9proc/src/core.zig +++ b/9proc/src/core.zig @@ -239,20 +239,20 @@ pub fn fieldsText(comptime T: type) []const u8 { @setEvalBranchQuota(200_000); var s: []const u8 = ""; switch (@typeInfo(T)) { - .@"struct" => |info| for (info.fields) |f| { + .@"struct" => |info| for (info.field_names, info.field_types, info.field_attrs) |name, F, attrs| { if (info.layout == .@"packed") { - s = s ++ std.fmt.comptimePrint("{s}: {s} @{d}b\n", .{ f.name, @typeName(f.type), @bitOffsetOf(T, f.name) }); - } else if (f.is_comptime) { - s = s ++ std.fmt.comptimePrint("{s}: {s} (comptime)\n", .{ f.name, @typeName(f.type) }); + s = s ++ std.fmt.comptimePrint("{s}: {s} @{d}b\n", .{ name, @typeName(F), @bitOffsetOf(T, name) }); + } else if (attrs.@"comptime") { + s = s ++ std.fmt.comptimePrint("{s}: {s} (comptime)\n", .{ name, @typeName(F) }); } else { - s = s ++ std.fmt.comptimePrint("{s}: {s} @{d}\n", .{ f.name, @typeName(f.type), @offsetOf(T, f.name) }); + s = s ++ std.fmt.comptimePrint("{s}: {s} @{d}\n", .{ name, @typeName(F), @offsetOf(T, name) }); } }, - .@"union" => |info| for (info.fields) |f| { - s = s ++ f.name ++ ": " ++ @typeName(f.type) ++ "\n"; + .@"union" => |info| for (info.field_names, info.field_types) |name, F| { + s = s ++ name ++ ": " ++ @typeName(F) ++ "\n"; }, - .@"enum" => |info| for (info.fields) |f| { - s = s ++ std.fmt.comptimePrint("{s} = {d}\n", .{ f.name, f.value }); + .@"enum" => |info| for (info.field_names, info.field_values) |name, value| { + s = s ++ std.fmt.comptimePrint("{s} = {d}\n", .{ name, value }); }, else => s = @typeName(T) ++ "\n", } @@ -264,11 +264,11 @@ fn declsText(comptime T: type) []const u8 { comptime { @setEvalBranchQuota(20_000); const decls = switch (@typeInfo(T)) { - inline .@"struct", .@"union", .@"enum", .@"opaque" => |info| info.decls, - else => &[_]std.builtin.Type.Declaration{}, + inline .@"struct", .@"union", .@"enum", .@"opaque" => |info| info.decl_names, + else => &[_][:0]const u8{}, }; var s: []const u8 = ""; - for (decls) |d| s = s ++ d.name ++ "\n"; + for (decls) |name| s = s ++ name ++ "\n"; return s; } } @@ -297,10 +297,10 @@ pub const Node = struct { } }; -fn genNodes(comptime Fns: type) [@typeInfo(Fns).@"struct".decls.len]Node { - const decls = @typeInfo(Fns).@"struct".decls; +fn genNodes(comptime Fns: type) [@typeInfo(Fns).@"struct".decl_names.len]Node { + const decls = @typeInfo(Fns).@"struct".decl_names; var arr: [decls.len]Node = undefined; - for (decls, 0..) |d, i| arr[i] = .{ .name = d.name, .kind = .dynamic, .gen = genFor(Fns, d.name) }; + for (decls, 0..) |name, i| arr[i] = .{ .name = name, .kind = .dynamic, .gen = genFor(Fns, name) }; return arr; } @@ -490,7 +490,7 @@ pub fn Server(comptime cfg: Config) type { pub fn expose(s: *Shared, name: []const u8, ptr: anytype) error{Full}!void { const P = @TypeOf(ptr); const info = @typeInfo(P); - if (info != .pointer or info.pointer.size != .one or info.pointer.is_const) @compileError("expose wants a *T, got " ++ @typeName(P)); + if (info != .pointer or info.pointer.size != .one or info.pointer.attrs.@"const") @compileError("expose wants a *T, got " ++ @typeName(P)); if (s.nvars == cfg.max_vars) return error.Full; std.debug.assert(validName(name) != error.BadName); std.debug.assert(s.findVar(name) == null); @@ -1759,7 +1759,7 @@ test "runtime/fn calls the function at open and at each read from offset 0" { defer x.deinit(); const names = try x.h.listPath(&.{ "runtime", "fn" }); defer TS.Harness.freeNames(names); - try testing.expectEqual(@typeInfo(TestFns).@"struct".decls.len, names.len); + try testing.expectEqual(@typeInfo(TestFns).@"struct".decl_names.len, names.len); const fib_text = try x.h.readPath(&.{ "runtime", "fn", "fib30" }); defer testing.allocator.free(fib_text); try testing.expectEqualStrings("832040", fib_text); @@ -2012,7 +2012,7 @@ test "provider: walk/list/stat/open/read/write/create/remove/wstat/clunk and err try testing.expectEqualStrings("fresh", rr.read); try x.h.walkTo(6, &.{"prov"}); try x.h.expectFail(.{ .create = .{ .fid = 6, .name = "new", .perm = 0o644, .mode = cloud9.oread } }, "file already exists"); - const long_name = [_]u8{'n'} ** (max_name + 1); + const long_name: [max_name + 1]u8 = @splat('n'); try x.h.expectFail(.{ .create = .{ .fid = 6, .name = &long_name, .perm = 0o644, .mode = cloud9.oread } }, e_illegal_name); try x.h.expectFail(.{ .create = .{ .fid = 6, .name = "d", .perm = cloud9.dmdir | 0o755, .mode = cloud9.owrite } }, e_perm); const dr = try x.h.ok(.{ .create = .{ .fid = 6, .name = "d", .perm = cloud9.dmdir | 0o755, .mode = cloud9.oread } }); @@ -2162,12 +2162,12 @@ test "msize: below the engine's floor the connection dies; at the floor everythi const st = try y.h.ok(.{ .stat = .{ .fid = 0 } }); try testing.expectEqualStrings("/", st.stat.name); // A full 16-element Rwalk is exactly msize_min. - const w = try y.h.ok(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &([_][]const u8{"."} ** 16) } }); + const w = try y.h.ok(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &@as([16][]const u8, @splat(".")) } }); try testing.expectEqual(@as(u16, 16), w.walk.nwqid); _ = try y.h.ok(.{ .clunk = .{ .fid = 1 } }); // An Rstat that cannot fit is an Rerror, not a dead connection. try y.h.walkTo(2, &.{"prov"}); - const long_name = [_]u8{'n'} ** 180; // Tcreate fits; the Rstat (61 + 180 bytes) does not + const long_name: [180]u8 = @splat('n'); // Tcreate fits; the Rstat (61 + 180 bytes) does not _ = try y.h.ok(.{ .create = .{ .fid = 2, .name = &long_name, .perm = 0o644, .mode = cloud9.oread } }); try y.h.expectFail(.{ .stat = .{ .fid = 2 } }, e_small_msize); _ = try y.h.ok(.{ .remove = .{ .fid = 2 } }); diff --git a/9proc/src/linux/debug.zig b/9proc/src/linux/debug.zig index a344380..8bbee52 100644 --- a/9proc/src/linux/debug.zig +++ b/9proc/src/linux/debug.zig @@ -163,7 +163,7 @@ pub const Debug = struct { max_paused: u8, capture: CaptureSlot = .{}, - paused: [max_paused_cap]PauseSlot = [_]PauseSlot{.{}} ** max_paused_cap, + paused: [max_paused_cap]PauseSlot = @splat(.{}), old_capture_action: linux.Sigaction = undefined, old_trap_action: linux.Sigaction = undefined, @@ -187,7 +187,7 @@ pub const Debug = struct { d.* = .{ .io = opts.io, .text_buf = opts.text_buf, - .capture_signal = @enumFromInt(opts.capture_signal), + .capture_signal = @fromBackingInt(@intCast(opts.capture_signal)), .capture_timeout_ns = opts.capture_timeout_ns, .max_paused = opts.max_paused, }; @@ -249,7 +249,7 @@ pub const Debug = struct { pub fn threadExists(d: *Debug, tid: u32) bool { _ = d; var path_buf: [64]u8 = undefined; - const path = std.fmt.bufPrintZ(&path_buf, "/proc/self/task/{d}/comm", .{tid}) catch return false; + const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/self/task/{d}/comm", .{tid}, 0) catch return false; var buf: [32]u8 = undefined; _ = readFile(path, &buf) catch return false; return true; @@ -259,7 +259,7 @@ pub const Debug = struct { pub fn threadName(d: *Debug, tid: u32, w: *Writer) Error!void { _ = d; var path_buf: [64]u8 = undefined; - const path = std.fmt.bufPrintZ(&path_buf, "/proc/self/task/{d}/comm", .{tid}) catch return error.Unexpected; + const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/self/task/{d}/comm", .{tid}, 0) catch return error.Unexpected; var buf: [64]u8 = undefined; const text = readFile(path, &buf) catch |err| switch (err) { error.NotFound => return error.NoThread, @@ -273,7 +273,7 @@ pub const Debug = struct { pub fn threadStat(d: *Debug, tid: u32, w: *Writer) Error!void { _ = d; var path_buf: [64]u8 = undefined; - const path = std.fmt.bufPrintZ(&path_buf, "/proc/self/task/{d}/stat", .{tid}) catch return error.Unexpected; + const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/self/task/{d}/stat", .{tid}, 0) catch return error.Unexpected; var buf: [1024]u8 = undefined; const text = readFile(path, &buf) catch |err| switch (err) { error.NotFound => return error.NoThread, @@ -924,8 +924,8 @@ fn writeHexLines(base: usize, bytes: []const u8, w: *Writer) Error!void { fn writeRegs(ctx: *const Native, w: *Writer) Error!void { if (comptime arch == .x86_64) { - inline for (@typeInfo(Native.Gpr).@"enum".fields) |f| { - w.print("{s} 0x{x}\n", .{ f.name, ctx.gprs.get(@field(Native.Gpr, f.name)) }) catch return error.WriteFailed; + inline for (@typeInfo(Native.GprName).@"enum".field_names) |name| { + w.print("{s} 0x{x}\n", .{ name, ctx.gprs.get(@field(Native.GprName, name)) }) catch return error.WriteFailed; } w.print("pc 0x{x}\nsp 0x{x}\nfp 0x{x}\n", .{ ctx.gprs.get(.rip), ctx.gprs.get(.rsp), ctx.gprs.get(.rbp), @@ -1369,7 +1369,7 @@ test "panic record path" { // A long message is truncated, not overflowed. resetPanicRecord(); - const long = [_]u8{'x'} ** (panic_msg_cap + 100); + const long: [panic_msg_cap + 100]u8 = @splat('x'); try testing.expect(recordPanic(&long, null)); out.clearRetainingCapacity(); try d.panicMessage(&out.writer); diff --git a/9proc/src/linux/probe.zig b/9proc/src/linux/probe.zig index 00c256e..f9cb585 100644 --- a/9proc/src/linux/probe.zig +++ b/9proc/src/linux/probe.zig @@ -141,7 +141,7 @@ pub fn Probe(comptime Srv: type) type { refused: u64 = 0, stopping: std.atomic.Value(bool) = .init(false), /// Slots whose request is being handled (excluded from nested servicing and eviction). - serving: std.StaticBitSet(256) = .initEmpty(), + serving: std.StaticBitSet(256) = .empty, /// Current `sleepServing` nesting depth. nested: u8 = 0, debug_ready: bool = false, @@ -569,7 +569,7 @@ pub fn Probe(comptime Srv: type) type { const rc = linux.statx(linux.AT.FDCWD, path, 0, .{ .TYPE = true, .INO = true }, &stx); const s: isize = @bitCast(rc); if (s == 0) return stx; - const noent: isize = @intCast(@intFromEnum(linux.E.NOENT)); + const noent: isize = @intCast(@backingInt(linux.E.NOENT)); if (s == -noent) return null; return error.StatFailed; } @@ -616,7 +616,7 @@ pub fn parseIpv4(text: []const u8) ?linux.sockaddr.in { var it = std.mem.splitScalar(u8, text[0..colon], '.'); for (&octets) |*o| o.* = std.fmt.parseInt(u8, it.next() orelse return null, 10) catch return null; if (it.next() != null) return null; - return .{ .port = std.mem.nativeToBig(u16, port), .addr = @bitCast(octets) }; + return .{ .port = std.mem.nativeToBig(u16, port), .addr = std.mem.bytesToValue(u32, &octets) }; } /// Names the calling thread (comm, at most 15 bytes) via prctl. @@ -624,7 +624,7 @@ pub fn setThreadName(name: []const u8) void { var buf: [16]u8 = @splat(0); const n = @min(name.len, 15); @memcpy(buf[0..n], name[0..n]); - _ = linux.prctl(@intFromEnum(linux.PR.SET_NAME), @intFromPtr(&buf), 0, 0, 0); + _ = linux.prctl(@backingInt(linux.PR.SET_NAME), @intFromPtr(&buf), 0, 0, 0); } pub fn sleepMs(ms: u64) void { @@ -863,7 +863,7 @@ test "probe: single pre-connected client mode ends when the client hangs up" { test "parseIpv4 and sleepServing off the probe thread" { const sa = parseIpv4("127.0.0.1:564").?; try testing.expectEqual(std.mem.nativeToBig(u16, 564), sa.port); - try testing.expectEqual(@as(u32, @bitCast([4]u8{ 127, 0, 0, 1 })), sa.addr); + try testing.expectEqual(std.mem.bytesToValue(u32, &[4]u8{ 127, 0, 0, 1 }), sa.addr); try testing.expect(parseIpv4("localhost:1") == null); try testing.expect(parseIpv4("1.2.3:1") == null); try testing.expect(parseIpv4("1.2.3.4") == null); @@ -871,7 +871,7 @@ test "parseIpv4 and sleepServing off the probe thread" { const t0 = monotonicMs(); var probe: TP = undefined; probe.thread_tid = .init(0); - probe.serving = .initEmpty(); + probe.serving = .empty; probe.nested = 0; probe.sleepServing(20); try testing.expect(monotonicMs() - t0 >= 20); diff --git a/9proc/src/linux/runtime.zig b/9proc/src/linux/runtime.zig index 503d6c2..c7a7366 100644 --- a/9proc/src/linux/runtime.zig +++ b/9proc/src/linux/runtime.zig @@ -86,5 +86,5 @@ test "runtime generators read Info through the context" { w = .fixed(&buf); try F.pid(&ctx, &w); try std.testing.expectEqual(linux.getpid(), try std.fmt.parseInt(i32, w.buffered(), 10)); - try std.testing.expectEqual(@as(usize, 7), @typeInfo(F).@"struct".decls.len); + try std.testing.expectEqual(@as(usize, 7), @typeInfo(F).@"struct".decl_names.len); } diff --git a/9proc/src/vars.zig b/9proc/src/vars.zig index 20cadfc..90a5ee4 100644 --- a/9proc/src/vars.zig +++ b/9proc/src/vars.zig @@ -100,8 +100,9 @@ fn hasFields(comptime T: type, depth: u8) bool { fn fieldCount(comptime T: type) usize { var n: usize = 0; - for (@typeInfo(T).@"struct".fields) |f| { - if (!f.is_comptime and @sizeOf(f.type) != 0) n += 1; + const info = @typeInfo(T).@"struct"; + for (info.field_types, info.field_attrs) |F, attrs| { + if (!attrs.@"comptime" and @sizeOf(F) != 0) n += 1; } return n; } @@ -110,9 +111,10 @@ fn countNodes(comptime T: type, depth: u8) usize { var n: usize = 6; // dir + value, type, size, addr, raw if (hasFields(T, depth)) { n += 1; // f - for (@typeInfo(T).@"struct".fields) |f| { - if (f.is_comptime or @sizeOf(f.type) == 0) continue; - n += countNodes(f.type, depth + 1); + const info = @typeInfo(T).@"struct"; + for (info.field_types, info.field_attrs) |F, attrs| { + if (attrs.@"comptime" or @sizeOf(F) == 0) continue; + n += countNodes(F, depth + 1); } } return n; @@ -137,9 +139,10 @@ fn fill(nodes: []Node, next: *usize, idx: usize, comptime T: type, name: []const next.* += nf; nodes[fdir] = .{ .name = "f", .kind = .fields, .parent = me, .first = @intCast(ffirst), .count = @intCast(nf), .offset = offset, .size = @sizeOf(T) }; var i: usize = 0; - for (@typeInfo(T).@"struct".fields) |f| { - if (f.is_comptime or @sizeOf(f.type) == 0) continue; - fill(nodes, next, ffirst + i, f.type, f.name, offset + @offsetOf(T, f.name), depth + 1, fdir); + const info = @typeInfo(T).@"struct"; + for (info.field_names, info.field_types, info.field_attrs) |field_name, F, attrs| { + if (attrs.@"comptime" or @sizeOf(F) == 0) continue; + fill(nodes, next, ffirst + i, F, field_name, offset + @offsetOf(T, field_name), depth + 1, fdir); i += 1; } } @@ -198,7 +201,7 @@ pub fn render(ptr: anytype, w: *Writer, depth: usize) Writer.Error!void { fn isPlainStruct(comptime T: type) bool { return switch (@typeInfo(T)) { - .@"struct" => |s| !s.is_tuple and s.fields.len > 0, + .@"struct" => |s| !s.is_tuple and s.field_names.len > 0, else => false, }; } @@ -210,25 +213,26 @@ fn renderStruct(comptime T: type, ptr: *const T, w: *Writer, depth: usize, inden try w.writeAll("…\n"); return; } - const packed_layout = @typeInfo(T).@"struct".layout == .@"packed"; - inline for (@typeInfo(T).@"struct".fields) |f| { + const info = @typeInfo(T).@"struct"; + const packed_layout = info.layout == .@"packed"; + inline for (info.field_names, info.field_types, info.field_attrs) |field_name, F, attrs| { try w.splatByteAll(' ', indent); - try w.writeAll(f.name); + try w.writeAll(field_name); try w.writeByte(':'); - if (comptime f.is_comptime) { + if (comptime attrs.@"comptime") { try w.writeAll(" (comptime)\n"); } else if (comptime packed_layout) { // Fields of a packed struct have no byte address: render a copy. - const v = @field(ptr.*, f.name); + const v = @field(ptr.*, field_name); try w.writeByte(' '); - try renderValue(f.type, &v, w, depth - 1); + try renderValue(F, &v, w, depth - 1); try w.writeByte('\n'); - } else if (comptime isPlainStruct(f.type)) { + } else if (comptime isPlainStruct(F)) { try w.writeByte('\n'); - try renderStruct(f.type, &@field(ptr.*, f.name), w, depth - 1, indent + 2); + try renderStruct(F, &@field(ptr.*, field_name), w, depth - 1, indent + 2); } else { try w.writeByte(' '); - try renderValue(f.type, &@field(ptr.*, f.name), w, depth - 1); + try renderValue(F, &@field(ptr.*, field_name), w, depth - 1); try w.writeByte('\n'); } } @@ -255,15 +259,15 @@ fn renderValue(comptime T: type, ptr: *const T, w: *Writer, depth: usize) Writer // value is a safety panic, and the value is caller memory we do not // control. A load through the tag type would truncate to its bit // width (a u2 tag in a byte), so the full storage width is read. - if (@sizeOf(T) == 0) return w.writeAll(e.fields[0].name); - const Raw = std.meta.Int(.unsigned, @sizeOf(T) * 8); + if (@sizeOf(T) == 0) return w.writeAll(e.field_names[0]); + const Raw = @Int(.unsigned, @sizeOf(T) * 8); const raw = @as(*align(@alignOf(T)) const Raw, @ptrCast(ptr)).*; - const TagU = std.meta.Int(.unsigned, @bitSizeOf(e.tag_type)); + const TagU = @Int(.unsigned, @bitSizeOf(e.tag_type)); const padding: Raw = if (@bitSizeOf(TagU) == @bitSizeOf(Raw)) 0 else ~@as(Raw, std.math.maxInt(TagU)); if (raw & padding == 0) { const low: TagU = @truncate(raw); - inline for (e.fields) |f| { - if (low == @as(TagU, @bitCast(@as(e.tag_type, f.value)))) return w.writeAll(f.name); + inline for (e.field_names, e.field_values) |field_name, value| { + if (low == @as(TagU, @bitCast(@as(e.tag_type, value)))) return w.writeAll(field_name); } } try w.print("{d}", .{raw}); @@ -306,24 +310,24 @@ fn renderValue(comptime T: type, ptr: *const T, w: *Writer, depth: usize) Writer try w.writeAll("…"); return; } - if (s.fields.len == 0) { + if (s.field_names.len == 0) { try w.writeAll("{}"); return; } try w.writeAll("{ "); - inline for (s.fields, 0..) |f, i| { + inline for (s.field_names, s.field_types, s.field_attrs, 0..) |field_name, F, attrs, i| { if (i != 0) try w.writeAll(", "); if (!s.is_tuple) { - try w.writeAll(f.name); + try w.writeAll(field_name); try w.writeAll(": "); } - if (comptime f.is_comptime) { + if (comptime attrs.@"comptime") { try w.writeAll("(comptime)"); } else if (comptime s.layout == .@"packed") { - const v = @field(ptr.*, f.name); - try renderValue(f.type, &v, w, depth - 1); + const v = @field(ptr.*, field_name); + try renderValue(F, &v, w, depth - 1); } else { - try renderValue(f.type, &@field(ptr.*, f.name), w, depth - 1); + try renderValue(F, &@field(ptr.*, field_name), w, depth - 1); } } try w.writeAll(" }"); @@ -338,13 +342,13 @@ fn renderValue(comptime T: type, ptr: *const T, w: *Writer, depth: usize) Writer return; } // A switch on a corrupt tag is a safety panic: match the integer first. - const raw = @intFromEnum(@as(Tag, ptr.*)); - inline for (u.fields) |f| { - if (raw == @intFromEnum(@field(Tag, f.name))) { - try w.writeAll(f.name); - if (f.type != void) { + const raw = @backingInt(@as(Tag, ptr.*)); + inline for (u.field_names, u.field_types) |field_name, F| { + if (raw == @backingInt(@field(Tag, field_name))) { + try w.writeAll(field_name); + if (F != void) { try w.writeAll(": "); - try renderValue(f.type, &@field(ptr.*, f.name), w, depth - 1); + try renderValue(F, &@field(ptr.*, field_name), w, depth - 1); } return; } @@ -421,9 +425,9 @@ pub fn set(ptr: anytype, text: []const u8) SetError!void { .@"enum" => |e| { if (std.meta.stringToEnum(T, s)) |v| { ptr.* = v; - } else if (!e.is_exhaustive) { + } else if (e.mode != .exhaustive) { const raw = std.fmt.parseInt(e.tag_type, s, 0) catch return error.Invalid; - ptr.* = @enumFromInt(raw); + ptr.* = @fromBackingInt(@intCast(raw)); } else return error.Invalid; }, else => return error.Unsupported, @@ -466,7 +470,7 @@ test "render scalars, strings, pointers, optionals, enums, arrays" { const e: E = .green; try testing.expectEqualStrings("green", try renderToBuf(&buf, &e)); const NE = enum(u8) { a, _ }; - const ne: NE = @enumFromInt(9); + const ne: NE = @fromBackingInt(@intCast(9)); try testing.expectEqualStrings("9", try renderToBuf(&buf, &ne)); const arr = [_]u16{ 1, 2, 3 }; try testing.expectEqualStrings("[1, 2, 3]", try renderToBuf(&buf, &arr)); @@ -508,7 +512,7 @@ test "render structs multi-line with nested indentation and depth limit" { } test "long strings and arrays are truncated" { - const long = [_]u8{'x'} ** 300; + const long: [300]u8 = @splat('x'); var buf: [1024]u8 = undefined; const s: []const u8 = &long; const out = try renderToBuf(&buf, &s); @@ -802,7 +806,7 @@ test "set rejects hostile input without partial writes" { const NE = enum(u8) { a, _ }; var ne: NE = .a; try set(&ne, "200"); - try testing.expectEqual(@as(u8, 200), @intFromEnum(ne)); + try testing.expectEqual(@as(u8, 200), @backingInt(ne)); try testing.expectError(error.Invalid, set(&ne, "256")); try testing.expectError(error.Invalid, set(&ne, "-1")); try set(&ne, "a"); @@ -1,6 +1,6 @@ # cloud9 -A Zig 0.16 library for base **9P2000** clients, servers, and transports. +A Zig 0.17 library for base **9P2000** clients, servers, and transports. The protocol core uses caller-owned buffers and bounded request tables. It has no heap allocation, OS calls, threads, or filesystem policy. TCP and Unix stream @@ -41,7 +41,7 @@ pub fn build(b: *std.Build) void { bridge.root_module.addAnonymousImport("client.wasm", .{ .root_source_file = wasm.getEmittedBin() }); b.installArtifact(bridge); const run_bridge = b.addRunArtifact(bridge); - if (b.args) |args| run_bridge.addArgs(args); + run_bridge.addPassthruArgs(); b.step("serve", "Run the HTTP/WebSocket bridge (--upstream tcp:127.0.0.1:564)").dependOn(&run_bridge.step); const native_http = b.addExecutable(.{ .name = "9web-test", .root_module = b.createModule(.{ .root_source_file = b.path("test/web/native.zig"), @@ -102,7 +102,7 @@ pub fn build(b: *std.Build) void { diff.addArtifactArg(probe); diff.addArg("--session-probe"); diff.addArtifactArg(session_probe); - if (b.args) |args| diff.addArgs(args); + diff.addPassthruArgs(); b.step("differential", "Compare valid traffic with pinned 9fans and go9p").dependOn(&diff.step); const transport_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("test/transport.zig"), @@ -134,7 +134,7 @@ pub fn build(b: *std.Build) void { .imports = &.{.{ .name = "cloud9", .module = module }}, }) }); const run_fuzz = b.addRunArtifact(fuzz); - if (b.args) |args| run_fuzz.addArgs(args); + run_fuzz.addPassthruArgs(); b.step("fuzz", "Run deterministic local decoder and server probes (seed, iterations)").dependOn(&run_fuzz.step); // ------------------------------------------------------------------ diff --git a/build.zig.zon b/build.zig.zon index b275168..67c11c9 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -2,7 +2,7 @@ .name = .cloud9, .fingerprint = 0xc8b2d5eaa3adfca, .version = "0.1.0", - .minimum_zig_version = "0.16.0", + .minimum_zig_version = "0.17.0", // Every directory build.zig reaches into must be here, or the // published package cannot build: build.zig @imports each program's // build fragment unconditionally, so a program missing from this @@ -10,8 +10,8 @@ // from a checkout. 9agents was exactly that until a pardes build // caught it. .paths = .{ - "build.zig", "build.zig.zon", "src", "web", - "test", "docs", "README.md", - "9ns", "9proc", "9agents", + "build.zig", "build.zig.zon", "src", "web", + "test", "docs", "README.md", "9ns", + "9proc", "9agents", }, } @@ -2068,7 +2068,7 @@ test "fs server: backend-sized filenames survive walk and stat within negotiated var encoded: [1024]u8 = undefined; var server = Native.init(.{ .in = &in, .out = &out, .root = 1 }); server.protocol.msize = case.msize; - server.setUname("u" ** Native.options.username_capacity); + server.setUname(&@as([Native.options.username_capacity]u8, @splat('u'))); server.fids[0] = .{ .used = true, .fid = 0, .node = 1, .dir = true, .perm = 0o500 }; const name = filename[0..case.length]; const walk = try encode(.{ .twalk = .{ @@ -2738,7 +2738,7 @@ test "fs server: a message arriving a byte at a time is served when its last byt } test "fs server: invalid framing and reply types terminate the connection" { - for ([_]u8{ @intFromEnum(wire.Type.rstat), 8, 0 }) |kind| { + for ([_]u8{ @backingInt(wire.Type.rstat), 8, 0 }) |kind| { var h: Harness = .{}; try h.handshake(4096); var buf: [64]u8 = undefined; diff --git a/src/post.zig b/src/post.zig index 641970d..1355b56 100644 --- a/src/post.zig +++ b/src/post.zig @@ -191,7 +191,7 @@ fn socketNonblocking() !i32 { /// directly. fn rawErrno(rc: isize) linux.E { const n: usize = if (rc < 0 and -rc < 4096) @intCast(-rc) else 0; - return @enumFromInt(n); + return @fromBackingInt(@intCast(n)); } pub const DialError = error{ @@ -329,7 +329,7 @@ pub fn post(io: Io, env: Env, name: []const u8, backlog: u31, path_buf: []u8) Po const parent = dir_path[0 .. dir_path.len - "/9p".len]; const serial = temp_serial.fetchAdd(1, .monotonic); var tmp_buf: [std.fs.max_path_bytes]u8 = undefined; - const tmp = std.fmt.bufPrintZ(&tmp_buf, "{s}/.post.sock.{d}.{d}", .{ parent, linux.getpid(), serial }) catch return error.NoSpace; + const tmp = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/.post.sock.{d}.{d}", .{ parent, linux.getpid(), serial }, 0) catch return error.NoSpace; var attempts: usize = 0; var saw_not_socket = false; claim: while (attempts < post_attempts) : (attempts += 1) { @@ -456,7 +456,7 @@ fn claimName(io: Io, registry_dir: [:0]const u8, path: [:0]const u8, sock_tmp: [ // registry directory, so no listing ever sees it. const dummy_serial = temp_serial.fetchAdd(1, .monotonic); var dummy_buf: [std.fs.max_path_bytes]u8 = undefined; - const dummy = std.fmt.bufPrintZ(&dummy_buf, "{s}/.post.tmp.{d}.{d}", .{ parent, linux.getpid(), dummy_serial }) catch return .retry; + const dummy = std.fmt.bufPrintSentinel(&dummy_buf, "{s}/.post.tmp.{d}.{d}", .{ parent, linux.getpid(), dummy_serial }, 0) catch return .retry; var dummy_file = Io.Dir.createFileAbsolute(io, dummy, .{ .exclusive = true, .truncate = false }) catch return .retry; dummy_file.close(io); const dummy_st = Io.Dir.statFile(.cwd(), io, dummy, .{}) catch { @@ -567,7 +567,7 @@ fn swapBack(path: [:0]const u8, tmp: [:0]const u8) isize { /// serialization. fn lockStaleRemoval(registry_dir: [:0]const u8) i32 { var buf: [std.fs.max_path_bytes]u8 = undefined; - const lock_path = std.fmt.bufPrintZ(&buf, "{s}/.post.lock", .{registry_dir[0 .. registry_dir.len - "/9p".len]}) catch return -1; + const lock_path = std.fmt.bufPrintSentinel(&buf, "{s}/.post.lock", .{registry_dir[0 .. registry_dir.len - "/9p".len]}, 0) catch return -1; const fd: isize = @bitCast(linux.open(lock_path.ptr, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, 0o600)); if (rawErrno(fd) != .SUCCESS) return -1; const lfd: i32 = @intCast(fd); @@ -709,7 +709,7 @@ const Scratch = struct { s.dir = testing.tmpDir(.{}); errdefer s.dir.cleanup(); const len = try s.dir.dir.realPath(io, &s.path_buf); - const value = try std.fmt.bufPrintZ(&s.env_buf, "XDG_RUNTIME_DIR={s}", .{s.path_buf[0..len]}); + const value = try std.fmt.bufPrintSentinel(&s.env_buf, "XDG_RUNTIME_DIR={s}", .{s.path_buf[0..len]}, 0); s.env[0] = @ptrCast(value.ptr); s.env[1] = null; } @@ -735,7 +735,7 @@ test "post getenv: the block is scanned, keys match whole" { test "post legalName: traversal, empties and the socket budget" { try testing.expect(legalName("demo")); try testing.expect(legalName("...")); - try testing.expect(legalName("a" ** max_name_len)); + try testing.expect(legalName(&@as([max_name_len]u8, @splat('a')))); // Empty and dot names are not postable. try testing.expect(!legalName("")); try testing.expect(!legalName(".")); @@ -746,8 +746,8 @@ test "post legalName: traversal, empties and the socket budget" { try testing.expect(!legalName("..\x00..")); try testing.expect(!legalName("a\x00b")); // The name must fit a Unix socket path. - try testing.expect(!legalName("a" ** (max_name_len + 1))); - try testing.expect(!legalName("a" ** 255)); + try testing.expect(!legalName(&@as([max_name_len + 1]u8, @splat('a')))); + try testing.expect(!legalName(&@as([255]u8, @splat('a')))); } test "post registryPath: unset XDG is refused, no /tmp fallback" { @@ -773,7 +773,7 @@ test "post registryPath: shape, budget and caller buffer" { try testing.expectError(error.IllegalName, registryPath(e, "..", &buf)); // The 108-byte sockaddr budget, checked against the real prefix. const long_env = [_:null]?[*:0]const u8{"XDG_RUNTIME_DIR=/tmp/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}; - const name = "n" ** max_name_len; // legal against the 32-byte XDG budget + const name: []const u8 = &@as([max_name_len]u8, @splat('n')); // legal against the 32-byte XDG budget try testing.expectError(error.NameTooLong, registryPath(@ptrCast(&long_env), name, &buf)); // Too small a caller buffer is NoSpace, not a truncation. var tiny: [4]u8 = undefined; @@ -947,9 +947,9 @@ test "post names: a 255-byte entry stages and iterates (NAME_MAX)" { // A 255-byte name can never be a socket (108-byte budget), but an // attacker can drop one in the registry; the raw listing must carry // it without overflowing the staged `len:u8` record. - const fat = "z" ** 255; + const fat: []const u8 = &@as([255]u8, @splat('z')); var fat_buf: [std.fs.max_path_bytes]u8 = undefined; - const fat_path = try std.fmt.bufPrintZ(&fat_buf, "{s}/{s}", .{ reg, fat }); + const fat_path = try std.fmt.bufPrintSentinel(&fat_buf, "{s}/{s}", .{ reg, fat }, 0); { var f = try Io.Dir.createFileAbsolute(io, fat_path, .{}); f.close(io); @@ -974,10 +974,10 @@ test "post long name: max_name_len posts, probes, dials and unposts" { // scratch directory of its own. const io = testing.io; var xdg_buf: [64]u8 = undefined; - const xdg = try std.fmt.bufPrintZ(&xdg_buf, "/tmp/.p9t{d}", .{linux.getpid()}); + const xdg = try std.fmt.bufPrintSentinel(&xdg_buf, "/tmp/.p9t{d}", .{linux.getpid()}, 0); _ = try Io.Dir.createDirPathStatus(.cwd(), io, xdg, .fromMode(0o700)); var env_buf: [96]u8 = undefined; - const value = try std.fmt.bufPrintZ(&env_buf, "XDG_RUNTIME_DIR={s}", .{xdg}); + const value = try std.fmt.bufPrintSentinel(&env_buf, "XDG_RUNTIME_DIR={s}", .{xdg}, 0); const env = [2]?[*:0]const u8{ @ptrCast(value.ptr), null }; const envp: Env = @ptrCast(&env); var dbuf: [std.fs.max_path_bytes]u8 = undefined; @@ -987,7 +987,7 @@ test "post long name: max_name_len posts, probes, dials and unposts" { _ = linux.rmdir(xdg.ptr); } var pbuf: [sun_path_len]u8 = undefined; - const name = "l" ** max_name_len; + const name: []const u8 = &@as([max_name_len]u8, @splat('l')); try testing.expect(legalName(name)); var p = try post(io, envp, name, 4, &pbuf); try testing.expect(probe(p.path) == .live); @@ -996,7 +996,7 @@ test "post long name: max_name_len posts, probes, dials and unposts" { unpost(io, p.path, p.inode); p.server.deinit(io); // One past the cap is not even a path. - const too_long = "l" ** (max_name_len + 1); + const too_long: []const u8 = &@as([max_name_len + 1]u8, @splat('l')); try testing.expect(!legalName(too_long)); try testing.expectError(error.IllegalName, registryPath(envp, too_long, &pbuf)); } @@ -1021,7 +1021,7 @@ test "post watch: queue overflow surfaces, a deleted registry is gone" { var name_buf: [std.fs.max_path_bytes]u8 = undefined; const spam = 20000; for (0..spam) |i| { - const p = try std.fmt.bufPrintZ(&name_buf, "{s}/q{d}", .{ reg, i }); + const p = try std.fmt.bufPrintSentinel(&name_buf, "{s}/q{d}", .{ reg, i }, 0); var f = try Io.Dir.createFileAbsolute(io, p, .{}); f.close(io); } @@ -1049,7 +1049,7 @@ test "post watch: queue overflow surfaces, a deleted registry is gone" { _ = try Io.Dir.createDirPathStatus(.cwd(), io, reg, .fromMode(0o750)); try w.add(reg); { - var f = try Io.Dir.createFileAbsolute(io, try std.fmt.bufPrintZ(&name_buf, "{s}/back", .{reg}), .{}); + var f = try Io.Dir.createFileAbsolute(io, try std.fmt.bufPrintSentinel(&name_buf, "{s}/back", .{reg}, 0), .{}); f.close(io); } const back = try w.next(); @@ -1091,7 +1091,7 @@ test "post dialPath: refused, missing, non-socket, loop and a CLOEXEC stream" { // A live socket: dialPath yields a blocking, close-on-exec stream // (the mounted PROGRAM must not inherit a dialed descriptor). - const sock_path = try std.fmt.bufPrintZ(&path_buf, "{s}/live.sock", .{root}); + const sock_path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/live.sock", .{root}, 0); var server = try (try Io.net.UnixAddress.init(sock_path)).listen(io, .{}); { var st = try dialPath(io, sock_path); @@ -1104,13 +1104,13 @@ test "post dialPath: refused, missing, non-socket, loop and a CLOEXEC stream" { try testing.expectError(error.Stale, dialPath(io, sock_path)); // No entry at all. - try testing.expectError(error.NotPosted, dialPath(io, try std.fmt.bufPrintZ(&path_buf, "{s}/missing", .{root}))); + try testing.expectError(error.NotPosted, dialPath(io, try std.fmt.bufPrintSentinel(&path_buf, "{s}/missing", .{root}, 0))); // An entry that is not a socket answers the same ECONNREFUSED the // kernel gives a dead socket; the caller tells them apart by stat // before dialing (post.post does exactly that). - try testing.expectError(error.Stale, dialPath(io, try std.fmt.bufPrintZ(&path_buf, "{s}", .{root}))); - const file_path = try std.fmt.bufPrintZ(&path_buf, "{s}/plain", .{root}); + try testing.expectError(error.Stale, dialPath(io, try std.fmt.bufPrintSentinel(&path_buf, "{s}", .{root}, 0))); + const file_path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/plain", .{root}, 0); { var f = try Io.Dir.createFileAbsolute(io, file_path, .{}); f.close(io); @@ -1118,7 +1118,7 @@ test "post dialPath: refused, missing, non-socket, loop and a CLOEXEC stream" { try testing.expectError(error.Stale, dialPath(io, file_path)); // A symlink loop is its own error, not a missing entry. - const loop_path = try std.fmt.bufPrintZ(&path_buf, "{s}/loop", .{root}); + const loop_path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/loop", .{root}, 0); try Io.Dir.symLinkAbsolute(io, loop_path, loop_path, .{}); try testing.expectError(error.SymLinkLoop, dialPath(io, loop_path)); } @@ -1132,12 +1132,12 @@ test "post postedDir: a 1000-entry directory lists fully or refuses cleanly" { var real_buf: [std.fs.max_path_bytes]u8 = undefined; const rlen = try s.dir.dir.realPath(io, &real_buf); var dir_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = try std.fmt.bufPrintZ(&dir_buf, "{s}", .{real_buf[0..rlen]}); + const dir = try std.fmt.bufPrintSentinel(&dir_buf, "{s}", .{real_buf[0..rlen]}, 0); for (0..1000) |i| { var name_buf: [32]u8 = undefined; var path_buf: [std.fs.max_path_bytes]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "e{d:0>4}", .{i}); - var f = try Io.Dir.createFileAbsolute(io, try std.fmt.bufPrintZ(&path_buf, "{s}/{s}", .{ dir, name }), .{}); + var f = try Io.Dir.createFileAbsolute(io, try std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dir, name }, 0), .{}); f.close(io); } // A staging buffer that cannot hold every record is an explicit diff --git a/src/quic.zig b/src/quic.zig index c78a79d..c372e0a 100644 --- a/src/quic.zig +++ b/src/quic.zig @@ -248,7 +248,7 @@ pub fn Quic(comptime ssl: type, comptime protocol: []const u8) type { switch (address) { .ip4 => |ip| { const addr: *libc.sockaddr.in = @ptrCast(out); - addr.* = .{ .port = std.mem.nativeToBig(u16, ip.port), .addr = @bitCast(ip.bytes) }; + addr.* = .{ .port = std.mem.nativeToBig(u16, ip.port), .addr = std.mem.bytesToValue(u32, &ip.bytes) }; return @sizeOf(libc.sockaddr.in); }, .ip6 => |ip| { diff --git a/src/serve.zig b/src/serve.zig index 5166b5f..ad774a3 100644 --- a/src/serve.zig +++ b/src/serve.zig @@ -1126,7 +1126,7 @@ test "serve: listenPosted serves the registry name and stop() unposts" { var real_buf: [std.fs.max_path_bytes]u8 = undefined; const len = try rig.dir.dir.realPath(io, &real_buf); var env_buf: [std.fs.max_path_bytes]u8 = undefined; - const value = try std.fmt.bufPrintZ(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..len]}); + const value = try std.fmt.bufPrintSentinel(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..len]}, 0); const env = [2]?[*:0]const u8{ @ptrCast(value.ptr), null }; const envp: post.Env = @ptrCast(&env); @@ -1171,7 +1171,7 @@ test "serve: a second listenPosted is refused; stop() never unposts another's na var real_buf: [std.fs.max_path_bytes]u8 = undefined; const len = try rig.dir.dir.realPath(io, &real_buf); var env_buf: [std.fs.max_path_bytes]u8 = undefined; - const value = try std.fmt.bufPrintZ(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..len]}); + const value = try std.fmt.bufPrintSentinel(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..len]}, 0); const env = [2]?[*:0]const u8{ @ptrCast(value.ptr), null }; const envp: post.Env = @ptrCast(&env); @@ -1209,7 +1209,7 @@ test "serve: listenPosted beside listen(): stop unposts only the registry name" var real_buf: [std.fs.max_path_bytes]u8 = undefined; const len = try rig.dir.dir.realPath(io, &real_buf); var env_buf: [std.fs.max_path_bytes]u8 = undefined; - const value = try std.fmt.bufPrintZ(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..len]}); + const value = try std.fmt.bufPrintSentinel(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..len]}, 0); const env = [2]?[*:0]const u8{ @ptrCast(value.ptr), null }; const envp: post.Env = @ptrCast(&env); @@ -1218,7 +1218,7 @@ test "serve: listenPosted beside listen(): stop unposts only the registry name" // A plain Unix listener (the application's path policy) beside the // posted name: both listener slots fill. var unix_buf: [std.fs.max_path_bytes]u8 = undefined; - const unix_path = try std.fmt.bufPrintZ(&unix_buf, "{s}/plain.sock", .{real_buf[0..len]}); + const unix_path = try std.fmt.bufPrintSentinel(&unix_buf, "{s}/plain.sock", .{real_buf[0..len]}, 0); _ = try rig.runner.listen(.{ .unix = unix_path }, 4); try rig.runner.listenPosted(envp, "mixed", 4); @@ -1419,7 +1419,7 @@ test "serve: every descriptor opened by the post/serve path is close-on-exec" { var real_buf: [std.fs.max_path_bytes]u8 = undefined; const rlen = try dir.dir.realPath(io, &real_buf); var env_buf: [std.fs.max_path_bytes]u8 = undefined; - const value = try std.fmt.bufPrintZ(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..rlen]}); + const value = try std.fmt.bufPrintSentinel(&env_buf, "XDG_RUNTIME_DIR={s}", .{real_buf[0..rlen]}, 0); const env = [2]?[*:0]const u8{ @ptrCast(value.ptr), null }; const envp: post.Env = @ptrCast(&env); diff --git a/src/transport.zig b/src/transport.zig index d7619be..c75aa3b 100644 --- a/src/transport.zig +++ b/src/transport.zig @@ -67,7 +67,7 @@ pub fn ipSockaddr(ip: std.Io.net.IpAddress, out: *libc.sockaddr.storage) libc.so return switch (ip) { .ip4 => |a| blk: { const addr: *libc.sockaddr.in = @ptrCast(out); - addr.* = .{ .port = std.mem.nativeToBig(u16, a.port), .addr = @bitCast(a.bytes) }; + addr.* = .{ .port = std.mem.nativeToBig(u16, a.port), .addr = std.mem.bytesToValue(u32, &a.bytes) }; break :blk @sizeOf(libc.sockaddr.in); }, .ip6 => |a| blk: { diff --git a/src/wire.zig b/src/wire.zig index e093450..05bc32c 100644 --- a/src/wire.zig +++ b/src/wire.zig @@ -45,7 +45,7 @@ pub const Type = enum(u8) { }; pub fn isT(t: Type) bool { - return @intFromEnum(t) % 2 == 0; + return @backingInt(t) % 2 == 0; } pub const header_len: usize = 4 + 1 + 2; @@ -85,7 +85,7 @@ comptime { assert(qid_len == 13); assert(stat_fixed == 49); for (std.enums.values(Type)) |t| { - const even = @intFromEnum(t) % 2 == 0; + const even = @backingInt(t) % 2 == 0; assert(isT(t) == even); assert(std.mem.startsWith(u8, @tagName(t), if (even) "t" else "r")); } @@ -320,7 +320,7 @@ pub fn encode(msg: Msg, tag: u16, buf: []u8) Error![]u8 { var w: Writer = .init(buf[0..total]); try w.putU32(@intCast(total)); - try w.putByte(@intFromEnum(msg.msgType())); + try w.putByte(@backingInt(msg.msgType())); try w.putU16(tag); switch (msg) { @@ -420,7 +420,7 @@ pub fn decode(bytes: []const u8) Error!Decoded { if (size > bytes.len) return error.Truncated; if (size < bytes.len) return error.Trailing; - const t: Type = @enumFromInt(bytes[4]); + const t: Type = @fromBackingInt(@intCast(bytes[4])); const tag = std.mem.readInt(u16, bytes[5..7], .little); var r: Reader = .init(bytes[header_len..size]); @@ -724,14 +724,14 @@ const sample_stat: Stat = .{ }; test "9p: the type numbers and their parity are the protocol's own" { - try testing.expectEqual(@as(u8, 100), @intFromEnum(Type.tversion)); - try testing.expectEqual(@as(u8, 106), @intFromEnum(Type.terror)); - try testing.expectEqual(@as(u8, 107), @intFromEnum(Type.rerror)); - try testing.expectEqual(@as(u8, 126), @intFromEnum(Type.twstat)); - try testing.expectEqual(@as(u8, 127), @intFromEnum(Type.rwstat)); + try testing.expectEqual(@as(u8, 100), @backingInt(Type.tversion)); + try testing.expectEqual(@as(u8, 106), @backingInt(Type.terror)); + try testing.expectEqual(@as(u8, 107), @backingInt(Type.rerror)); + try testing.expectEqual(@as(u8, 126), @backingInt(Type.twstat)); + try testing.expectEqual(@as(u8, 127), @backingInt(Type.rwstat)); try testing.expectEqual(@as(usize, 28), std.enums.values(Type).len); - for (std.enums.values(Type), 100..) |t, want| try testing.expectEqual(@as(u8, @intCast(want)), @intFromEnum(t)); + for (std.enums.values(Type), 100..) |t, want| try testing.expectEqual(@as(u8, @intCast(want)), @backingInt(t)); try testing.expect(isT(.tversion)); try testing.expect(!isT(.rversion)); @@ -814,8 +814,8 @@ test "9p: every message round-trips" { _ = try roundTrip(&buf, 13, .{ .twstat = .{ .fid = 1, .stat = sample_stat } }); _ = try roundTrip(&buf, 13, .rwstat); - try testing.expectEqual(@as(usize, 27), @typeInfo(Msg).@"union".fields.len); - try testing.expectEqual(std.enums.values(Type).len - 1, @typeInfo(Msg).@"union".fields.len); + try testing.expectEqual(@as(usize, 27), @typeInfo(Msg).@"union".field_names.len); + try testing.expectEqual(std.enums.values(Type).len - 1, @typeInfo(Msg).@"union".field_names.len); } test "9p: empty and maximum-length strings survive the trip" { @@ -862,7 +862,7 @@ test "9p: Twalk carries 0, 1 and 16 elements and refuses 17" { const bad = blk: { var w: Writer = .init(&raw); try w.putU32(0); // patched below - try w.putByte(@intFromEnum(Type.twalk)); + try w.putByte(@backingInt(Type.twalk)); try w.putU16(1); try w.putU32(0); try w.putU32(1); @@ -877,7 +877,7 @@ test "9p: Twalk carries 0, 1 and 16 elements and refuses 17" { const bad_r = blk: { var w: Writer = .init(&raw); try w.putU32(0); - try w.putByte(@intFromEnum(Type.rwalk)); + try w.putByte(@backingInt(Type.rwalk)); try w.putU16(1); try w.putU16(17); for (0..17) |_| try w.putQid(sample_qid); @@ -1003,13 +1003,13 @@ test "9p: an unknown or illegal type byte is refused" { var t: u16 = 0; while (t <= 255) : (t += 1) { raw[4] = @intCast(t); - const defined = t >= 100 and t <= 127 and t != @intFromEnum(Type.terror); + const defined = t >= 100 and t <= 127 and t != @backingInt(Type.terror); if (decode(raw[0..bytes.len])) |got| { - try testing.expectEqual(@as(u8, @intCast(t)), @intFromEnum(got.msg.msgType())); - try testing.expect(t == @intFromEnum(Type.tclunk) or - t == @intFromEnum(Type.tremove) or - t == @intFromEnum(Type.tstat) or - t == @intFromEnum(Type.rwrite)); + try testing.expectEqual(@as(u8, @intCast(t)), @backingInt(got.msg.msgType())); + try testing.expect(t == @backingInt(Type.tclunk) or + t == @backingInt(Type.tremove) or + t == @backingInt(Type.tstat) or + t == @backingInt(Type.rwrite)); } else |err| { if (!defined) try testing.expectEqual(Error.BadTag, err); } @@ -1021,7 +1021,7 @@ test "9p: trailing bytes inside the size are refused" { var w: Writer = .init(&raw); try w.putU32(12); - try w.putByte(@intFromEnum(Type.tclunk)); + try w.putByte(@backingInt(Type.tclunk)); try w.putU16(1); try w.putU32(7); try w.putByte(0xAA); @@ -1030,7 +1030,7 @@ test "9p: trailing bytes inside the size are refused" { w = .init(&raw); try w.putU32(header_len + 2 + 2); - try w.putByte(@intFromEnum(Type.tflush)); + try w.putByte(@backingInt(Type.tflush)); try w.putU16(1); try w.putU16(3); try w.putU16(3); diff --git a/web/main.zig b/web/main.zig index 7222d91..130ed4b 100644 --- a/web/main.zig +++ b/web/main.zig @@ -95,7 +95,7 @@ fn parseUpstream(allocator: std.mem.Allocator, text: []const u8) !mux.Address { if (std.mem.startsWith(u8, text, "tcp:")) return .{ .network = .{ .tcp = try Io.net.IpAddress.parseLiteral(text[4..]) } }; if (std.mem.startsWith(u8, text, "unix:")) - return .{ .network = .{ .unix = try allocator.dupeZ(u8, text[5..]) } }; + return .{ .network = .{ .unix = try allocator.dupeSentinel(u8, text[5..], 0) } }; if (std.mem.startsWith(u8, text, "file:")) return .{ .file = text[5..] }; return error.InvalidUpstream; @@ -105,7 +105,7 @@ fn parseServe(allocator: std.mem.Allocator, text: []const u8) !c9.transport.Addr if (std.mem.startsWith(u8, text, "tcp:")) return .{ .tcp = try Io.net.IpAddress.parseLiteral(text[4..]) }; if (std.mem.startsWith(u8, text, "unix:")) - return .{ .unix = try allocator.dupeZ(u8, text[5..]) }; + return .{ .unix = try allocator.dupeSentinel(u8, text[5..], 0) }; return error.InvalidServe; } |
