jukebox
All repositories: gitoria
66.5 KB
// hl:fs plugin — native shared library// Compiled to fs.so, loaded by runtime via dlopen//// Exports:// hl_fs_file(path) → file descriptor with metadata + line iterator// hl_fs_read_file(path) → entire file as string (raw bytes, unchecked)// hl_fs_write_file(path, text, mode?) / hl_fs_write_file_hex(path, hex, mode?)// hl_fs_create_file(path, text, mode?) / hl_fs_create_file_hex(path, hex, mode?)// hl_fs_append_file(path, text, mode?) / hl_fs_append_file_hex(path, hex, mode?)// hl_fs_list_dir(path) → streaming directory iteratorconst std = @import("std");const api = @import("plugin_api");const linux = std.os.linux;const HlValue = api.HlValue;const HlObject = api.HlObject;const HlField = api.HlField;const HlIterator = api.HlIterator;const HlString = api.HlString;// the plugins' allocator (plugin_api.zig)const allocator = api.allocator;// =========================================================================// Path resolution (mission 068)//// CONTRACT: relative paths passed to hl:fs resolve against the MAIN SCRIPT's// directory, not the process CWD — Hybriel path resolution is file-relative// everywhere (import, inherit, plugin discovery), and fs follows suit.// Absolute paths are used as-is. The runtime injects the script dir via the// optional plugin hook hl_fs_set_script_dir right after dlopen.// =========================================================================var script_dir: ?[]u8 = null;export fn hl_fs_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {if (script_dir) |old| allocator.free(old);script_dir = allocator.dupe(u8, ptr[0..len]) catch null;}/// A compiled binary's unpacked `ship` files (mission 316): a relative path/// one of them answers resolves there; any other as it would without it.var ship_dir: ?[]u8 = null;export fn hl_fs_set_ship_dir(ptr: [*]const u8, len: usize) callconv(.c) void {if (ship_dir) |old| allocator.free(old);ship_dir = allocator.dupe(u8, ptr[0..len]) catch null;}/// THE READ TRACE (326 rung 12, the build cache): while a trace file is named/// — by hl:fs `traceReads(path)`, or by HL_FS_TRACE in the environment, which a build/// hands the programs it runs — every path this plugin reads, lists or probes/// is appended to it as one line, `r <path>`, `l <path>` or `e <path>`, the/// path as resolved (absolute when the process's was). A build records what it/// depends on this way; nothing else changes.var trace_path: ?[:0]u8 = null;var trace_env_read = false;export fn hl_fs_trace(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {trace_env_read = true;if (trace_path) |old| allocator.free(old);trace_path = null;if (argc >= 1 and argv[0].type == .hl_string) {const p = argv[0].data.string.ptr[0..argv[0].data.string.len];if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;}return api.makeNull();}fn traceAccess(kind: u8, resolved: []const u8) void {if (!trace_env_read) {trace_env_read = true;if (std.c.getenv("HL_FS_TRACE")) |e| {const p = std.mem.span(e);if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;}}const tp = trace_path orelse return;var cwd_buf: [4096]u8 = undefined;const line = if (resolved.len > 0 and resolved[0] == '/')std.fmt.allocPrint(allocator, "{c} {s}\n", .{ kind, resolved }) catch returnelse blk: {const rc: isize = @bitCast(linux.getcwd(&cwd_buf, cwd_buf.len));if (rc <= 0) return;const cwd = std.mem.sliceTo(&cwd_buf, 0);break :blk std.fmt.allocPrint(allocator, "{c} {s}/{s}\n", .{ kind, cwd, resolved }) catch return;};defer allocator.free(line);const rc = linuxOpenRc(tp, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o600);if (rc < 0) return;const fd: i32 = @intCast(rc);defer _ = linux.close(fd);_ = linux.write(fd, line.ptr, line.len);}/// hl_fs_digest(path) — the SHA-256 of a file's bytes as 64 hex digits, or/// null when it cannot be read; hl_fs_digest_text(text) — of a text's. The/// build cache's content keys (326 rung 12): hashed here, in the plugin, so/// every engine has them and nothing crosses as a value but the answer.export fn hl_fs_digest(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digest expects a string path");const path_str = argv[0].data.string;const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();defer allocator.free(resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);const rc = linuxOpenRc(path_z, .{}, 0);if (rc < 0) return api.makeNull();const fd: i32 = @intCast(rc);defer _ = linux.close(fd);var h = std.crypto.hash.sha2.Sha256.init(.{});var buf: [65536]u8 = undefined;while (true) {const n: isize = @bitCast(linux.read(fd, &buf, buf.len));if (n == 0) break;if (n < 0) {if (@as(usize, @intCast(-n)) == @intFromEnum(linux.E.INTR)) continue;return api.makeNull();}h.update(buf[0..@intCast(n)]);}return hexDigest(&h);}export fn hl_fs_digest_text(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digestText expects a string");const t = argv[0].data.string;var h = std.crypto.hash.sha2.Sha256.init(.{});h.update(t.ptr[0..t.len]);return hexDigest(&h);}fn hexDigest(h: *std.crypto.hash.sha2.Sha256) HlValue {var d: [32]u8 = undefined;h.final(&d);const out = allocator.alloc(u8, 64) catch return api.makeNull();const hex = "0123456789abcdef";for (d, 0..) |b, i| {out[i * 2] = hex[b >> 4];out[i * 2 + 1] = hex[b & 15];}return api.makeString(out);}/// Resolve a (possibly relative) path against the script dir. Returned slice/// is allocated with the plugin allocator; caller frees.fn resolvePath(path: []const u8) ?[]u8 {if (path.len == 0) return allocator.dupe(u8, path) catch null;if (path[0] == '/') return allocator.dupe(u8, path) catch null;if (ship_dir) |sd| {if (std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ sd, path }, 0)) |shipped| {defer allocator.free(shipped);if (std.c.access(shipped.ptr, 0) == 0) return allocator.dupe(u8, shipped) catch null;} else |_| {}}if (script_dir) |sd| {return std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, path }) catch null;}return allocator.dupe(u8, path) catch null;}// =========================================================================// Error values (mission 068): open failures are LOUD — api.makeError with// the operation, the path as the caller wrote it, and the OS reason. The// runtime turns a top-level error value into a located runtime error.// =========================================================================fn errnoText(errno: usize) []const u8 {return switch (errno) {2 => "no such file or directory",13 => "permission denied",20 => "not a directory",21 => "is a directory",1 => "operation not permitted",17 => "file exists",23 => "too many open files in the system",24 => "too many open files",28 => "no space left on device",30 => "read-only file system",36 => "file name too long",40 => "too many levels of symbolic links",else => "I/O error",};}/// What to do about it, for the two descriptor-limit errors (fd403): a docker soft limit of/// 1024 turned a boot into an unexplained "I/O error (errno 24)".fn errnoHint(errno: usize) []const u8 {return switch (errno) {23, 24 => "raise the open-file limit (ulimit -n) or close handles",else => "relative paths resolve against the script's directory",};}fn errDeinit(val: *api.HlValue) callconv(.c) void {if (val.type == .hl_error) {const s = val.data.string;allocator.free(@constCast(s.ptr[0..s.len]));}}fn makeOpenError(op: []const u8, path: []const u8, errno: usize) api.HlValue {const msg = std.fmt.allocPrint(allocator, "{s}: cannot open '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catchreturn api.makeError("fs: cannot open file");var v = api.makeError(msg);v.deinit_fn = &errDeinit;return v;}fn makeReadError(op: []const u8, path: []const u8, errno: usize) api.HlValue {const msg = std.fmt.allocPrint(allocator, "{s}: cannot read '{s}' — {s} (errno {d})", .{ op, path, errnoText(errno), errno }) catchreturn api.makeError("fs: cannot read file");var v = api.makeError(msg);v.deinit_fn = &errDeinit;return v;}// =========================================================================// hl_fs_file — file descriptor with metadata + line iterator// =========================================================================const FileIterState = struct {fd: i32,allocated_strings: std.array_list.Managed([]u8),done: bool,buf: [4096]u8,buf_pos: usize,buf_len: usize,};export fn hl_fs_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.file expects a string path");const path_str = argv[0].data.string;const path = path_str.ptr[0..path_str.len];// Resolve relative paths against the script dir; keep the caller's path// for the descriptor's name/path fields.const resolved = resolvePath(path) orelse return api.makeNull();defer allocator.free(resolved);traceAccess('r', resolved);// We need a null-terminated path for the OSconst path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);// Open fileconst rc = linuxOpenRc(path_z, .{}, 0);if (rc < 0) return makeOpenError("fs.file", path, @intCast(-rc));const fd: i32 = @intCast(rc);// Stat for size, chmod, uid, gidvar size: f64 = 0;var chmod: f64 = 0;var uid: f64 = 0;var gid: f64 = 0;var stat_ok = false;var statx_buf: std.os.linux.Statx = undefined;const statx_rc = std.os.linux.statx(fd,"",std.os.linux.AT.EMPTY_PATH,std.os.linux.STATX.BASIC_STATS,&statx_buf,);if (statx_rc == 0) {size = @floatFromInt(statx_buf.size);chmod = @floatFromInt(statx_buf.mode & 0o7777);uid = @floatFromInt(statx_buf.uid);gid = @floatFromInt(statx_buf.gid);stat_ok = true;}// Extract name from pathconst name = if (std.mem.lastIndexOfScalar(u8, path, '/')) |idx|path[idx + 1 ..]elsepath;// Mime from extensionconst mime = mimeFromName(name);// Build fields: name, path, size, mime, chmod, user, group = 7 fieldsconst field_count: usize = 7;const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name) };fields[1] = .{ .key = hlStr("path"), .value = api.makeString(path) };fields[2] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };fields[3] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };fields[4] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };if (stat_ok) {fields[5] = .{ .key = hlStr("user"), .value = api.makeNumber(uid) };fields[6] = .{ .key = hlStr("group"), .value = api.makeNumber(gid) };} else {fields[5] = .{ .key = hlStr("user"), .value = api.makeNull() };fields[6] = .{ .key = hlStr("group"), .value = api.makeNull() };}const obj = allocator.create(HlObject) catch return api.makeNull();obj.* = .{.fields = fields.ptr,.field_count = field_count,.deinit_fn = &fileObjDeinit,};// Create line iteratorconst iter_state = allocator.create(FileIterState) catch return api.makeNull();iter_state.* = .{.fd = fd,.allocated_strings = std.array_list.Managed([]u8).init(allocator),.done = false,.buf = undefined,.buf_pos = 0,.buf_len = 0,};const iter = allocator.create(HlIterator) catch return api.makeNull();iter.* = .{.context = @ptrCast(iter_state),.next_fn = &fileIterNext,.deinit_fn = &fileIterDeinit,};// Return object — runtime will see it has both object fields and an iterator// We pack the iterator pointer into the object by adding one more fieldconst full_fields = allocator.alloc(HlField, field_count + 1) catch return api.makeNull();@memcpy(full_fields[0..field_count], fields);full_fields[field_count] = .{ .key = hlStr("__iter"), .value = api.makeIterator(iter) };// Free the original fields, use full_fieldsallocator.free(fields);obj.fields = full_fields.ptr;obj.field_count = field_count + 1;return api.makeObject(obj);}fn fileIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));if (state.done) return api.makeNull();var line_buf = std.array_list.Managed(u8).init(allocator);while (true) {if (state.buf_pos < state.buf_len) {const remaining = state.buf[state.buf_pos..state.buf_len];if (std.mem.indexOfScalar(u8, remaining, '\n')) |nl_pos| {line_buf.appendSlice(remaining[0..nl_pos]) catch return api.makeNull();state.buf_pos += nl_pos + 1;break;} else {line_buf.appendSlice(remaining) catch return api.makeNull();state.buf_pos = 0;state.buf_len = 0;}}// Read from file using posix readconst n = linuxRead(state.fd, &state.buf) orelse {state.done = true;break;};if (n == 0) {state.done = true;break;}state.buf_pos = 0;state.buf_len = n;}if (state.done) closeIterFd(state);if (line_buf.items.len == 0 and state.done) {line_buf.deinit();return api.makeNull();}const line = line_buf.toOwnedSlice() catch return api.makeNull();state.allocated_strings.append(line) catch return api.makeNull();return api.makeString(line);}/// An iterator that ran to its end gives its fd back at once (fd403: the compiler's/// directory walks held one fd per listDir until the GC finalized them: > 1024 at boot)./// The fd is -1 afterwards; deinit closes only a still-open one.fn closeIterFd(state: anytype) void {if (state.fd >= 0) {_ = linux.close(state.fd);state.fd = -1;}}fn fileIterDeinit(ctx: ?*anyopaque) callconv(.c) void {const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return));closeIterFd(state);for (state.allocated_strings.items) |s| {allocator.free(s);}state.allocated_strings.deinit();allocator.destroy(state);}fn fileObjDeinit(obj: *HlObject) callconv(.c) void {const fields = obj.fields[0..obj.field_count];// Check for iterator field and clean it up (only if not already nulled out by runtime)for (fields) |field| {if (field.value.type == .hl_iterator) {const iter = field.value.data.iterator;if (iter.deinit_fn) |deinit_fn| {deinit_fn(iter.context);}allocator.destroy(iter);}}allocator.free(fields);allocator.destroy(obj);}// =========================================================================// hl_fs_read_file — read entire file as string// =========================================================================fn readFileDeinit(val: *HlValue) callconv(.c) void {if (val.type == .hl_string) {const s = val.data.string;allocator.free(@constCast(s.ptr[0..s.len]));}}/// exists(path) → Boolean (mission 077, 074 GAP 8). The ONLY hl:fs entry point/// that never errors: it answers a question, and "no" is an answer, not a/// failure. Same script-relative resolution as everything else. Without it the/// only way to test a path was to open it and survive the error — which is why/// the retired live_server used to index `static/` blind instead of probing it.export fn hl_fs_exists(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeBool(false);const path_str = argv[0].data.string;const path = path_str.ptr[0..path_str.len];const resolved = resolvePath(path) orelse return api.makeBool(false);defer allocator.free(resolved);traceAccess('e', resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeBool(false);defer allocator.free(path_z);// statx, not open: a directory, a symlink target, a device — anything the// OS can name — counts, and nothing is opened (no fd, no side effect).var statx_buf: std.os.linux.Statx = undefined;const rc = std.os.linux.statx(std.os.linux.AT.FDCWD,path_z,0,std.os.linux.STATX.BASIC_STATS,&statx_buf,);return api.makeBool(@as(isize, @bitCast(rc)) == 0);}/// changeTime(path) → the path's last status change (ctime, which no write can set/// back) as milliseconds since the epoch, or null when it is not there (#195). The/// build cache asks it of everything a build read: an input changed after the build/// began (a file edited, a checkout, a file made or removed in a listed directory)/// makes what the build saw differ from what the record would say. Not traced.export fn hl_fs_change_time(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();const path_str = argv[0].data.string;const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();defer allocator.free(resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);var statx_buf: std.os.linux.Statx = undefined;const rc = std.os.linux.statx(std.os.linux.AT.FDCWD,path_z,0,std.os.linux.STATX.BASIC_STATS,&statx_buf,);if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();const sec: f64 = @floatFromInt(statx_buf.ctime.sec);const nsec: f64 = @floatFromInt(statx_buf.ctime.nsec);return api.makeNumber(sec * 1000.0 + nsec / 1000000.0);}/// stat(path) → { size, mtime, ctime, type } without opening or reading the file, or/// null when the path is not there (the way changeTime treats a missing path). `size`/// is in bytes; `mtime` and `ctime` are milliseconds since the epoch, the same form/// changeTime answers in; `type` is "file", "directory" or "other" (the words listDir/// uses). Symlinks are followed, so the answer describes what the link points at./// Not traced (like changeTime, it reads no content).export fn hl_fs_stat(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.stat expects a string path");const path_str = argv[0].data.string;const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();defer allocator.free(resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);var sx: std.os.linux.Statx = undefined;const rc = std.os.linux.statx(std.os.linux.AT.FDCWD, path_z, 0, std.os.linux.STATX.BASIC_STATS, &sx);if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();const fmt = sx.mode & std.os.linux.S.IFMT;const kind: []const u8 = if (fmt == std.os.linux.S.IFREG) "file" else if (fmt == std.os.linux.S.IFDIR) "directory" else "other";const m_ms: f64 = @as(f64, @floatFromInt(sx.mtime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.mtime.nsec)) / 1000000.0;const c_ms: f64 = @as(f64, @floatFromInt(sx.ctime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.ctime.nsec)) / 1000000.0;const field_count: usize = 4;const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();fields[0] = .{ .key = hlStr("size"), .value = api.makeNumber(@floatFromInt(sx.size)) };fields[1] = .{ .key = hlStr("mtime"), .value = api.makeNumber(m_ms) };fields[2] = .{ .key = hlStr("ctime"), .value = api.makeNumber(c_ms) };fields[3] = .{ .key = hlStr("type"), .value = api.makeString(kind) };const obj = allocator.create(HlObject) catch return api.makeNull();obj.* = .{ .fields = fields.ptr, .field_count = field_count, .deinit_fn = &entryObjDeinit };return api.makeObject(obj);}/// readRange(path, offset, length) → at most `length` bytes starting at byte `offset`,/// as a string of raw bytes (the Hybriel side wraps it in Bytes). Only that range is/// read (pread), never the rest of the file. An offset at or past the end gives an empty/// result; a length running past the end gives the shorter rest. Offset and length must/// be whole numbers, zero or more; anything else is an error. A missing file is an error/// like readFile's.export fn hl_fs_read_range(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 3 or argv[0].type != .hl_string) return api.makeError("fs.readBytes expects a string path, an offset and a length");if (argv[1].type != .hl_number or argv[2].type != .hl_number) return api.makeError("fs.readBytes: offset and length must both be numbers (or both left out to read the whole file)");const off_f: f64 = argv[1].data.number;const len_f: f64 = argv[2].data.number;if (!(off_f >= 0) or !(len_f >= 0) or off_f != @floor(off_f) or len_f != @floor(len_f) or off_f > 9.0e15 or len_f > 9.0e15)return api.makeError("fs.readBytes: offset and length must be whole numbers, zero or more");const offset: u64 = @intFromFloat(off_f);const want: u64 = @intFromFloat(len_f);const path_str = argv[0].data.string;const path = path_str.ptr[0..path_str.len];const resolved = resolvePath(path) orelse return api.makeNull();defer allocator.free(resolved);traceAccess('r', resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);const rc = linuxOpenRc(path_z, .{}, 0);if (rc < 0) return makeOpenError("fs.readBytes", path, @intCast(-rc));const fd: i32 = @intCast(rc);defer _ = linux.close(fd);// Never allocate more than the file can still give: a huge length on a small file is cheap.var cap: u64 = want;var sx: std.os.linux.Statx = undefined;const src = std.os.linux.statx(fd, "", std.os.linux.AT.EMPTY_PATH, std.os.linux.STATX.BASIC_STATS, &sx);if (@as(isize, @bitCast(src)) == 0 and (sx.mode & std.os.linux.S.IFMT) == std.os.linux.S.IFREG) {cap = if (offset >= sx.size) 0 else @min(want, sx.size - offset);}var content = std.array_list.Managed(u8).init(allocator);defer content.deinit();var buf: [65536]u8 = undefined;var got: u64 = 0;while (got < cap) {const chunk: usize = @intCast(@min(@as(u64, buf.len), cap - got));const n_read: isize = @bitCast(linux.pread(fd, &buf, chunk, @intCast(offset + got)));if (n_read == 0) break;if (n_read < 0) {const errno: usize = @intCast(-n_read);if (errno == @intFromEnum(linux.E.INTR)) continue;return makeReadError("fs.readBytes", path, errno);}content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readBytes: out of memory reading the range");got += @intCast(n_read);}const result_slice = content.toOwnedSlice() catch return api.makeNull();var result = api.makeString(result_slice);result.deinit_fn = &readFileDeinit;return result;}export fn hl_fs_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {return readWhole(argc, argv, false);}/// tryReadFile(path) → the file as a string, or null when the path is not/// there (ENOENT/ENOTDIR). Any other failure is an error as in readFile. For a/// file another process may delete between a probe and the read (a shared/// cache): the vanishing is an answer, not a fault.export fn hl_fs_try_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {return readWhole(argc, argv, true);}fn readWhole(argc: u32, argv: [*]const HlValue, absent_is_null: bool) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.readFile expects a string path");const path_str = argv[0].data.string;const path = path_str.ptr[0..path_str.len];const resolved = resolvePath(path) orelse return api.makeNull();defer allocator.free(resolved);traceAccess('r', resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);const rc = linuxOpenRc(path_z, .{}, 0);if (rc < 0) {const en: usize = @intCast(-rc);if (absent_is_null and (en == @intFromEnum(linux.E.NOENT) or en == @intFromEnum(linux.E.NOTDIR))) return api.makeNull();return makeOpenError("fs.readFile", path, en);}const fd: i32 = @intCast(rc);defer _ = linux.close(fd);// The whole file: no size cap (a 10 MiB cap once truncated silently, ticket #112).// A failed read is an error naming the path, never a short string.var content = std.array_list.Managed(u8).init(allocator);defer content.deinit();var buf: [65536]u8 = undefined;while (true) {const n_read: isize = @bitCast(linux.read(fd, &buf, buf.len));if (n_read == 0) break;if (n_read < 0) {const errno: usize = @intCast(-n_read);if (errno == @intFromEnum(linux.E.INTR)) continue;return makeReadError("fs.readFile", path, errno);}content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readFile: out of memory reading the file");}const result_slice = content.toOwnedSlice() catch return api.makeNull();var result = api.makeString(result_slice);result.deinit_fn = &readFileDeinit;return result;}// =========================================================================// hl_fs_list_dir — streaming directory iterator with metadata// =========================================================================const DirIterState = struct {base_path: []const u8,// Snapshot at call time, in filesystem order: type byte, name, NUL.// Each syscall becomes one compact chunk, released as it is consumed.chunks: std.array_list.Managed([]u8),chunk_index: usize = 0,chunk_pos: usize = 0,dir_resolved: []u8,done: bool = false,};export fn hl_fs_list_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.listDir expects a string path");const path_str = argv[0].data.string;const path = path_str.ptr[0..path_str.len];const resolved = resolvePath(path) orelse return api.makeNull();defer allocator.free(resolved);traceAccess('l', resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);if (rc < 0) return makeOpenError("fs.listDir", path, @intCast(-rc));const fd: i32 = @intCast(rc);const path_copy = allocator.dupe(u8, path) catch {_ = linux.close(fd);return api.makeNull();};const state = allocator.create(DirIterState) catch {allocator.free(path_copy);_ = linux.close(fd);return api.makeNull();};state.* = .{.base_path = path_copy,.chunks = std.array_list.Managed([]u8).init(allocator),.dir_resolved = allocator.dupe(u8, resolved) catch {allocator.free(path_copy);allocator.destroy(state);_ = linux.close(fd);return api.makeNull();},};var chunk: [4096]u8 align(8) = undefined;var compact: [4096]u8 = undefined;while (true) {const got = std.os.linux.getdents64(fd, &chunk, chunk.len);if (@as(isize, @bitCast(got)) <= 0) break;var pos: usize = 0;var used: usize = 0;while (pos < got) {const entry: *align(1) const linux.dirent64 = @ptrCast(&chunk[pos]);const reclen = entry.reclen;if (reclen < 20 or reclen > got - pos) break;const name = std.mem.sliceTo(chunk[pos + 19 .. pos + reclen], 0);pos += reclen;if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;compact[used] = entry.type;@memcpy(compact[used + 1 ..][0..name.len], name);compact[used + 1 + name.len] = 0;used += name.len + 2;}if (used == 0) continue;const copy = allocator.dupe(u8, compact[0..used]) catch {_ = linux.close(fd);dirIterDeinit(state);return api.makeNull();};state.chunks.append(copy) catch {allocator.free(copy);_ = linux.close(fd);dirIterDeinit(state);return api.makeNull();};}_ = linux.close(fd);const iter = allocator.create(HlIterator) catch {dirIterDeinit(state);return api.makeNull();};iter.* = .{.context = @ptrCast(state),.next_fn = &dirIterNext,.deinit_fn = &dirIterDeinit,.close_fn = &dirIterClose,};return api.makeIterator(iter);}fn dirIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));if (state.done) return api.makeNull();while (true) {while (state.chunk_index < state.chunks.items.len andstate.chunk_pos == state.chunks.items[state.chunk_index].len){allocator.free(state.chunks.items[state.chunk_index]);state.chunk_index += 1;state.chunk_pos = 0;}if (state.chunk_index == state.chunks.items.len) {dirIterClose(ctx);return api.makeNull();}const chunk = state.chunks.items[state.chunk_index];const kind = chunk[state.chunk_pos];const name = std.mem.sliceTo(chunk[state.chunk_pos + 1 ..], 0);state.chunk_pos += name.len + 2;const name_copy = allocator.dupe(u8, name) catch return api.makeNull();const full_path = std.fmt.allocPrint(allocator, "{s}/{s}", .{ state.base_path, name }) catch {allocator.free(name_copy);return api.makeNull();};// Entry type from d_typeconst kind_str: []const u8 = switch (kind) {std.os.linux.DT.DIR => "directory",std.os.linux.DT.REG => "file",std.os.linux.DT.LNK => "symlink",else => "other",};// Stat for size, chmod, uid, gidvar size: f64 = 0;var chmod: f64 = 0;var e_uid: f64 = 0;var e_gid: f64 = 0;// null-terminate name for statxvar name_z_buf: [256]u8 = undefined;if (name.len < name_z_buf.len) {@memcpy(name_z_buf[0..name.len], name);name_z_buf[name.len] = 0;var statx_buf: std.os.linux.Statx = undefined;var stat_path: [4096]u8 = undefined;const stat_z = std.fmt.bufPrintZ(&stat_path, "{s}/{s}", .{ state.dir_resolved, name }) catch null;const src = if (stat_z) |sz| std.os.linux.statx(std.os.linux.AT.FDCWD,sz.ptr,0,std.os.linux.STATX.BASIC_STATS,&statx_buf,) else @as(usize, 1);if (src == 0) {size = @floatFromInt(statx_buf.size);chmod = @floatFromInt(statx_buf.mode & 0o7777);e_uid = @floatFromInt(statx_buf.uid);e_gid = @floatFromInt(statx_buf.gid);}}const mime = mimeFromName(name_copy);// Build object: name, path, type, size, mime, chmod, user, group// The runtime's hlObjectToValue will call dirEntryObjDeinit after conversion,// so these objects are freed immediately upon consumption.const field_count: usize = 8;const fields = allocator.alloc(HlField, field_count) catch {allocator.free(name_copy);allocator.free(full_path);return api.makeNull();};fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };fields[1] = .{ .key = hlStr("path"), .value = api.makeString(full_path) };fields[2] = .{ .key = hlStr("type"), .value = api.makeString(kind_str) };fields[3] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };fields[4] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };fields[5] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };fields[6] = .{ .key = hlStr("user"), .value = api.makeNumber(e_uid) };fields[7] = .{ .key = hlStr("group"), .value = api.makeNumber(e_gid) };const obj = allocator.create(HlObject) catch {allocator.free(fields);allocator.free(name_copy);allocator.free(full_path);return api.makeNull();};obj.* = .{.fields = fields.ptr,.field_count = field_count,.deinit_fn = &dirEntryObjDeinit,};return api.makeObject(obj);}}fn dirEntryObjDeinit(obj: *HlObject) callconv(.c) void {// hl_pvResultObject has copied every field; the iterator owns neither string.for (obj.fields[0..2]) |field| {const str = field.value.data.string;allocator.free(@constCast(str.ptr[0..str.len]));}entryObjDeinit(obj);}fn entryObjDeinit(obj: *HlObject) callconv(.c) void {allocator.free(obj.fields[0..obj.field_count]);allocator.destroy(obj);}fn dirIterClose(ctx: ?*anyopaque) callconv(.c) void {const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));if (state.done) return;state.done = true;for (state.chunks.items[state.chunk_index..]) |chunk| allocator.free(chunk);state.chunks.deinit();allocator.free(state.dir_resolved);allocator.free(@constCast(state.base_path));}fn dirIterDeinit(ctx: ?*anyopaque) callconv(.c) void {const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));dirIterClose(ctx);allocator.destroy(state);}// =========================================================================// Helpers// =========================================================================/// Raw open: >= 0 is the fd, < 0 is -errno.fn linuxOpenRc(path_z: [*:0]const u8, flags: linux.O, mode: u32) isize {const rc = linux.open(path_z, flags, mode);return @bitCast(rc);}fn linuxRead(fd: i32, buf: []u8) ?usize {const rc = linux.read(fd, buf.ptr, buf.len);if (@as(isize, @bitCast(rc)) <= 0) return null;return rc;}fn hlStr(comptime s: []const u8) HlString {return .{ .ptr = s.ptr, .len = s.len };}fn mimeFromName(name: []const u8) []const u8 {const ext = if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot|name[dot..]elsereturn "application/octet-stream";if (std.mem.eql(u8, ext, ".txt")) return "text/plain";if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return "text/html";if (std.mem.eql(u8, ext, ".css")) return "text/css";if (std.mem.eql(u8, ext, ".js")) return "text/javascript";if (std.mem.eql(u8, ext, ".json")) return "application/json";if (std.mem.eql(u8, ext, ".xml")) return "application/xml";if (std.mem.eql(u8, ext, ".png")) return "image/png";if (std.mem.eql(u8, ext, ".jpg") or std.mem.eql(u8, ext, ".jpeg")) return "image/jpeg";if (std.mem.eql(u8, ext, ".gif")) return "image/gif";if (std.mem.eql(u8, ext, ".svg")) return "image/svg+xml";if (std.mem.eql(u8, ext, ".pdf")) return "application/pdf";if (std.mem.eql(u8, ext, ".zip")) return "application/zip";if (std.mem.eql(u8, ext, ".gz")) return "application/gzip";if (std.mem.eql(u8, ext, ".mp3")) return "audio/mpeg";if (std.mem.eql(u8, ext, ".mp4")) return "video/mp4";if (std.mem.eql(u8, ext, ".wasm")) return "application/wasm";if (std.mem.eql(u8, ext, ".hl")) return "text/x-hybriel";if (std.mem.eql(u8, ext, ".md")) return "text/markdown";if (std.mem.eql(u8, ext, ".yml") or std.mem.eql(u8, ext, ".yaml")) return "text/yaml";if (std.mem.eql(u8, ext, ".toml")) return "application/toml";if (std.mem.eql(u8, ext, ".csv")) return "text/csv";if (std.mem.eql(u8, ext, ".ts")) return "text/typescript";if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return "text/x-c";if (std.mem.eql(u8, ext, ".zig")) return "text/x-zig";if (std.mem.eql(u8, ext, ".rs")) return "text/x-rust";if (std.mem.eql(u8, ext, ".py")) return "text/x-python";if (std.mem.eql(u8, ext, ".sh")) return "text/x-shellscript";if (std.mem.eql(u8, ext, ".sql")) return "application/sql";if (std.mem.eql(u8, ext, ".webp")) return "image/webp";if (std.mem.eql(u8, ext, ".ico")) return "image/x-icon";if (std.mem.eql(u8, ext, ".woff2")) return "font/woff2";if (std.mem.eql(u8, ext, ".woff")) return "font/woff";if (std.mem.eql(u8, ext, ".ttf")) return "font/ttf";return "application/octet-stream";}// ── fs.watch: an inotify LOOP SOURCE (the dev-reload bell) ───────────────────// `watch(path)` returns an event-loop source whose wake_fd combines inotify// readability and a bell for events already buffered by a read. Watches// the directory RECURSIVELY at registration (dot-dirs skipped); directories// created afterwards are picked up the next time the app is restarted, which// is the honest v1 for a dev tool.//// EXCLUSIONS (mission 266). `watch(path, exclude)` takes a second argument —// a path STRING or a LIST of them, the same either-shape the plugin surface// already uses in `hl_proc_spawn` — naming directories the descent must not// enter. One argument still means "watch everything": the argument is optional// and a null is the same as absent.//// This exists because a program that knows, at startup, about a directory it// will write to constantly (hl:web's session store is the first) had NO way to// say so. The only skip the walker possessed was "the name starts with a dot",// so the framework's advice was to RENAME the directory — a lecture standing// in for a fix. The dot-dir skip STAYS; `.git` is its reason and it is a good// one. This is a second, explicit reason to skip, not a replacement.const WatchState = struct {ifd: i32,wake_fd: i32 = -1, // epoll over ifd and bell_fd; readable while either is readybell_fd: i32 = -1,buf: [4096]u8 align(4) = undefined,len: usize = 0,pos: usize = 0,};/// LEXICAL path normalisation — collapses `//` and resolves `.` / `..`/// without touching the filesystem. It must be lexical: an excluded directory/// need not exist yet at the moment the watch is armed (hl:web resolves its/// session dir before it creates it), and realpath(2) on a missing path fails./// Both the watch root and every exclusion go through this, so the comparison/// below is between two paths written the same way.fn normalizePath(path: []const u8) ?[]u8 {const absolute = path.len > 0 and path[0] == '/';var parts = std.ArrayListUnmanaged([]const u8).empty;defer parts.deinit(allocator);var it = std.mem.tokenizeScalar(u8, path, '/');while (it.next()) |seg| {if (std.mem.eql(u8, seg, ".")) continue;if (std.mem.eql(u8, seg, "..")) {if (parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], "..")) {_ = parts.pop();continue;}if (absolute) continue; // ".." above "/" is "/"}parts.append(allocator, seg) catch return null;}var out = std.ArrayListUnmanaged(u8).empty;defer out.deinit(allocator);for (parts.items, 0..) |seg, i| {if (absolute or i > 0) out.append(allocator, '/') catch return null;out.appendSlice(allocator, seg) catch return null;}if (out.items.len == 0) out.appendSlice(allocator, if (absolute) "/" else ".") catch return null;return allocator.dupe(u8, out.items) catch null;}/// Is `child` the directory `root`, or somewhere under it? Both must already/// be normalised. A bare `startsWith` would call `/a/sessions-old` a child of/// `/a/sessions`, which is the whole reason this is a function: the byte after/// the prefix has to BE a separator.fn pathIsInside(child: []const u8, root: []const u8) bool {if (root.len == 0) return false;if (std.mem.eql(u8, child, root)) return true;if (child.len <= root.len) return false;if (!std.mem.startsWith(u8, child, root)) return false;if (root[root.len - 1] == '/') return true; // root is "/" itselfreturn child[root.len] == '/';}fn addWatchesRecursive(ifd: i32, dir_path: []const u8, depth: u32, excludes: []const []const u8) void {if (depth > 8) return;// The SECOND reason to skip a directory (mission 266). `dir_path` is// normalised: the root was normalised before the first call and every// child below is that root plus one plain name.for (excludes) |ex| if (pathIsInside(dir_path, ex)) return;const path_z = allocator.dupeZ(u8, dir_path) catch return;defer allocator.free(path_z);const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_TO | linux.IN.MOVED_FROM;_ = linux.inotify_add_watch(ifd, path_z, mask);// The descent walks getdents64 directly, like hl_fs_list_dir does — this// plugin speaks raw syscalls throughout and never pulls in std.fs.const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);if (rc < 0) return;const fd: i32 = @intCast(rc);defer _ = linux.close(fd);var dents: [4096]u8 align(8) = undefined;while (true) {const got = linux.getdents64(fd, &dents, dents.len);if (@as(isize, @bitCast(got)) <= 0) break;var pos: usize = 0;while (pos < got) {const entry: *align(1) linux.dirent64 = @ptrCast(&dents[pos]);pos += entry.reclen;if (entry.type != linux.DT.DIR) continue;const name_ptr: [*]const u8 = @ptrCast(&entry.name);const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;const name = name_ptr[0..name_len];// "." and ".." would recurse forever; every other dot-dir is noise// for a dev watcher (.git alone would cost thousands of watches).if (name.len == 0 or name[0] == '.') continue;const child = std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir_path, name }) catch continue;defer allocator.free(child);addWatchesRecursive(ifd, child, depth + 1, excludes);}}}/// One exclusion, resolved against the script dir like every other hl:fs path/// and then normalised. Appends nothing on an empty string.fn appendExclusion(list: *std.ArrayListUnmanaged([]u8), raw: []const u8) bool {if (raw.len == 0) return true;const resolved = resolvePath(raw) orelse return false;defer allocator.free(resolved);const norm = normalizePath(resolved) orelse return false;list.append(allocator, norm) catch {allocator.free(norm);return false;};return true;}export fn hl_fs_watch(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:fs: watch(path) needs a path string");const raw = argv[0].data.string.ptr[0..argv[0].data.string.len];const resolved = resolvePath(raw) orelse return api.makeError("hl:fs: watch: could not resolve the path");defer allocator.free(resolved);const path = normalizePath(resolved) orelse return api.makeError("hl:fs: watch: could not resolve the path");defer allocator.free(path);// THE OPTIONAL SECOND ARGUMENT: absent or null → watch everything, exactly// as before. A string is one directory; an object with numeric keys is the// loader's list shape (`hl_proc_spawn` reads its argv list the same way).var excludes = std.ArrayListUnmanaged([]u8).empty;defer {for (excludes.items) |e| allocator.free(e);excludes.deinit(allocator);}if (argc >= 2) {switch (argv[1].type) {.hl_null => {},.hl_string => {const sv = argv[1].data.string;if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");},.hl_object => {const obj_in = argv[1].data.object;for (obj_in.fields[0..obj_in.field_count]) |field| {if (field.value.type == .hl_null) continue;if (field.value.type != .hl_string) return api.makeError("hl:fs: watch(path, exclude): every exclusion must be a path string");const sv = field.value.data.string;if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");}},else => return api.makeError("hl:fs: watch(path, exclude): exclude is a path string or a list of path strings"),}}const rc = linux.inotify_init1(linux.IN.NONBLOCK);const ifd: i32 = @intCast(@as(isize, @bitCast(rc)));if (ifd < 0) return api.makeError("hl:fs: watch: inotify unavailable");addWatchesRecursive(ifd, path, 0, excludes.items);const state = allocator.create(WatchState) catch return api.makeError("hl:fs: out of memory");state.* = .{ .ifd = ifd };watchWakeInit(state);const iter = allocator.create(HlIterator) catch {watchDeinit(state);return api.makeError("hl:fs: out of memory");};iter.* = .{.context = @ptrCast(state),.next_fn = &watchTryNext, // non-blocking either way — event loop only.try_next_fn = &watchTryNext,.deinit_fn = &watchDeinit,.wake_fd = state.wake_fd,};return api.makeIterator(iter);}// An epoll fd is itself pollable. The runtime's eight-byte bell read on it// fails harmlessly, leaving protocol bytes to this source alone. No thread is// needed: the inotify fd wakes for new events, the bell for buffered events.fn watchWakeInit(st: *WatchState) void {const erc: isize = @bitCast(linux.epoll_create1(linux.EPOLL.CLOEXEC));if (erc < 0) return; // -1 retains the runtime's polled fallbackconst ep: i32 = @intCast(erc);const brc: isize = @bitCast(linux.eventfd(0, linux.EFD.NONBLOCK | linux.EFD.CLOEXEC));if (brc < 0) {_ = linux.close(ep);return;}const bell: i32 = @intCast(brc);for ([_]i32{ st.ifd, bell }) |fd| {var ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = fd } };const rc: isize = @bitCast(linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, fd, &ev));if (rc < 0) {_ = linux.close(bell);_ = linux.close(ep);return;}}st.wake_fd = ep;st.bell_fd = bell;}fn watchTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {const st: *WatchState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));var sink: u64 = 0;if (st.bell_fd >= 0) _ = linux.read(st.bell_fd, @ptrCast(&sink), 8);if (st.pos >= st.len) {const r = linux.read(st.ifd, &st.buf, st.buf.len);const n: isize = @bitCast(r);if (n <= 0) return api.makeNull(); // EAGAIN: drainedst.len = @intCast(n);st.pos = 0;}// one inotify_event: wd(i32) mask(u32) cookie(u32) len(u32) name[len]const base = st.pos;if (st.len - base < 16) {st.pos = st.len;return api.makeNull();}const name_len = std.mem.readInt(u32, st.buf[base + 12 ..][0..4], .little);const name_start = base + 16;var name: []const u8 = "";if (name_len > 0 and name_start + name_len <= st.len) {const raw_name = st.buf[name_start .. name_start + name_len];name = std.mem.sliceTo(raw_name, 0);}st.pos = name_start + name_len;if (st.pos < st.len and st.bell_fd >= 0) {const one: u64 = 1;_ = linux.write(st.bell_fd, @ptrCast(&one), 8);}const fields = allocator.alloc(api.HlField, 1) catch return api.makeNull();const name_copy = allocator.dupe(u8, name) catch {allocator.free(fields);return api.makeNull();};fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };const obj = allocator.create(api.HlObject) catch {allocator.free(name_copy);allocator.free(fields);return api.makeNull();};obj.* = .{ .fields = fields.ptr, .field_count = 1, .deinit_fn = &watchEventDeinit };return api.makeObject(obj);}/// An event is the loader's to copy and ours to free (the emit soak, 2026-10-02): with/// no deinit, every inotify event of the dev watcher — each write a db makes under the/// watched root — kept its name, its field and its object for good.fn watchEventDeinit(obj: *api.HlObject) callconv(.c) void {const sv = obj.fields[0].value.data.string;allocator.free(@constCast(sv.ptr)[0..sv.len]);allocator.free(obj.fields[0..obj.field_count]);allocator.destroy(obj);}fn watchDeinit(ctx: ?*anyopaque) callconv(.c) void {const st: *WatchState = @ptrCast(@alignCast(ctx orelse return));if (st.wake_fd >= 0) _ = linux.close(st.wake_fd);if (st.bell_fd >= 0) _ = linux.close(st.bell_fd);_ = linux.close(st.ifd);allocator.destroy(st);}// =========================================================================// THE WRITE SURFACE (2026-08-28)//// hl:fs was READ-ONLY until this block: file, readFile, listDir, exists,// watch. It could report a file's `chmod` and never set one. Session// persistence is the first thing in this tree that has to put bytes on a// disk, and the rule when the framework can do something the language// cannot is that the LANGUAGE is missing it — so the capability lands here,// as an ordinary hl:fs surface any program can use, not as a private hook// the session store reaches through.//// Three calls, and the shape of each is a decision://// writeFile(path, contents, mode?) ATOMIC. Writes a sibling temp file,// fsyncs it, then rename()s it over the target — so a reader sees// either the whole previous file or the whole new one, never a torn// one. A half-written session file that revives as garbage is a// silent logout, and the crash that produces it is exactly the crash// nobody can reproduce. rename(2) within one directory is atomic on// every filesystem Linux ships; that is the whole reason the temp// file is a SIBLING rather than in /tmp (a cross-device rename fails).// mkDir(path, mode?) recursive, and succeeds when the// directory is already there — the caller wants it to exist, not to// be the one who created it.// remove(path) IDEMPOTENT: true when the path is// gone on return, including when it was already gone. A sweep// deleting an expired file must not fail because something else// deleted it first.//// MODES ARE EXPLICIT AND DEFAULT TIGHT. hybrilior passes no mode anywhere,// so its session files land at whatever the umask says — 0644 on a shared// box, i.e. every session on the machine readable by every other tenant.// Here the default is 0600 for a file and 0700 for a directory, and a// caller who wants them looser has to say so. This is not the kind of bug// that shows up in a test; it shows up in someone else's logs.// =========================================================================fn makeWriteError(op: []const u8, path: []const u8, errno: usize) api.HlValue {const msg = std.fmt.allocPrint(allocator, "{s}: cannot write '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catchreturn api.makeError("fs: write failed");var v = api.makeError(msg);v.deinit_fn = &errDeinit;return v;}/// mkdir every missing component of `path`. Returns 0, or the errno of the/// first component that could not be created for a reason other than "it is/// already there".fn mkdirRecursive(path: []const u8, mode: u32) usize {if (path.len == 0) return 0;const buf = allocator.dupeZ(u8, path) catch return 12; // ENOMEMdefer allocator.free(buf);// Walk the separators left to right, creating each prefix in turn. Index// 0 is skipped so a leading '/' is never itself a component to create.var i: usize = 1;while (i <= buf.len) : (i += 1) {const at_end = i == buf.len;if (!at_end and buf[i] != '/') continue;if (!at_end) buf[i] = 0;const rc: isize = @bitCast(linux.mkdir(buf.ptr, mode));if (!at_end) buf[i] = '/';if (rc < 0) {const errno: usize = @intCast(-rc);// EEXIST is the success case: the caller wants it to exist.if (errno != 17) return errno;}}return 0;}export fn hl_fs_mk_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.mkDir expects a string path");const path_str = argv[0].data.string;const path = path_str.ptr[0..path_str.len];var mode: u32 = 0o700;if (argc >= 2 and argv[1].type == .hl_number) mode = @intFromFloat(argv[1].data.number);const resolved = resolvePath(path) orelse return api.makeError("fs.mkDir: out of memory");defer allocator.free(resolved);const errno = mkdirRecursive(resolved, mode);if (errno != 0) return makeWriteError("fs.mkDir", path, errno);return api.makeBool(true);}const write_usage = "fs.writeFile expects (String path, String or Bytes contents, Number mode?)";export fn hl_fs_write_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {return api.makeError(write_usage);}const path_str = argv[0].data.string;const body_str = argv[1].data.string;return writeWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));}/// hl_fs_write_file_hex(path, hex, mode?) — writeFile with a Bytes (ticket/// #88): a Bytes crosses the plugin boundary as its hex text (the ABI has no/// Bytes, as hl:proc's write_hex says), is decoded here and written raw.export fn hl_fs_write_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {return api.makeError(write_usage);}const path_str = argv[0].data.string;const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.writeFile: out of memory");defer allocator.free(raw);_ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.writeFile: not a Bytes");return writeWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));}fn modeArg(argc: u32, argv: [*]const HlValue) u32 {if (argc >= 3 and argv[2].type == .hl_number) return @intFromFloat(argv[2].data.number);return 0o600;}fn writeWhole(path: []const u8, body: []const u8, mode: u32) HlValue {const resolved = resolvePath(path) orelse return api.makeError("fs.writeFile: out of memory");defer allocator.free(resolved);// The temp name is a SIBLING (see the block comment): rename(2) is only// atomic within one filesystem, and /tmp is routinely a different one.// The pid keeps two processes writing the same path off each other's temp// file; the rename itself settles who wins the target.const pid = linux.getpid();const tmp = std.fmt.allocPrintSentinel(allocator, "{s}.hltmp{d}", .{ resolved, pid }, 0) catchreturn api.makeError("fs.writeFile: out of memory");defer allocator.free(tmp);const rc = linuxOpenRc(tmp.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode);if (rc < 0) return makeWriteError("fs.writeFile", path, @intCast(-rc));const fd: i32 = @intCast(rc);var wrote: usize = 0;while (wrote < body.len) {const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));if (n <= 0) {_ = linux.close(fd);_ = linux.unlink(tmp.ptr);return makeWriteError("fs.writeFile", path, if (n < 0) @intCast(-n) else 5);}wrote += @intCast(n);}// fsync BEFORE the rename, or the rename can land while the bytes are// still only in the page cache — a power cut then leaves an EMPTY file// where a complete one used to be, which is worse than either outcome._ = linux.fsync(fd);_ = linux.close(fd);// O_CREAT honours the mode only through the umask; say it outright so a// 0600 request is 0600 whatever the process umask happens to be._ = linux.chmod(tmp.ptr, mode);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.writeFile: out of memory");defer allocator.free(path_z);const ren: isize = @bitCast(linux.rename(tmp.ptr, path_z.ptr));if (ren < 0) {_ = linux.unlink(tmp.ptr);return makeWriteError("fs.writeFile", path, @intCast(-ren));}return api.makeBool(true);}const create_usage = "fs.createFile expects (String path, String or Bytes contents, Number mode?)";export fn hl_fs_create_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {return api.makeError(create_usage);}const path_str = argv[0].data.string;const body_str = argv[1].data.string;return createWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));}/// Bytes cross the plugin ABI as hex, just as writeFile does.export fn hl_fs_create_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {return api.makeError(create_usage);}const path_str = argv[0].data.string;const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.createFile: out of memory");defer allocator.free(raw);_ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.createFile: not a Bytes");return createWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));}/// Exclusive creation publishes the path before writing its content.fn createWhole(path: []const u8, body: []const u8, mode: u32) HlValue {const resolved = resolvePath(path) orelse return api.makeError("fs.createFile: out of memory");defer allocator.free(resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.createFile: out of memory");defer allocator.free(path_z);const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, mode);if (rc == -17) return api.makeBool(false); // EEXIST: another creator won.if (rc < 0) return makeWriteError("fs.createFile", path, @intCast(-rc));const fd: i32 = @intCast(rc);defer _ = linux.close(fd);// Set the requested mode through the descriptor, even with a restrictive umask.const chmod_rc: isize = @bitCast(linux.fchmod(fd, mode));if (chmod_rc < 0) return makeWriteError("fs.createFile", path, @intCast(-chmod_rc));var wrote: usize = 0;while (wrote < body.len) {const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));if (n == -4) continue; // EINTRif (n <= 0) {return makeWriteError("fs.createFile", path, if (n < 0) @intCast(-n) else 5);}wrote += @intCast(n);}return api.makeBool(true);}const append_usage = "fs.appendFile expects (String path, String or Bytes contents, Number mode?)";export fn hl_fs_append_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {return api.makeError(append_usage);}const path_str = argv[0].data.string;const body_str = argv[1].data.string;return appendWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));}/// hl_fs_append_file_hex(path, hex, mode?) — appendFile with a Bytes (ticket/// #88), the same hex-text crossing writeFile's hex sibling uses.export fn hl_fs_append_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {return api.makeError(append_usage);}const path_str = argv[0].data.string;const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.appendFile: out of memory");defer allocator.free(raw);_ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.appendFile: not a Bytes");return appendWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));}/// APPEND, NOT ATOMIC BY RENAME (writeFile's block comment above): an append/// MUTATES the file that is already there, so there is no whole "old" or/// "new" version to swap in — O_APPEND gives a narrower guarantee instead./// The kernel positions a single write() at the file's CURRENT end and/// performs it as one operation, so two processes each appending a line never/// interleave their bytes mid-line and a reader never sees a torn append —/// which is why this is ONE write() of the whole body where writeFile's is/// (short-write retries aside). The file is created at `mode` (default 0600,/// same default as writeFile) if it is not there yet; O_APPEND on an existing/// file leaves its mode untouched, same as any other open of it.fn appendWhole(path: []const u8, body: []const u8, mode: u32) HlValue {const resolved = resolvePath(path) orelse return api.makeError("fs.appendFile: out of memory");defer allocator.free(resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.appendFile: out of memory");defer allocator.free(path_z);const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, mode);if (rc < 0) return makeWriteError("fs.appendFile", path, @intCast(-rc));const fd: i32 = @intCast(rc);defer _ = linux.close(fd);var wrote: usize = 0;while (wrote < body.len) {const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));if (n <= 0) {return makeWriteError("fs.appendFile", path, if (n < 0) @intCast(-n) else 5);}wrote += @intCast(n);}return api.makeBool(true);}export fn hl_fs_remove(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.remove expects a string path");const path_str = argv[0].data.string;const path = path_str.ptr[0..path_str.len];const resolved = resolvePath(path) orelse return api.makeError("fs.remove: out of memory");defer allocator.free(resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.remove: out of memory");defer allocator.free(path_z);var rc: isize = @bitCast(linux.unlink(path_z.ptr));// an empty directory goes too (EISDIR): hybriel.hl's scratch directories// (mission 326 rung 12), with no `rmdir` to shell out toif (rc == -21) rc = @bitCast(linux.rmdir(path_z.ptr));if (rc < 0) {const errno: usize = @intCast(-rc);// ENOENT is success: the caller asked for the path to be gone.if (errno == 2) return api.makeBool(true);return makeWriteError("fs.remove", path, errno);}return api.makeBool(true);}/// realPath(path) → the canonical absolute path (symlinks resolved, `.`/`..`/// folded; realpath(3)), or null when the path is not there or cannot be/// resolved. `/proc/self/exe` answers the running binary without a shell.export fn hl_fs_real_path(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();const path_str = argv[0].data.string;const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();defer allocator.free(resolved);traceAccess('e', resolved);const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();defer allocator.free(path_z);var buf: [std.posix.PATH_MAX]u8 = undefined;const out = std.c.realpath(path_z.ptr, &buf) orelse return api.makeNull();const text = allocator.dupe(u8, std.mem.span(out)) catch return api.makeNull();var result = api.makeString(text);result.deinit_fn = &readFileDeinit;return result;}test "wake burst fs buffered inotify events" {const w = @import("wake_test");const tmp = std.c.getenv("TMPDIR") orelse return error.NoScratchDirectory;const dir = try std.fmt.allocPrintSentinel(allocator, "{s}/fs-wake-{d}", .{ std.mem.span(tmp), linux.getpid() }, 0);defer allocator.free(dir);_ = linux.mkdir(dir, 0o700);defer _ = linux.rmdir(dir);var passed: usize = 0;for (0..10) |_| {const args = [_]api.HlValue{api.makeString(dir)};const v = hl_fs_watch(1, &args);try std.testing.expect(v.type == .hl_iterator);const it = v.data.iterator;defer allocator.destroy(it);defer watchDeinit(it.context);// 32 creates fit in one read. There are no writes/close-write events.for (0..32) |i| {const path = try std.fmt.allocPrintSentinel(allocator, "{s}/{d}", .{ dir, i }, 0);defer allocator.free(path);const fd = linuxOpenRc(path, .{ .CREAT = true, .ACCMODE = .RDONLY }, 0o600);try std.testing.expect(fd >= 0);_ = linux.close(@intCast(fd));}if (w.burst(it.wake_fd, it.context, &watchTryNext, 32)) passed += 1;for (0..32) |i| {const path = try std.fmt.allocPrintSentinel(allocator, "{s}/{d}", .{ dir, i }, 0);defer allocator.free(path);_ = linux.unlink(path);}}try w.result("fs inotify buffer", passed);try w.require(&.{passed});}
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre