diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-23 11:00:44 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-23 17:10:58 -0300 |
| commit | 80314064f6e81c8828340e010202b446f0e1f36d (patch) | |
| tree | aa56e86238ac9397055f601db924868bb6511538 /src | |
| parent | a53a1aafb9804e943bdcd720c2bb688ecb90a888 (diff) | |
| download | pardes-80314064f6e81c8828340e010202b446f0e1f36d.tar.gz pardes-80314064f6e81c8828340e010202b446f0e1f36d.zip | |
Audit (misc): std mkdir -p and JSON escaping, a 9P late failure's errno from ctl.failureErrno, dead switches and dumpHex out
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src')
| -rw-r--r-- | src/9p_io.zig | 112 | ||||
| -rw-r--r-- | src/File.zig | 5 | ||||
| -rw-r--r-- | src/Output.zig | 52 | ||||
| -rw-r--r-- | src/builtins.zig | 86 | ||||
| -rw-r--r-- | src/builtins_json.zig | 22 | ||||
| -rw-r--r-- | src/config.zig | 75 | ||||
| -rw-r--r-- | src/dump.zig | 11 | ||||
| -rw-r--r-- | src/esp32p4/uart.zig | 16 | ||||
| -rw-r--r-- | src/fs.zig | 12 | ||||
| -rw-r--r-- | src/gui/gui.zig | 13 | ||||
| -rw-r--r-- | src/hunks.zig | 6 | ||||
| -rw-r--r-- | src/locations.zig | 25 | ||||
| -rw-r--r-- | src/look.zig | 8 | ||||
| -rw-r--r-- | src/main.zig | 40 | ||||
| -rw-r--r-- | src/syntax.zig | 5 | ||||
| -rw-r--r-- | src/tagline.zig | 7 | ||||
| -rw-r--r-- | src/terminal.zig | 4 | ||||
| -rw-r--r-- | src/web.zig | 59 |
18 files changed, 156 insertions, 402 deletions
diff --git a/src/9p_io.zig b/src/9p_io.zig index a825475f..a089a7cf 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -11,10 +11,7 @@ const quic = if (quic_enabled) @import("9p_quic.zig") else struct {}; const log = std.log.scoped(.ninep); -pub const darwin = switch (builtin.os.tag) { - .macos, .ios, .tvos, .watchos, .visionos => true, - else => false, -}; +pub const darwin = builtin.os.tag.isDarwin(); pub const supported = builtin.os.tag == .linux or darwin; pub const sun_path_len = @typeInfo(@FieldType(libc.sockaddr.un, "path")).array.len; @@ -47,15 +44,8 @@ pub fn statNoFollow(path: [:0]const u8) ?FileFacts { pub fn ensureSocketDir(dir: [:0]const u8) bool { if (dir.len == 0) return false; - var partial: [sun_path_len:0]u8 = undefined; - @memcpy(partial[0 .. dir.len + 1], dir[0 .. dir.len + 1]); - for (1..dir.len) |i| { - if (dir[i] != '/') continue; - partial[i] = 0; - _ = libc.mkdir(partial[0..i :0], 0o700); - partial[i] = '/'; - } - _ = libc.mkdir(dir, 0o700); + // A failure shows in the stat below. + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o700)) catch {}; const stat = statNoFollow(dir) orelse return false; return stat.mode & 0o170000 == 0o040000 and stat.uid == libc.getuid() and stat.mode & 0o077 == 0; } @@ -394,11 +384,11 @@ pub const Listener = struct { // settle in the same wait is told to this write too. if (l.core == core and core.fs.late_failure_len != 0) { const late = core.fs.late_failure[0..core.fs.late_failure_len]; - // What is not there (`no such directory`) is ENOENT, as a - // builtin's failure saying so is (ctl.failureErrno). - const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) - pardes.ctlfs.E.NOENT - else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else if (std.mem.indexOf(u8, late, "permission denied") != null) pardes.ctlfs.E.PERM else if (std.mem.indexOf(u8, late, "invalid") != null) pardes.ctlfs.E.INVAL else pardes.ctlfs.E.IO; + // The errno a builtin's failure in the same words has; what + // that leaves EIO and says `no space` (a full disk under a + // Save) is ENOSPC. + const said = @import("ninep/ctl.zig").failureErrno(late); + const errno = if (said == pardes.ctlfs.E.IO and std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else said; const failed = pardes.ctlfs.failText(req.tag, errno, late); // Its err record says it (the path in it), the one record: it // was said with no msg while this waited (fs.write_waits). @@ -1017,21 +1007,11 @@ fn onFatalSignal(s: std.posix.SIG) callconv(.c) void { pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { if (comptime !supported) return; var names: [8192]u8 = undefined; - var staged: usize = 0; - { - const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return; - defer d.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(d, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (deadSocketPid(listed.name) == null) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; + const staged = stageNames(io, dir, &names, struct { + fn keep(name: []const u8) bool { + return deadSocketPid(name) != null; } - } + }.keep); var i: usize = 0; while (i < staged) { const name = names[i + 1 ..][0..names[i]]; @@ -1048,6 +1028,28 @@ pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { } } +/// The names in `dir` that `keep` takes (all with none), into `names` as a length byte and +/// the name each, until it is full; the bytes staged. They are staged +/// before anything is unlinked, so a sweep never asks a directory to keep +/// reading while it is being edited. +fn stageNames(io: std.Io, dir: [:0]const u8, names: []u8, comptime keep: ?fn ([]const u8) bool) usize { + const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return 0; + defer d.close(io); + var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; + var reader: std.Io.Dir.Reader = .init(d, &read_buf); + var staged: usize = 0; + while (true) { + const listed = (reader.next(io) catch break) orelse break; + if (listed.name.len == 0 or listed.name.len > 255) continue; + if (keep) |takes| if (!takes(listed.name)) continue; + if (staged + 1 + listed.name.len > names.len) break; + names[staged] = @intCast(listed.name.len); + @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); + staged += 1 + listed.name.len; + } + return staged; +} + /// The pid a `pardes-9p-<pid>.sock` name carries, or null for any other. fn deadSocketPid(name: []const u8) ?std.c.pid_t { if (!std.mem.startsWith(u8, name, prefix) or !std.mem.endsWith(u8, name, ".sock")) return null; @@ -1279,24 +1281,8 @@ fn ourSocket(target: []const u8, sockets: []const u8) bool { fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void { if (comptime !supported) return; - // The names are staged before anything is unlinked, so the sweep - // never asks a directory to keep reading while it is being edited. var names: [4096]u8 = undefined; - var staged: usize = 0; - { - const dir = std.Io.Dir.openDirAbsolute(io, svc, .{ .iterate = true }) catch return; - defer dir.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(dir, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (listed.name.len == 0 or listed.name.len > 255) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; - } - } + const staged = stageNames(io, svc, &names, null); var reaped: usize = 0; var i: usize = 0; @@ -2179,10 +2165,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - return fetchBytes(gpa, sock, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { + return fetchBytes(gpa, dial, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2209,10 +2193,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const result = fetchBytes(gpa, sock, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { + const result = fetchBytes(gpa, dial, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2470,7 +2452,7 @@ pub const Client = struct { fn fetchBytes( gpa: std.mem.Allocator, - sock: Dial, + dial: []const u8, names: []const []const u8, remote: *RemoteError, write_bytes: ?[]const u8, @@ -2478,7 +2460,7 @@ pub const Client = struct { read_limit: usize, ) ![]u8 { if (comptime !supported) return Error.Dial; - const s = try startSession(gpa, sock, display_path); + const s = try startSession(gpa, dial, display_path); defer endSession(gpa, s); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); @@ -2486,8 +2468,10 @@ pub const Client = struct { return out.toOwnedSlice(); } - /// A connected session whose requests have the usual deadline. - fn startSession(gpa: std.mem.Allocator, sock: Dial, display_path: []const u8) !*Session { + /// A connected session at `dial` whose requests have the usual deadline. + fn startSession(gpa: std.mem.Allocator, dial: []const u8, display_path: []const u8) !*Session { + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); const deadline = nowMs() +| budget_ms; const s = try gpa.create(Session); s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; @@ -2518,11 +2502,9 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; errdefer said = remote; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2562,10 +2544,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2642,7 +2622,7 @@ pub const Client = struct { const before = nowMs(); try testing.expectError( Error.Dial, - fetchBytes(testing.allocator, .{ .unix = "/tmp/pardes-9p-no-such-socket.sock" }, names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), + fetchBytes(testing.allocator, "/tmp/pardes-9p-no-such-socket.sock", names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), ); try testing.expect(nowMs() - before < budget_ms); } diff --git a/src/File.zig b/src/File.zig index e92efaba..b1a4271f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2153,15 +2153,14 @@ pub const DiffOutput = struct { text[at] = '\n'; at += 1; } + // An empty slot, else the least recently used. var oldest: usize = 0; for (&o.slots, 0..) |*slot, i| { const e = slot.* orelse { oldest = i; break; }; - if (o.slots[oldest]) |old| if (e.used < old.used) { - oldest = i; - }; + if (e.used < o.slots[oldest].?.used) oldest = i; } if (o.slots[oldest]) |old| { p.gpa.free(old.text); diff --git a/src/Output.zig b/src/Output.zig index 3fc08d9a..9a11b2fc 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -949,51 +949,23 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { "C-left-click definition, by mouse\n" ++ "SPC l ... hover, rename, symbols,\n" ++ " calls, types: above\n"; - var len: usize = if (prefix.len == 0) - full_header.len + language_footer.len - else - group_header.len + prefix.len * 2 + 2; - if (show_calls_help) len += calls_help.len; + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + if (prefix.len == 0) try w.writeAll(full_header) else { + try w.writeAll(group_header); + for (prefix) |c| try w.print(" {c}", .{c}); + try w.writeAll("\n\n"); + } for (pardes.builtin_rows) |row| { // a path-less builtin filters as the empty path: in the full listing // (which starts with nothing) and out of every group if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - len += row.line.len + 1; - } - const content = try gpa.alloc(u8, len); - var at: usize = 0; - if (prefix.len == 0) { - @memcpy(content[0..full_header.len], full_header); - at = full_header.len; - } else { - @memcpy(content[0..group_header.len], group_header); - at = group_header.len; - for (prefix) |c| { - content[at] = ' '; - content[at + 1] = c; - at += 2; - } - content[at] = '\n'; - content[at + 1] = '\n'; - at += 2; - } - for (pardes.builtin_rows) |row| { - if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - @memcpy(content[at..][0..row.line.len], row.line); - at += row.line.len; - content[at] = '\n'; - at += 1; - } - if (show_calls_help) { - @memcpy(content[at..][0..calls_help.len], calls_help); - at += calls_help.len; - } - if (prefix.len == 0) { - @memcpy(content[at..][0..language_footer.len], language_footer); - at += language_footer.len; + try w.print("{s}\n", .{row.line}); } - std.debug.assert(at == content.len); - return content; + if (show_calls_help) try w.writeAll(calls_help); + if (prefix.len == 0) try w.writeAll(language_footer); + return out.toOwnedSlice(); } pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { diff --git a/src/builtins.zig b/src/builtins.zig index 7b1541ac..64710554 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -109,54 +109,27 @@ pub fn absentWhy(name: []const u8) ?[]const u8 { return null; } -fn manualBuiltinCount() comptime_int { +fn manualBuiltinList() []const type { comptime { - var count = 0; + @setEvalBranchQuota(4000); + var list: []const type = &.{}; for (@typeInfo(@This()).@"struct".decl_names) |d| { if (@TypeOf(@field(@This(), d)) != type) continue; const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; if (@TypeOf(T.run) != fn (Ctx) void) @compileError(d ++ ".run must have signature fn (Ctx) void"); - count += 1; - } - return count; - } -} - -fn manualBuiltinList() [manualBuiltinCount()]type { - comptime { - @setEvalBranchQuota(4000); - var list: [manualBuiltinCount()]type = undefined; - var count = 0; - for (@typeInfo(@This()).@"struct".decl_names) |d| { - if (@TypeOf(@field(@This(), d)) != type) continue; - const T = @field(@This(), d); - if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; - list[count] = T; - count += 1; + list = list ++ .{T}; } return list; } } -fn settingCount() comptime_int { +fn settingList() []const config.Runtime.Setting { comptime { - var count = 0; + var list: []const config.Runtime.Setting = &.{}; for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - count += 1; - }; - return count; - } -} - -fn settingList() [settingCount()]config.Runtime.Setting { - comptime { - var list: [settingCount()]config.Runtime.Setting = undefined; - var count = 0; - for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - list[count] = setting; - count += 1; + list = list ++ .{setting}; }; return list; } @@ -197,11 +170,17 @@ pub const registry = struct { return @Enum(Tag, .exhaustive, &names, &std.simd.iota(Tag, count)); } + /// What a hand-written builtin says as `name` (`pub const takes_arg = + /// true;`), `default` when it says nothing, and `setting` for a setting. + fn declOr(b: Builtin(), comptime name: []const u8, default: anytype, setting: @TypeOf(default)) @TypeOf(default) { + inline for (comptime manualBuiltinList(), 0..) |T, i| + if (@backingInt(b) == i) return if (@hasDecl(T, name)) @field(T, name) else default; + return setting; + } + pub fn takesArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; // Every setting takes its value, and a switch flips when bare. - return true; + return declOr(b, "takes_arg", false, true); } /// Whether the word takes its argument joined by a `+` as one word a @@ -209,9 +188,7 @@ pub const registry = struct { /// that says `pub const plus_arg = true;`: others have arguments a `+` /// may be in (`Dump+2024.zon` is a name, not Dump's argument). pub fn plusArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; - return false; + return declOr(b, "plus_arg", false, false); } /// Whether the word means nothing without its argument (`Mount`, @@ -222,15 +199,11 @@ pub const registry = struct { /// it says `pub const needs: PaneKind = .terminal;`, and on any other /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. pub fn needs(b: Builtin()) ?PaneKind { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; - return null; + return declOr(b, "needs", @as(?PaneKind, null), null); } pub fn requiresArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default @@ -239,35 +212,28 @@ pub const registry = struct { // bare, it says the current value (exec.applySettingBuiltin) .tab, .callstack_depth => false, }; - unreachable; + return declOr(b, "requires_arg", false, false); } pub fn scope(b: Builtin()) Scope { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; - return .session; // a setting + return declOr(b, "scope", Scope.pane, .session); } pub fn outputTraits(b: Builtin()) ?OutputTraits { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "output")) T.output else null; - inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@backingInt(b) == i) return null; - unreachable; + return declOr(b, "output", @as(?OutputTraits, null), null); } /// Does this builtin say its own name on the message row before it runs? /// The ones that own that row themselves declare `quiet` and do not. pub fn announces(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); - return true; // a setting builtin changes something invisible; say so + // a setting builtin changes something invisible; say so + return !declOr(b, "quiet", false, false); } pub fn dispatch(b: Builtin(), c: Ctx) void { - inline for (manualBuiltinList(), 0..) |T, i| + inline for (comptime manualBuiltinList(), 0..) |T, i| if (@backingInt(b) == i) return T.run(c); - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } diff --git a/src/builtins_json.zig b/src/builtins_json.zig index 7f998388..4440130d 100644 --- a/src/builtins_json.zig +++ b/src/builtins_json.zig @@ -11,17 +11,7 @@ const builtins = @import("builtins.zig"); const config = @import("config.zig"); const ctl = @import("ninep/ctl.zig"); -fn str(w: *std.Io.Writer, s: []const u8) !void { - try w.writeByte('"'); - for (s) |c| switch (c) { - '"' => try w.writeAll("\\\""), - '\\' => try w.writeAll("\\\\"), - '\n' => try w.writeAll("\\n"), - 0...9, 11...0x1f => try w.print("\\u{x:0>4}", .{c}), - else => try w.writeByte(c), - }; - try w.writeByte('"'); -} +const str = std.json.Stringify.encodeJsonString; const Entry = struct { name: []const u8, row: usize }; @@ -39,7 +29,7 @@ pub fn write(w: *std.Io.Writer) !void { const b = row.cmd; const name = @tagName(b); try w.writeAll(" {\"name\": "); - try str(w, name); + try str(name, .{}, w); try w.writeAll(", \"leader\": "); if (row.path) |p| { try w.writeAll("\"SPC"); @@ -55,21 +45,21 @@ pub fn write(w: *std.Io.Writer) !void { while (parts.next()) |part| if (part.len > 0) { if (!first) try w.writeAll(", "); first = false; - try str(w, part); + try str(part, .{}, w); }; try w.writeAll("], \"arg\": "); try w.writeAll(if (builtins.registry.takesArg(b)) "true" else "false"); try w.writeAll(", \"scope\": "); - try str(w, if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane"); + try str(if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane", .{}, w); const setting = config.Runtime.find(name); try w.writeAll(", \"setting\": "); try w.writeAll(if (setting != null) "true" else "false"); try w.writeAll(", \"choices\": "); - if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(w, v) else try w.writeAll("null") else try w.writeAll("null"); + if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(v, .{}, w) else try w.writeAll("null") else try w.writeAll("null"); var buf: [2048]u8 = undefined; const doc = if (setting) |s| s.doc else ctl.summaryOf(name, &buf); try w.writeAll(", \"doc\": "); - try str(w, doc); + try str(doc, .{}, w); try w.writeAll(if (n + 1 < order.len) "},\n" else "}\n"); } try w.writeAll("]\n"); diff --git a/src/config.zig b/src/config.zig index 5251b1e5..1fbf0d1b 100644 --- a/src/config.zig +++ b/src/config.zig @@ -293,9 +293,6 @@ pub const back_out: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; -// OSC 133 prompt cells are hidden in normal mode; input columns stay intact. -pub const tty_blank: enum { prompt, prompt_and_input } = .prompt; - // Projected colors below this contrast use the theme's more legible anchor. pub const tty_filter_min_contrast: f64 = 1.5; @@ -386,9 +383,6 @@ pub const gui_topbar_pane_border_px: u8 = 1; // null follows the theme's scrollbar track. pub const gui_topbar_pane_border_rgb: ?[3]u8 = null; -// Transparency requires the SDL readback/blit path, even with an opaque theme. -pub const gui_transparent: bool = false; - // A vertical wheel tick suppresses this many subsequent horizontal ticks. pub const wheel_guard_ticks: u8 = 3; @@ -1428,12 +1422,12 @@ pub const Runtime = struct { /// effect but set by no word follows, after a blank line. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; - for (settings) |setting| switch (setting.action) { + // TaglineSize is said wherever the shell sizes its tag, by its word + // or only at build time. + for (settings) |setting| if (!(if (setting.action == .tagline_size) context.capabilities.tagline_font_size else setting.enabled(context.capabilities))) + try out.print("# {s} unsupported\n", .{setting.word}) + else switch (setting.action) { .toggle => |field| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const value = switch (field) { inline else => |f| @field(state, @tagName(f)), }; @@ -1443,18 +1437,8 @@ pub const Runtime = struct { try out.print("ThemeFile {s}\n", .{path}) else try out.print("{s} {s}\n", .{ setting.word, context.theme_name }), - .window_opacity => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, - .window_blur => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_blur }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, + .window_opacity => try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }), + .window_blur => try out.print("{s} {d}\n", .{ setting.word, state.window_blur }), .dump_dir => { const dir = if (state.dump_dir.len > 0) state.dump_dir.get() else context.default_dump_dir; if (dir.len > 0) try out.print("{s} {s}\n", .{ setting.word, dir }) else try out.print("# {s} (none)\n", .{setting.word}); @@ -1466,9 +1450,7 @@ pub const Runtime = struct { const chosen = state.shell.requested.get(); try out.print("{s} {s}\n", .{ setting.word, if (chosen.len == 0) context.compiled_default_shell else chosen }); }, - .font => if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else { + .font => { // As `Font` takes it, `name:size`: the one asked for, else // the one in use. const f = &state.font; @@ -1483,28 +1465,14 @@ pub const Runtime = struct { if (f.requested_size_hundredths != 0) try out.print(":{d}.{d:0>2}", .{ f.requested_size_hundredths / 100, f.requested_size_hundredths % 100 }); try out.writeByte('\n'); }, - .tagline_size => if (!context.capabilities.tagline_font_size) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), + .tagline_size => try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), // Each a switch of its own, the one in use on. - .transition => |transition| if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), + .transition => |transition| try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), .scene => |effect| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const level = state.post.level(effect); if (level == 0) try out.print("{s} off\n", .{setting.word}) else try out.print("{s} {d}\n", .{ setting.word, level }); }, .shader => { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } var files: usize = 0; for (state.post.list()) |entry| if (entry.scene == null) { try out.print("{s} {s}\n", .{ setting.word, entry.path.get() }); @@ -1512,25 +1480,16 @@ pub const Runtime = struct { }; if (files == 0) try out.print("{s} off\n", .{setting.word}); }, - .shader_animation => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .shader_animation => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }), .choice => |which| switch (which) { inline else => |field| try out.print("{s} {s}\n", .{ setting.word, @tagName(@field(state, @tagName(field))) }), }, - .lift => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .lift => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }), .motion => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.motion) }), .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), - .grip_width => if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.grip_width }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1566,14 +1525,6 @@ pub const Runtime = struct { try out.print("# Pet: {s}\n", .{@tagName(state.pet)}); } - test "setting names are unique" { - for (settings, 0..) |setting, i| { - try std.testing.expect(setting.word.len > 0); - for (settings[i + 1 ..]) |later| - try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); - } - } - test "panel and scene effects flip bare and are set by on and off" { var state: Runtime = .{}; const slide = findAction(.{ .transition = .slide }).?; diff --git a/src/dump.zig b/src/dump.zig index 67934e0a..c8c302ab 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -38,16 +38,7 @@ pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; var dir_buf: [900]u8 = undefined; const dir = directory(&dir_buf, dir_setting) orelse return null; - var dz: [901:0]u8 = undefined; - @memcpy(dz[0..dir.len], dir); - dz[dir.len] = 0; - // Each missing directory on the way, as `mkdir -p`: EEXIST is fine. - for (dz[1..dir.len], 1..) |c, i| if (c == '/') { - dz[i] = 0; - _ = std.c.mkdir(dz[0..i :0], 0o755); - dz[i] = '/'; - }; - _ = std.c.mkdir(dz[0..dir.len :0], 0o755); + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; var ts: std.c.timespec = undefined; _ = std.c.clock_gettime(.REALTIME, &ts); const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) }; diff --git a/src/esp32p4/uart.zig b/src/esp32p4/uart.zig index 5690520c..a185737d 100644 --- a/src/esp32p4/uart.zig +++ b/src/esp32p4/uart.zig @@ -126,22 +126,6 @@ pub fn writeByte(b: u8) void { uart0.pushByte(b); } -/// Emit `n` bytes read from `addr` as two hex digits each, computing the digits arithmetically so -/// nothing here reads a lookup table. Used to answer "does a load from this address return what the -/// linker put there", which is not a question a string literal can be trusted to ask. -pub fn dumpHex(addr: u32, n: u32) void { - const p: [*]const volatile u8 = @ptrFromInt(addr); - var i: u32 = 0; - while (i < n) : (i += 1) { - const byte = p[i]; - for ([2]u8{ byte >> 4, byte & 0xf }) |nib| { - writeByte(if (nib < 10) '0' + nib else 'a' + (nib - 10)); - } - } - writeByte('\r'); - writeByte('\n'); -} - /// A u32 as eight hex digits, reading no memory at all. pub fn dumpWord(v: u32) void { var shift: u5 = 28; @@ -686,18 +686,10 @@ test "a path with a part over 255 bytes is NameTooLong, never a panic" { /// that follows. pub fn makeDirs(dir: []const u8) void { if (comptime !platform_has_fs) return; - var z: [4096:0]u8 = undefined; - if (dir.len == 0 or dir.len >= z.len) return; - @memcpy(z[0..dir.len], dir); - z[dir.len] = 0; + if (dir.len == 0) return; pardes.turn.yield(); defer pardes.turn.back(); - for (z[1..dir.len], 1..) |c, i| if (c == '/') { - z[i] = 0; - _ = libc.mkdir(z[0..i :0], 0o755); - z[i] = '/'; - }; - _ = libc.mkdir(z[0..dir.len :0], 0o755); + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; } /// Whether `dir` is not there to make because one above it refuses: its diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 2d01db33..795ea743 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -54,11 +54,6 @@ const Ground = struct { } }; -fn ground(theme_bg: ?[3]u8, transparent: bool) Ground { - if (theme_bg) |rgb| return .opaqueRgb(rgb); - return .{ .rgb = bg_default, .clear = transparent }; -} - const p9_arrow_clr = [32]u8{ 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, 0x80, 0x10, 0x80, 0x10, 0x80, 0x08, 0x80, 0x04, @@ -1769,7 +1764,6 @@ const Gui = struct { capture_xfer_size: u32 = 0, soft_present: bool = false, - transparent: bool = false, surface_opacity: bool = false, applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, @@ -2187,7 +2181,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); // Background-only opacity needs per-pixel alpha; whole-window compositor // opacity would dim the text as well. SDL requires this flag at creation. - const surface_opacity = config.gui_transparent or native_wayland; + const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; const window = c.SDL_CreateWindow("pardes", 1120, 720, win_flags) orelse { log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); @@ -2391,7 +2385,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, .capture_dir = capture_dir orelse "", .soft_present = soft_present, - .transparent = config.gui_transparent, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, }; @@ -6092,7 +6085,7 @@ fn renderFrame( coverFrame(previous_covered, surface.cols, surface.rows, surface.previous_body_layers, surface.previous_tag_layers, surface.previous_regions); try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); - const page = ground(chrome.page, g.transparent); + const page: Ground = .opaqueRgb(chrome.page orelse bg_default); const background_opacity = backgroundOpacity(g.applied_window_opacity); var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo); color_target.texture = scene; @@ -8449,7 +8442,7 @@ fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTex // The cell shader already produced premultiplied backgrounds with opaque // foreground ink. Copy that alpha unchanged; never modulate the full frame. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); - _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.transparent or g.surface_opacity) 0 else 255); + _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255); _ = c.SDL_RenderClear(renderer); _ = c.SDL_RenderTexture(renderer, texture, null, null); _ = c.SDL_RenderPresent(renderer); diff --git a/src/hunks.zig b/src/hunks.zig index 24aaf63d..8cd5c43a 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -111,11 +111,7 @@ const Out = struct { fn deinit(out: *Out) void { out.text.deinit(); - for (out.rows.items) |r| { - out.p.gpa.free(r.path); - out.p.gpa.free(r.colors); - } - out.rows.deinit(out.p.gpa); + locations.freeRowList(out.p.gpa, &out.rows); } const Meta = struct { diff --git a/src/locations.zig b/src/locations.zig index 1e4a20cf..6f086214 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -33,6 +33,15 @@ pub fn freeRows(gpa: std.mem.Allocator, rows: []Row) void { gpa.free(rows); } +/// A list of rows being built, given up: each row's own bytes, then the list. +pub fn freeRowList(gpa: std.mem.Allocator, rows: *std.ArrayList(Row)) void { + for (rows.items) |row| { + gpa.free(row.path); + gpa.free(row.colors); + } + rows.deinit(gpa); +} + pub fn equalRows(a: []const Row, b: []const Row) bool { if (a.len != b.len) return false; for (a, b) |left, right| { @@ -316,13 +325,7 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); const stacked = p.settings.callstack_layout == .stacked; const resolved = try resolveCallstack(p, arena, dir, input); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); @@ -496,13 +499,7 @@ pub fn format(p: *pardes.Pardes, dir: []const u8, input: []const u8, anchor: ?us var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); var mapped = anchor; if (p.locations_config.layout == .stacked) { for (pending.items, 0..) |row, index| { diff --git a/src/look.zig b/src/look.zig index 588574ed..2d97cb9f 100644 --- a/src/look.zig +++ b/src/look.zig @@ -32,9 +32,7 @@ const Key = pardes.Key; const Event = pardes.Event; const Pardes = pardes.Pardes; -extern "c" fn fork() c_int; extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; -extern "c" fn _exit(status: c_int) noreturn; const opener_path: ?[*:0]const u8 = switch (builtin.os.tag) { .linux => "/usr/bin/xdg-open", @@ -46,15 +44,15 @@ pub fn openLink(url: []const u8) void { const opener = opener_path orelse return; var buf: [1024]u8 = undefined; const url_z = std.fmt.bufPrintSentinel(&buf, "{s}", .{url}, 0) catch return; - const pid = fork(); + const pid = libc.fork(); if (pid < 0) return; if (pid == 0) { - if (fork() == 0) { + if (libc.fork() == 0) { @import("host_io.zig").resetChildSignals(); const argv: [3:null]?[*:0]const u8 = .{ opener, url_z.ptr, null }; _ = execv(opener, &argv); } - _exit(0); + libc._exit(0); } _ = libc.waitpid(pid, null, 0); } diff --git a/src/main.zig b/src/main.zig index ea2db917..52093b9a 100644 --- a/src/main.zig +++ b/src/main.zig @@ -144,32 +144,22 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const /// Stdin to its end, as it came (its escapes are the session's to parse, /// pager.zig), at most a file's limit, a longer one cut there and said so /// at its end. -fn readStdinText(gpa: std.mem.Allocator) ![]u8 { +fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; var chunk: [64 * 1024]u8 = undefined; - var cut = false; - while (true) { - const n = std.c.read(0, &chunk, chunk.len); - if (n < 0) { - if (std.posix.errno(n) == .INTR) continue; - return error.ReadFailed; - } - if (n == 0) break; - const got: usize = @intCast(n); - if (raw.items.len + got > limit) { - try raw.appendSlice(gpa, chunk[0 .. limit - raw.items.len]); - cut = true; - break; - } - try raw.appendSlice(gpa, chunk[0..got]); - } - if (cut) { - // CAN ends an escape the cut left half sent, and SGR 0 its colour, - // so the note is never swallowed or tinted. - const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; - try raw.appendSlice(gpa, said); - } + var stdin = std.Io.File.stdin().readerStreaming(io, &chunk); + // One byte past the limit says there is more. + stdin.interface.appendRemaining(gpa, &raw, .limited(limit + 1)) catch |err| switch (err) { + error.StreamTooLong => { + raw.shrinkRetainingCapacity(limit); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); + }, + else => |e| return e, + }; return raw.toOwnedSlice(gpa); } @@ -561,7 +551,7 @@ fn nativeMain(std_init: std.process.Init) !void { // made of it (as acme's `B` has no stdin, through pane/new, a name // and the body), and back at once: the PAGER a pane's shell gets. if (positional) |word| if (std.mem.eql(u8, word, "-")) { - const text = readStdinText(arena) catch |err| Refuse.with(init.io, "stdin", err); + const text = readStdinText(init.io, arena) catch |err| Refuse.with(init.io, "stdin", err); // Nothing paged: no pane, and done. if (text.len == 0) return; pageInto(init.io, arena, parent.dial, text); @@ -676,7 +666,7 @@ fn nativeMain(std_init: std.process.Init) !void { // `pardes -` outside a session: an editor whose first pane holds stdin, // as `vim -` does; the terminal is /dev/tty, never stdin. if (positional) |a| if (std.mem.eql(u8, a, "-")) { - opts.stdin_text = readStdinText(arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); + opts.stdin_text = readStdinText(init.io, arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); // Nothing paged: nothing to show. if (opts.stdin_text.?.len == 0) return; positional = null; diff --git a/src/syntax.zig b/src/syntax.zig index 1c09c9f3..803d815a 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -1172,15 +1172,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at errdefer syntax_allocator.free(colored); try paintHunk(gpa, colored, bytes, kinds, sel); window.put(at, colored); + // An empty slot, else the least recently used. var oldest: usize = 0; for (&diff_pieces, 0..) |*slot, i| { const piece = slot.* orelse { oldest = i; break; }; - if (diff_pieces[oldest]) |o| if (piece.used < o.used) { - oldest = i; - }; + if (piece.used < diff_pieces[oldest].?.used) oldest = i; } if (diff_pieces[oldest]) |old| syntax_allocator.free(old.styles); diff_pieces[oldest] = .{ .hash = hash, .styles = colored, .used = diff_clock }; diff --git a/src/tagline.zig b/src/tagline.zig index b6601d61..e668419d 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -192,12 +192,7 @@ pub fn defaultTail(pane: *const Pane) []const u8 { /// The tag as it is shown, read and pointed at: its computed prefix and /// its own text after it. pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - const prefix = try tagPrefix(p, pane); - const tail = curTail(pane); - const out = try arena.alloc(u8, prefix.len + tail.len); - @memcpy(out[0..prefix.len], prefix); - @memcpy(out[prefix.len..], tail); - return out; + return std.mem.concat(arena, u8, &.{ try tagPrefix(p, pane), curTail(pane) }); } /// Give the keyboard to the tag in normal mode (`:`), its cursor where diff --git a/src/terminal.zig b/src/terminal.zig index 05054521..755fde6c 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1363,7 +1363,8 @@ const Rows = struct { const empty_grid = [1][]const u8{""}; /// What LEAVING raw tty mode does to one prompt row, decided from its cells -/// alone. See config.tty_blank for why any of this happens. +/// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at +/// them stays. const PromptCut = union(enum) { /// show the row exactly as ghostty dumped it keep, @@ -1375,7 +1376,6 @@ const PromptCut = union(enum) { }; fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; const cells = pin.cells(.all); var cols: usize = 0; while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; diff --git a/src/web.zig b/src/web.zig index f89aa7e9..fd6371c0 100644 --- a/src/web.zig +++ b/src/web.zig @@ -15,58 +15,19 @@ const mouse = @import("mouse.zig"); const gpa = std.heap.wasm_allocator; const embedded_dump = @embedFile("embedded.dump.zon"); const input_capacity = 64 * 1024; -const c_alloc_header_size = 16; const attr_tagline: u16 = 1 << 7; +/// Tree-sitter's C runtime is linked into this module: its malloc, calloc, +/// realloc and free are the wasm allocator's, as the Zig core's are. A var, +/// as c_heap compares the allocator it is at run time (wasm_allocator's +/// `ptr` is undefined, which comptime refuses to compare). +var c_allocator: std.mem.Allocator = gpa; +const c_heap = @import("c_heap").Heap(&c_allocator); comptime { - if (c_alloc_header_size < @sizeOf(usize)) @compileError("C allocation header is too small"); -} - -/// Tree-sitter's C runtime is linked into this module. Its conventional -/// allocation symbols share the same wasm allocator as the Zig core and keep -/// the original allocation size in a 16-byte, max-aligned prefix. -export fn malloc(size_arg: usize) callconv(.c) ?*anyopaque { - const size = @max(size_arg, 1); - const total = std.math.add(usize, c_alloc_header_size, size) catch return null; - const bytes = gpa.alignedAlloc(u8, .@"16", total) catch return null; - const header: *align(16) usize = @ptrCast(bytes.ptr); - header.* = total; - return @ptrCast(bytes.ptr + c_alloc_header_size); -} - -export fn calloc(count: usize, size: usize) callconv(.c) ?*anyopaque { - const len = std.math.mul(usize, count, size) catch return null; - const ptr = malloc(len) orelse return null; - if (len != 0) { - const bytes: [*]u8 = @ptrCast(ptr); - @memset(bytes[0..len], 0); - } - return ptr; -} - -export fn free(ptr: ?*anyopaque) callconv(.c) void { - const data = ptr orelse return; - const data_bytes: [*]u8 = @ptrCast(data); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - gpa.free(base[0..header.*]); -} - -export fn realloc(ptr: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { - if (ptr == null) return malloc(size); - if (size == 0) { - free(ptr); - return null; - } - const data_bytes: [*]u8 = @ptrCast(ptr.?); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - const old_size = header.* - c_alloc_header_size; - const replacement = malloc(size) orelse return null; - const replacement_bytes: [*]u8 = @ptrCast(replacement); - @memcpy(replacement_bytes[0..@min(old_size, size)], data_bytes[0..@min(old_size, size)]); - free(ptr); - return replacement; + @export(&c_heap.malloc, .{ .name = "malloc" }); + @export(&c_heap.calloc, .{ .name = "calloc" }); + @export(&c_heap.realloc, .{ .name = "realloc" }); + @export(&c_heap.free, .{ .name = "free" }); } pub const std_options: std.Options = .{ .logFn = logFn }; |
