gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit85fa6c9b85fa6c9blog: CB68 result, CB69 startedmre85fa6c9b/plugins/fs/fs.zig

65.2 KB

  1. // hl:fs plugin — native shared library
  2. // Compiled to fs.so, loaded by runtime via dlopen
  3. //
  4. // Exports:
  5. // hl_fs_file(path) → file descriptor with metadata + line iterator
  6. // hl_fs_read_file(path) → entire file as string (raw bytes, unchecked)
  7. // hl_fs_write_file(path, text, mode?) / hl_fs_write_file_hex(path, hex, mode?)
  8. // hl_fs_create_file(path, text, mode?) / hl_fs_create_file_hex(path, hex, mode?)
  9. // hl_fs_append_file(path, text, mode?) / hl_fs_append_file_hex(path, hex, mode?)
  10. // hl_fs_list_dir(path) → streaming directory iterator
  11. const std = @import("std");
  12. const api = @import("plugin_api");
  13. const linux = std.os.linux;
  14. const HlValue = api.HlValue;
  15. const HlObject = api.HlObject;
  16. const HlField = api.HlField;
  17. const HlIterator = api.HlIterator;
  18. const HlString = api.HlString;
  19. // the plugins' allocator (plugin_api.zig)
  20. const allocator = api.allocator;
  21. // =========================================================================
  22. // Path resolution (mission 068)
  23. //
  24. // CONTRACT: relative paths passed to hl:fs resolve against the MAIN SCRIPT's
  25. // directory, not the process CWD — Hybriel path resolution is file-relative
  26. // everywhere (import, inherit, plugin discovery), and fs follows suit.
  27. // Absolute paths are used as-is. The runtime injects the script dir via the
  28. // optional plugin hook hl_fs_set_script_dir right after dlopen.
  29. // =========================================================================
  30. var script_dir: ?[]u8 = null;
  31. export fn hl_fs_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  32. if (script_dir) |old| allocator.free(old);
  33. script_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  34. }
  35. /// A compiled binary's unpacked `ship` files (mission 316): a relative path
  36. /// one of them answers resolves there; any other as it would without it.
  37. var ship_dir: ?[]u8 = null;
  38. export fn hl_fs_set_ship_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  39. if (ship_dir) |old| allocator.free(old);
  40. ship_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  41. }
  42. /// THE READ TRACE (326 rung 12, the build cache): while a trace file is named
  43. /// — by hl:fs `traceReads(path)`, or by HL_FS_TRACE in the environment, which a build
  44. /// hands the programs it runs — every path this plugin reads, lists or probes
  45. /// is appended to it as one line, `r <path>`, `l <path>` or `e <path>`, the
  46. /// path as resolved (absolute when the process's was). A build records what it
  47. /// depends on this way; nothing else changes.
  48. var trace_path: ?[:0]u8 = null;
  49. var trace_env_read = false;
  50. export fn hl_fs_trace(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  51. trace_env_read = true;
  52. if (trace_path) |old| allocator.free(old);
  53. trace_path = null;
  54. if (argc >= 1 and argv[0].type == .hl_string) {
  55. const p = argv[0].data.string.ptr[0..argv[0].data.string.len];
  56. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  57. }
  58. return api.makeNull();
  59. }
  60. fn traceAccess(kind: u8, resolved: []const u8) void {
  61. if (!trace_env_read) {
  62. trace_env_read = true;
  63. if (std.c.getenv("HL_FS_TRACE")) |e| {
  64. const p = std.mem.span(e);
  65. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  66. }
  67. }
  68. const tp = trace_path orelse return;
  69. var cwd_buf: [4096]u8 = undefined;
  70. const line = if (resolved.len > 0 and resolved[0] == '/')
  71. std.fmt.allocPrint(allocator, "{c} {s}\n", .{ kind, resolved }) catch return
  72. else blk: {
  73. const rc: isize = @bitCast(linux.getcwd(&cwd_buf, cwd_buf.len));
  74. if (rc <= 0) return;
  75. const cwd = std.mem.sliceTo(&cwd_buf, 0);
  76. break :blk std.fmt.allocPrint(allocator, "{c} {s}/{s}\n", .{ kind, cwd, resolved }) catch return;
  77. };
  78. defer allocator.free(line);
  79. const rc = linuxOpenRc(tp, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o600);
  80. if (rc < 0) return;
  81. const fd: i32 = @intCast(rc);
  82. defer _ = linux.close(fd);
  83. _ = linux.write(fd, line.ptr, line.len);
  84. }
  85. /// hl_fs_digest(path) — the SHA-256 of a file's bytes as 64 hex digits, or
  86. /// null when it cannot be read; hl_fs_digest_text(text) — of a text's. The
  87. /// build cache's content keys (326 rung 12): hashed here, in the plugin, so
  88. /// every engine has them and nothing crosses as a value but the answer.
  89. export fn hl_fs_digest(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  90. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digest expects a string path");
  91. const path_str = argv[0].data.string;
  92. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  93. defer allocator.free(resolved);
  94. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  95. defer allocator.free(path_z);
  96. const rc = linuxOpenRc(path_z, .{}, 0);
  97. if (rc < 0) return api.makeNull();
  98. const fd: i32 = @intCast(rc);
  99. defer _ = linux.close(fd);
  100. var h = std.crypto.hash.sha2.Sha256.init(.{});
  101. var buf: [65536]u8 = undefined;
  102. while (true) {
  103. const n: isize = @bitCast(linux.read(fd, &buf, buf.len));
  104. if (n == 0) break;
  105. if (n < 0) {
  106. if (@as(usize, @intCast(-n)) == @intFromEnum(linux.E.INTR)) continue;
  107. return api.makeNull();
  108. }
  109. h.update(buf[0..@intCast(n)]);
  110. }
  111. return hexDigest(&h);
  112. }
  113. export fn hl_fs_digest_text(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  114. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digestText expects a string");
  115. const t = argv[0].data.string;
  116. var h = std.crypto.hash.sha2.Sha256.init(.{});
  117. h.update(t.ptr[0..t.len]);
  118. return hexDigest(&h);
  119. }
  120. fn hexDigest(h: *std.crypto.hash.sha2.Sha256) HlValue {
  121. var d: [32]u8 = undefined;
  122. h.final(&d);
  123. const out = allocator.alloc(u8, 64) catch return api.makeNull();
  124. const hex = "0123456789abcdef";
  125. for (d, 0..) |b, i| {
  126. out[i * 2] = hex[b >> 4];
  127. out[i * 2 + 1] = hex[b & 15];
  128. }
  129. return api.makeString(out);
  130. }
  131. /// Resolve a (possibly relative) path against the script dir. Returned slice
  132. /// is allocated with the plugin allocator; caller frees.
  133. fn resolvePath(path: []const u8) ?[]u8 {
  134. if (path.len == 0) return allocator.dupe(u8, path) catch null;
  135. if (path[0] == '/') return allocator.dupe(u8, path) catch null;
  136. if (ship_dir) |sd| {
  137. if (std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ sd, path }, 0)) |shipped| {
  138. defer allocator.free(shipped);
  139. if (std.c.access(shipped.ptr, 0) == 0) return allocator.dupe(u8, shipped) catch null;
  140. } else |_| {}
  141. }
  142. if (script_dir) |sd| {
  143. return std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, path }) catch null;
  144. }
  145. return allocator.dupe(u8, path) catch null;
  146. }
  147. // =========================================================================
  148. // Error values (mission 068): open failures are LOUD — api.makeError with
  149. // the operation, the path as the caller wrote it, and the OS reason. The
  150. // runtime turns a top-level error value into a located runtime error.
  151. // =========================================================================
  152. fn errnoText(errno: usize) []const u8 {
  153. return switch (errno) {
  154. 2 => "no such file or directory",
  155. 13 => "permission denied",
  156. 20 => "not a directory",
  157. 21 => "is a directory",
  158. 1 => "operation not permitted",
  159. 17 => "file exists",
  160. 23 => "too many open files in the system",
  161. 24 => "too many open files",
  162. 28 => "no space left on device",
  163. 30 => "read-only file system",
  164. 36 => "file name too long",
  165. 40 => "too many levels of symbolic links",
  166. else => "I/O error",
  167. };
  168. }
  169. /// What to do about it, for the two descriptor-limit errors (fd403): a docker soft limit of
  170. /// 1024 turned a boot into an unexplained "I/O error (errno 24)".
  171. fn errnoHint(errno: usize) []const u8 {
  172. return switch (errno) {
  173. 23, 24 => "raise the open-file limit (ulimit -n) or close handles",
  174. else => "relative paths resolve against the script's directory",
  175. };
  176. }
  177. fn errDeinit(val: *api.HlValue) callconv(.c) void {
  178. if (val.type == .hl_error) {
  179. const s = val.data.string;
  180. allocator.free(@constCast(s.ptr[0..s.len]));
  181. }
  182. }
  183. fn makeOpenError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  184. const msg = std.fmt.allocPrint(allocator, "{s}: cannot open '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  185. return api.makeError("fs: cannot open file");
  186. var v = api.makeError(msg);
  187. v.deinit_fn = &errDeinit;
  188. return v;
  189. }
  190. fn makeReadError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  191. const msg = std.fmt.allocPrint(allocator, "{s}: cannot read '{s}' — {s} (errno {d})", .{ op, path, errnoText(errno), errno }) catch
  192. return api.makeError("fs: cannot read file");
  193. var v = api.makeError(msg);
  194. v.deinit_fn = &errDeinit;
  195. return v;
  196. }
  197. // =========================================================================
  198. // hl_fs_file — file descriptor with metadata + line iterator
  199. // =========================================================================
  200. const FileIterState = struct {
  201. fd: i32,
  202. allocated_strings: std.array_list.Managed([]u8),
  203. done: bool,
  204. buf: [4096]u8,
  205. buf_pos: usize,
  206. buf_len: usize,
  207. };
  208. export fn hl_fs_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  209. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.file expects a string path");
  210. const path_str = argv[0].data.string;
  211. const path = path_str.ptr[0..path_str.len];
  212. // Resolve relative paths against the script dir; keep the caller's path
  213. // for the descriptor's name/path fields.
  214. const resolved = resolvePath(path) orelse return api.makeNull();
  215. defer allocator.free(resolved);
  216. traceAccess('r', resolved);
  217. // We need a null-terminated path for the OS
  218. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  219. defer allocator.free(path_z);
  220. // Open file
  221. const rc = linuxOpenRc(path_z, .{}, 0);
  222. if (rc < 0) return makeOpenError("fs.file", path, @intCast(-rc));
  223. const fd: i32 = @intCast(rc);
  224. // Stat for size, chmod, uid, gid
  225. var size: f64 = 0;
  226. var chmod: f64 = 0;
  227. var uid: f64 = 0;
  228. var gid: f64 = 0;
  229. var stat_ok = false;
  230. var statx_buf: std.os.linux.Statx = undefined;
  231. const statx_rc = std.os.linux.statx(
  232. fd,
  233. "",
  234. std.os.linux.AT.EMPTY_PATH,
  235. std.os.linux.STATX.BASIC_STATS,
  236. &statx_buf,
  237. );
  238. if (statx_rc == 0) {
  239. size = @floatFromInt(statx_buf.size);
  240. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  241. uid = @floatFromInt(statx_buf.uid);
  242. gid = @floatFromInt(statx_buf.gid);
  243. stat_ok = true;
  244. }
  245. // Extract name from path
  246. const name = if (std.mem.lastIndexOfScalar(u8, path, '/')) |idx|
  247. path[idx + 1 ..]
  248. else
  249. path;
  250. // Mime from extension
  251. const mime = mimeFromName(name);
  252. // Build fields: name, path, size, mime, chmod, user, group = 7 fields
  253. const field_count: usize = 7;
  254. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  255. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name) };
  256. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(path) };
  257. fields[2] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  258. fields[3] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  259. fields[4] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  260. if (stat_ok) {
  261. fields[5] = .{ .key = hlStr("user"), .value = api.makeNumber(uid) };
  262. fields[6] = .{ .key = hlStr("group"), .value = api.makeNumber(gid) };
  263. } else {
  264. fields[5] = .{ .key = hlStr("user"), .value = api.makeNull() };
  265. fields[6] = .{ .key = hlStr("group"), .value = api.makeNull() };
  266. }
  267. const obj = allocator.create(HlObject) catch return api.makeNull();
  268. obj.* = .{
  269. .fields = fields.ptr,
  270. .field_count = field_count,
  271. .deinit_fn = &fileObjDeinit,
  272. };
  273. // Create line iterator
  274. const iter_state = allocator.create(FileIterState) catch return api.makeNull();
  275. iter_state.* = .{
  276. .fd = fd,
  277. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  278. .done = false,
  279. .buf = undefined,
  280. .buf_pos = 0,
  281. .buf_len = 0,
  282. };
  283. const iter = allocator.create(HlIterator) catch return api.makeNull();
  284. iter.* = .{
  285. .context = @ptrCast(iter_state),
  286. .next_fn = &fileIterNext,
  287. .deinit_fn = &fileIterDeinit,
  288. };
  289. // Return object — runtime will see it has both object fields and an iterator
  290. // We pack the iterator pointer into the object by adding one more field
  291. const full_fields = allocator.alloc(HlField, field_count + 1) catch return api.makeNull();
  292. @memcpy(full_fields[0..field_count], fields);
  293. full_fields[field_count] = .{ .key = hlStr("__iter"), .value = api.makeIterator(iter) };
  294. // Free the original fields, use full_fields
  295. allocator.free(fields);
  296. obj.fields = full_fields.ptr;
  297. obj.field_count = field_count + 1;
  298. return api.makeObject(obj);
  299. }
  300. fn fileIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  301. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  302. if (state.done) return api.makeNull();
  303. var line_buf = std.array_list.Managed(u8).init(allocator);
  304. while (true) {
  305. if (state.buf_pos < state.buf_len) {
  306. const remaining = state.buf[state.buf_pos..state.buf_len];
  307. if (std.mem.indexOfScalar(u8, remaining, '\n')) |nl_pos| {
  308. line_buf.appendSlice(remaining[0..nl_pos]) catch return api.makeNull();
  309. state.buf_pos += nl_pos + 1;
  310. break;
  311. } else {
  312. line_buf.appendSlice(remaining) catch return api.makeNull();
  313. state.buf_pos = 0;
  314. state.buf_len = 0;
  315. }
  316. }
  317. // Read from file using posix read
  318. const n = linuxRead(state.fd, &state.buf) orelse {
  319. state.done = true;
  320. break;
  321. };
  322. if (n == 0) {
  323. state.done = true;
  324. break;
  325. }
  326. state.buf_pos = 0;
  327. state.buf_len = n;
  328. }
  329. if (state.done) closeIterFd(state);
  330. if (line_buf.items.len == 0 and state.done) {
  331. line_buf.deinit();
  332. return api.makeNull();
  333. }
  334. const line = line_buf.toOwnedSlice() catch return api.makeNull();
  335. state.allocated_strings.append(line) catch return api.makeNull();
  336. return api.makeString(line);
  337. }
  338. /// An iterator that ran to its end gives its fd back at once (fd403: the compiler's
  339. /// directory walks held one fd per listDir until the GC finalized them: > 1024 at boot).
  340. /// The fd is -1 afterwards; deinit closes only a still-open one.
  341. fn closeIterFd(state: anytype) void {
  342. if (state.fd >= 0) {
  343. _ = linux.close(state.fd);
  344. state.fd = -1;
  345. }
  346. }
  347. fn fileIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  348. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return));
  349. closeIterFd(state);
  350. for (state.allocated_strings.items) |s| {
  351. allocator.free(s);
  352. }
  353. state.allocated_strings.deinit();
  354. allocator.destroy(state);
  355. }
  356. fn fileObjDeinit(obj: *HlObject) callconv(.c) void {
  357. const fields = obj.fields[0..obj.field_count];
  358. // Check for iterator field and clean it up (only if not already nulled out by runtime)
  359. for (fields) |field| {
  360. if (field.value.type == .hl_iterator) {
  361. const iter = field.value.data.iterator;
  362. if (iter.deinit_fn) |deinit_fn| {
  363. deinit_fn(iter.context);
  364. }
  365. allocator.destroy(iter);
  366. }
  367. }
  368. allocator.free(fields);
  369. allocator.destroy(obj);
  370. }
  371. // =========================================================================
  372. // hl_fs_read_file — read entire file as string
  373. // =========================================================================
  374. fn readFileDeinit(val: *HlValue) callconv(.c) void {
  375. if (val.type == .hl_string) {
  376. const s = val.data.string;
  377. allocator.free(@constCast(s.ptr[0..s.len]));
  378. }
  379. }
  380. /// exists(path) → Boolean (mission 077, 074 GAP 8). The ONLY hl:fs entry point
  381. /// that never errors: it answers a question, and "no" is an answer, not a
  382. /// failure. Same script-relative resolution as everything else. Without it the
  383. /// only way to test a path was to open it and survive the error — which is why
  384. /// the retired live_server used to index `static/` blind instead of probing it.
  385. export fn hl_fs_exists(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  386. if (argc < 1 or argv[0].type != .hl_string) return api.makeBool(false);
  387. const path_str = argv[0].data.string;
  388. const path = path_str.ptr[0..path_str.len];
  389. const resolved = resolvePath(path) orelse return api.makeBool(false);
  390. defer allocator.free(resolved);
  391. traceAccess('e', resolved);
  392. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeBool(false);
  393. defer allocator.free(path_z);
  394. // statx, not open: a directory, a symlink target, a device — anything the
  395. // OS can name — counts, and nothing is opened (no fd, no side effect).
  396. var statx_buf: std.os.linux.Statx = undefined;
  397. const rc = std.os.linux.statx(
  398. std.os.linux.AT.FDCWD,
  399. path_z,
  400. 0,
  401. std.os.linux.STATX.BASIC_STATS,
  402. &statx_buf,
  403. );
  404. return api.makeBool(@as(isize, @bitCast(rc)) == 0);
  405. }
  406. /// changeTime(path) → the path's last status change (ctime, which no write can set
  407. /// back) as milliseconds since the epoch, or null when it is not there (#195). The
  408. /// build cache asks it of everything a build read: an input changed after the build
  409. /// began (a file edited, a checkout, a file made or removed in a listed directory)
  410. /// makes what the build saw differ from what the record would say. Not traced.
  411. export fn hl_fs_change_time(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  412. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  413. const path_str = argv[0].data.string;
  414. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  415. defer allocator.free(resolved);
  416. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  417. defer allocator.free(path_z);
  418. var statx_buf: std.os.linux.Statx = undefined;
  419. const rc = std.os.linux.statx(
  420. std.os.linux.AT.FDCWD,
  421. path_z,
  422. 0,
  423. std.os.linux.STATX.BASIC_STATS,
  424. &statx_buf,
  425. );
  426. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  427. const sec: f64 = @floatFromInt(statx_buf.ctime.sec);
  428. const nsec: f64 = @floatFromInt(statx_buf.ctime.nsec);
  429. return api.makeNumber(sec * 1000.0 + nsec / 1000000.0);
  430. }
  431. /// stat(path) → { size, mtime, ctime, type } without opening or reading the file, or
  432. /// null when the path is not there (the way changeTime treats a missing path). `size`
  433. /// is in bytes; `mtime` and `ctime` are milliseconds since the epoch, the same form
  434. /// changeTime answers in; `type` is "file", "directory" or "other" (the words listDir
  435. /// uses). Symlinks are followed, so the answer describes what the link points at.
  436. /// Not traced (like changeTime, it reads no content).
  437. export fn hl_fs_stat(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  438. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.stat expects a string path");
  439. const path_str = argv[0].data.string;
  440. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  441. defer allocator.free(resolved);
  442. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  443. defer allocator.free(path_z);
  444. var sx: std.os.linux.Statx = undefined;
  445. const rc = std.os.linux.statx(std.os.linux.AT.FDCWD, path_z, 0, std.os.linux.STATX.BASIC_STATS, &sx);
  446. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  447. const fmt = sx.mode & std.os.linux.S.IFMT;
  448. const kind: []const u8 = if (fmt == std.os.linux.S.IFREG) "file" else if (fmt == std.os.linux.S.IFDIR) "directory" else "other";
  449. const m_ms: f64 = @as(f64, @floatFromInt(sx.mtime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.mtime.nsec)) / 1000000.0;
  450. const c_ms: f64 = @as(f64, @floatFromInt(sx.ctime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.ctime.nsec)) / 1000000.0;
  451. const field_count: usize = 4;
  452. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  453. fields[0] = .{ .key = hlStr("size"), .value = api.makeNumber(@floatFromInt(sx.size)) };
  454. fields[1] = .{ .key = hlStr("mtime"), .value = api.makeNumber(m_ms) };
  455. fields[2] = .{ .key = hlStr("ctime"), .value = api.makeNumber(c_ms) };
  456. fields[3] = .{ .key = hlStr("type"), .value = api.makeString(kind) };
  457. const obj = allocator.create(HlObject) catch return api.makeNull();
  458. obj.* = .{ .fields = fields.ptr, .field_count = field_count, .deinit_fn = &entryObjDeinit };
  459. return api.makeObject(obj);
  460. }
  461. /// readRange(path, offset, length) → at most `length` bytes starting at byte `offset`,
  462. /// as a string of raw bytes (the Hybriel side wraps it in Bytes). Only that range is
  463. /// read (pread), never the rest of the file. An offset at or past the end gives an empty
  464. /// result; a length running past the end gives the shorter rest. Offset and length must
  465. /// be whole numbers, zero or more; anything else is an error. A missing file is an error
  466. /// like readFile's.
  467. export fn hl_fs_read_range(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  468. if (argc < 3 or argv[0].type != .hl_string) return api.makeError("fs.readBytes expects a string path, an offset and a length");
  469. 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)");
  470. const off_f: f64 = argv[1].data.number;
  471. const len_f: f64 = argv[2].data.number;
  472. 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)
  473. return api.makeError("fs.readBytes: offset and length must be whole numbers, zero or more");
  474. const offset: u64 = @intFromFloat(off_f);
  475. const want: u64 = @intFromFloat(len_f);
  476. const path_str = argv[0].data.string;
  477. const path = path_str.ptr[0..path_str.len];
  478. const resolved = resolvePath(path) orelse return api.makeNull();
  479. defer allocator.free(resolved);
  480. traceAccess('r', resolved);
  481. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  482. defer allocator.free(path_z);
  483. const rc = linuxOpenRc(path_z, .{}, 0);
  484. if (rc < 0) return makeOpenError("fs.readBytes", path, @intCast(-rc));
  485. const fd: i32 = @intCast(rc);
  486. defer _ = linux.close(fd);
  487. // Never allocate more than the file can still give: a huge length on a small file is cheap.
  488. var cap: u64 = want;
  489. var sx: std.os.linux.Statx = undefined;
  490. const src = std.os.linux.statx(fd, "", std.os.linux.AT.EMPTY_PATH, std.os.linux.STATX.BASIC_STATS, &sx);
  491. if (@as(isize, @bitCast(src)) == 0 and (sx.mode & std.os.linux.S.IFMT) == std.os.linux.S.IFREG) {
  492. cap = if (offset >= sx.size) 0 else @min(want, sx.size - offset);
  493. }
  494. var content = std.array_list.Managed(u8).init(allocator);
  495. defer content.deinit();
  496. var buf: [65536]u8 = undefined;
  497. var got: u64 = 0;
  498. while (got < cap) {
  499. const chunk: usize = @intCast(@min(@as(u64, buf.len), cap - got));
  500. const n_read: isize = @bitCast(linux.pread(fd, &buf, chunk, @intCast(offset + got)));
  501. if (n_read == 0) break;
  502. if (n_read < 0) {
  503. const errno: usize = @intCast(-n_read);
  504. if (errno == @intFromEnum(linux.E.INTR)) continue;
  505. return makeReadError("fs.readBytes", path, errno);
  506. }
  507. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readBytes: out of memory reading the range");
  508. got += @intCast(n_read);
  509. }
  510. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  511. var result = api.makeString(result_slice);
  512. result.deinit_fn = &readFileDeinit;
  513. return result;
  514. }
  515. export fn hl_fs_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  516. return readWhole(argc, argv, false);
  517. }
  518. /// tryReadFile(path) → the file as a string, or null when the path is not
  519. /// there (ENOENT/ENOTDIR). Any other failure is an error as in readFile. For a
  520. /// file another process may delete between a probe and the read (a shared
  521. /// cache): the vanishing is an answer, not a fault.
  522. export fn hl_fs_try_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  523. return readWhole(argc, argv, true);
  524. }
  525. fn readWhole(argc: u32, argv: [*]const HlValue, absent_is_null: bool) HlValue {
  526. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.readFile expects a string path");
  527. const path_str = argv[0].data.string;
  528. const path = path_str.ptr[0..path_str.len];
  529. const resolved = resolvePath(path) orelse return api.makeNull();
  530. defer allocator.free(resolved);
  531. traceAccess('r', resolved);
  532. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  533. defer allocator.free(path_z);
  534. const rc = linuxOpenRc(path_z, .{}, 0);
  535. if (rc < 0) {
  536. const en: usize = @intCast(-rc);
  537. if (absent_is_null and (en == @intFromEnum(linux.E.NOENT) or en == @intFromEnum(linux.E.NOTDIR))) return api.makeNull();
  538. return makeOpenError("fs.readFile", path, en);
  539. }
  540. const fd: i32 = @intCast(rc);
  541. defer _ = linux.close(fd);
  542. // The whole file: no size cap (a 10 MiB cap once truncated silently, ticket #112).
  543. // A failed read is an error naming the path, never a short string.
  544. var content = std.array_list.Managed(u8).init(allocator);
  545. defer content.deinit();
  546. var buf: [65536]u8 = undefined;
  547. while (true) {
  548. const n_read: isize = @bitCast(linux.read(fd, &buf, buf.len));
  549. if (n_read == 0) break;
  550. if (n_read < 0) {
  551. const errno: usize = @intCast(-n_read);
  552. if (errno == @intFromEnum(linux.E.INTR)) continue;
  553. return makeReadError("fs.readFile", path, errno);
  554. }
  555. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readFile: out of memory reading the file");
  556. }
  557. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  558. var result = api.makeString(result_slice);
  559. result.deinit_fn = &readFileDeinit;
  560. return result;
  561. }
  562. // =========================================================================
  563. // hl_fs_list_dir — streaming directory iterator with metadata
  564. // =========================================================================
  565. const DirIterState = struct {
  566. fd: i32,
  567. base_path: []const u8,
  568. allocated_strings: std.array_list.Managed([]u8),
  569. // fd403: the WHOLE getdents64 output, read when listDir() is called, so the directory fd
  570. // is closed at once. A for-of that ends with break/return never finalizes its iterator
  571. // before the GC runs, and the compiler's own pathKind() returns from inside one: 1000+
  572. // directory fds open at the tracker's boot (docker nofile 1024). Stat is lazy, by path.
  573. raw: std.array_list.Managed(u8),
  574. dir_resolved: []u8,
  575. dents_pos: usize,
  576. dents_len: usize,
  577. done: bool,
  578. };
  579. export fn hl_fs_list_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  580. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.listDir expects a string path");
  581. const path_str = argv[0].data.string;
  582. const path = path_str.ptr[0..path_str.len];
  583. const resolved = resolvePath(path) orelse return api.makeNull();
  584. defer allocator.free(resolved);
  585. traceAccess('l', resolved);
  586. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  587. defer allocator.free(path_z);
  588. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  589. if (rc < 0) return makeOpenError("fs.listDir", path, @intCast(-rc));
  590. const fd: i32 = @intCast(rc);
  591. const path_copy = allocator.dupe(u8, path) catch {
  592. _ = linux.close(fd);
  593. return api.makeNull();
  594. };
  595. var raw = std.array_list.Managed(u8).init(allocator);
  596. var chunk: [4096]u8 align(8) = undefined;
  597. while (true) {
  598. const got = std.os.linux.getdents64(fd, &chunk, chunk.len);
  599. if (@as(isize, @bitCast(got)) <= 0) break;
  600. raw.appendSlice(chunk[0..got]) catch break;
  601. }
  602. _ = linux.close(fd);
  603. const state = allocator.create(DirIterState) catch return api.makeNull();
  604. state.* = .{
  605. .fd = -1,
  606. .base_path = path_copy,
  607. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  608. .raw = raw,
  609. .dir_resolved = allocator.dupe(u8, resolved) catch @constCast(""),
  610. .dents_pos = 0,
  611. .dents_len = raw.items.len,
  612. .done = false,
  613. };
  614. const iter = allocator.create(HlIterator) catch return api.makeNull();
  615. iter.* = .{
  616. .context = @ptrCast(state),
  617. .next_fn = &dirIterNext,
  618. .deinit_fn = &dirIterDeinit,
  619. };
  620. return api.makeIterator(iter);
  621. }
  622. fn dirIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  623. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  624. if (state.done) return api.makeNull();
  625. while (true) {
  626. // Need more directory entries?
  627. if (state.dents_pos >= state.dents_len) {
  628. state.done = true;
  629. return api.makeNull();
  630. }
  631. // Parse next dirent64
  632. const entry_ptr: *align(1) std.os.linux.dirent64 = @ptrCast(&state.raw.items[state.dents_pos]);
  633. state.dents_pos += entry_ptr.reclen;
  634. // Get name
  635. const name_ptr: [*]const u8 = @ptrCast(&entry_ptr.name);
  636. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  637. const name = name_ptr[0..name_len];
  638. // Skip . and ..
  639. if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
  640. const name_copy = allocator.dupe(u8, name) catch return api.makeNull();
  641. state.allocated_strings.append(name_copy) catch return api.makeNull();
  642. // Build full path
  643. const full_path = std.fmt.allocPrint(allocator, "{s}/{s}", .{ state.base_path, name }) catch return api.makeNull();
  644. state.allocated_strings.append(full_path) catch return api.makeNull();
  645. // Entry type from d_type
  646. const kind_str: []const u8 = switch (entry_ptr.type) {
  647. std.os.linux.DT.DIR => "directory",
  648. std.os.linux.DT.REG => "file",
  649. std.os.linux.DT.LNK => "symlink",
  650. else => "other",
  651. };
  652. // Stat for size, chmod, uid, gid
  653. var size: f64 = 0;
  654. var chmod: f64 = 0;
  655. var e_uid: f64 = 0;
  656. var e_gid: f64 = 0;
  657. // null-terminate name for statx
  658. var name_z_buf: [256]u8 = undefined;
  659. if (name.len < name_z_buf.len) {
  660. @memcpy(name_z_buf[0..name.len], name);
  661. name_z_buf[name.len] = 0;
  662. var statx_buf: std.os.linux.Statx = undefined;
  663. var stat_path: [4096]u8 = undefined;
  664. const stat_z = std.fmt.bufPrintZ(&stat_path, "{s}/{s}", .{ state.dir_resolved, name }) catch null;
  665. const src = if (stat_z) |sz| std.os.linux.statx(
  666. std.os.linux.AT.FDCWD,
  667. sz.ptr,
  668. 0,
  669. std.os.linux.STATX.BASIC_STATS,
  670. &statx_buf,
  671. ) else @as(usize, 1);
  672. if (src == 0) {
  673. size = @floatFromInt(statx_buf.size);
  674. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  675. e_uid = @floatFromInt(statx_buf.uid);
  676. e_gid = @floatFromInt(statx_buf.gid);
  677. }
  678. }
  679. const mime = mimeFromName(name_copy);
  680. // Build object: name, path, type, size, mime, chmod, user, group
  681. // The runtime's hlObjectToValue will call entryObjDeinit after conversion,
  682. // so these objects are freed immediately upon consumption.
  683. const field_count: usize = 8;
  684. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  685. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  686. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(full_path) };
  687. fields[2] = .{ .key = hlStr("type"), .value = api.makeString(kind_str) };
  688. fields[3] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  689. fields[4] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  690. fields[5] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  691. fields[6] = .{ .key = hlStr("user"), .value = api.makeNumber(e_uid) };
  692. fields[7] = .{ .key = hlStr("group"), .value = api.makeNumber(e_gid) };
  693. const obj = allocator.create(HlObject) catch return api.makeNull();
  694. obj.* = .{
  695. .fields = fields.ptr,
  696. .field_count = field_count,
  697. .deinit_fn = &entryObjDeinit,
  698. };
  699. return api.makeObject(obj);
  700. }
  701. }
  702. fn entryObjDeinit(obj: *HlObject) callconv(.c) void {
  703. allocator.free(obj.fields[0..obj.field_count]);
  704. allocator.destroy(obj);
  705. }
  706. fn dirIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  707. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));
  708. closeIterFd(state);
  709. state.raw.deinit();
  710. if (state.dir_resolved.len > 0) allocator.free(state.dir_resolved);
  711. for (state.allocated_strings.items) |s| {
  712. allocator.free(s);
  713. }
  714. state.allocated_strings.deinit();
  715. allocator.free(@constCast(state.base_path));
  716. allocator.destroy(state);
  717. }
  718. // =========================================================================
  719. // Helpers
  720. // =========================================================================
  721. /// Raw open: >= 0 is the fd, < 0 is -errno.
  722. fn linuxOpenRc(path_z: [*:0]const u8, flags: linux.O, mode: u32) isize {
  723. const rc = linux.open(path_z, flags, mode);
  724. return @bitCast(rc);
  725. }
  726. fn linuxRead(fd: i32, buf: []u8) ?usize {
  727. const rc = linux.read(fd, buf.ptr, buf.len);
  728. if (@as(isize, @bitCast(rc)) <= 0) return null;
  729. return rc;
  730. }
  731. fn hlStr(comptime s: []const u8) HlString {
  732. return .{ .ptr = s.ptr, .len = s.len };
  733. }
  734. fn mimeFromName(name: []const u8) []const u8 {
  735. const ext = if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot|
  736. name[dot..]
  737. else
  738. return "application/octet-stream";
  739. if (std.mem.eql(u8, ext, ".txt")) return "text/plain";
  740. if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return "text/html";
  741. if (std.mem.eql(u8, ext, ".css")) return "text/css";
  742. if (std.mem.eql(u8, ext, ".js")) return "text/javascript";
  743. if (std.mem.eql(u8, ext, ".json")) return "application/json";
  744. if (std.mem.eql(u8, ext, ".xml")) return "application/xml";
  745. if (std.mem.eql(u8, ext, ".png")) return "image/png";
  746. if (std.mem.eql(u8, ext, ".jpg") or std.mem.eql(u8, ext, ".jpeg")) return "image/jpeg";
  747. if (std.mem.eql(u8, ext, ".gif")) return "image/gif";
  748. if (std.mem.eql(u8, ext, ".svg")) return "image/svg+xml";
  749. if (std.mem.eql(u8, ext, ".pdf")) return "application/pdf";
  750. if (std.mem.eql(u8, ext, ".zip")) return "application/zip";
  751. if (std.mem.eql(u8, ext, ".gz")) return "application/gzip";
  752. if (std.mem.eql(u8, ext, ".mp3")) return "audio/mpeg";
  753. if (std.mem.eql(u8, ext, ".mp4")) return "video/mp4";
  754. if (std.mem.eql(u8, ext, ".wasm")) return "application/wasm";
  755. if (std.mem.eql(u8, ext, ".hl")) return "text/x-hybriel";
  756. if (std.mem.eql(u8, ext, ".md")) return "text/markdown";
  757. if (std.mem.eql(u8, ext, ".yml") or std.mem.eql(u8, ext, ".yaml")) return "text/yaml";
  758. if (std.mem.eql(u8, ext, ".toml")) return "application/toml";
  759. if (std.mem.eql(u8, ext, ".csv")) return "text/csv";
  760. if (std.mem.eql(u8, ext, ".ts")) return "text/typescript";
  761. if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return "text/x-c";
  762. if (std.mem.eql(u8, ext, ".zig")) return "text/x-zig";
  763. if (std.mem.eql(u8, ext, ".rs")) return "text/x-rust";
  764. if (std.mem.eql(u8, ext, ".py")) return "text/x-python";
  765. if (std.mem.eql(u8, ext, ".sh")) return "text/x-shellscript";
  766. if (std.mem.eql(u8, ext, ".sql")) return "application/sql";
  767. if (std.mem.eql(u8, ext, ".webp")) return "image/webp";
  768. if (std.mem.eql(u8, ext, ".ico")) return "image/x-icon";
  769. if (std.mem.eql(u8, ext, ".woff2")) return "font/woff2";
  770. if (std.mem.eql(u8, ext, ".woff")) return "font/woff";
  771. if (std.mem.eql(u8, ext, ".ttf")) return "font/ttf";
  772. return "application/octet-stream";
  773. }
  774. // ── fs.watch: an inotify LOOP SOURCE (the dev-reload bell) ───────────────────
  775. // `watch(path)` returns an event-loop source whose wake_fd combines inotify
  776. // readability and a bell for events already buffered by a read. Watches
  777. // the directory RECURSIVELY at registration (dot-dirs skipped); directories
  778. // created afterwards are picked up the next time the app is restarted, which
  779. // is the honest v1 for a dev tool.
  780. //
  781. // EXCLUSIONS (mission 266). `watch(path, exclude)` takes a second argument —
  782. // a path STRING or a LIST of them, the same either-shape the plugin surface
  783. // already uses in `hl_proc_spawn` — naming directories the descent must not
  784. // enter. One argument still means "watch everything": the argument is optional
  785. // and a null is the same as absent.
  786. //
  787. // This exists because a program that knows, at startup, about a directory it
  788. // will write to constantly (hl:web's session store is the first) had NO way to
  789. // say so. The only skip the walker possessed was "the name starts with a dot",
  790. // so the framework's advice was to RENAME the directory — a lecture standing
  791. // in for a fix. The dot-dir skip STAYS; `.git` is its reason and it is a good
  792. // one. This is a second, explicit reason to skip, not a replacement.
  793. const WatchState = struct {
  794. ifd: i32,
  795. wake_fd: i32 = -1, // epoll over ifd and bell_fd; readable while either is ready
  796. bell_fd: i32 = -1,
  797. buf: [4096]u8 align(4) = undefined,
  798. len: usize = 0,
  799. pos: usize = 0,
  800. };
  801. /// LEXICAL path normalisation — collapses `//` and resolves `.` / `..`
  802. /// without touching the filesystem. It must be lexical: an excluded directory
  803. /// need not exist yet at the moment the watch is armed (hl:web resolves its
  804. /// session dir before it creates it), and realpath(2) on a missing path fails.
  805. /// Both the watch root and every exclusion go through this, so the comparison
  806. /// below is between two paths written the same way.
  807. fn normalizePath(path: []const u8) ?[]u8 {
  808. const absolute = path.len > 0 and path[0] == '/';
  809. var parts = std.ArrayListUnmanaged([]const u8).empty;
  810. defer parts.deinit(allocator);
  811. var it = std.mem.tokenizeScalar(u8, path, '/');
  812. while (it.next()) |seg| {
  813. if (std.mem.eql(u8, seg, ".")) continue;
  814. if (std.mem.eql(u8, seg, "..")) {
  815. if (parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], "..")) {
  816. _ = parts.pop();
  817. continue;
  818. }
  819. if (absolute) continue; // ".." above "/" is "/"
  820. }
  821. parts.append(allocator, seg) catch return null;
  822. }
  823. var out = std.ArrayListUnmanaged(u8).empty;
  824. defer out.deinit(allocator);
  825. for (parts.items, 0..) |seg, i| {
  826. if (absolute or i > 0) out.append(allocator, '/') catch return null;
  827. out.appendSlice(allocator, seg) catch return null;
  828. }
  829. if (out.items.len == 0) out.appendSlice(allocator, if (absolute) "/" else ".") catch return null;
  830. return allocator.dupe(u8, out.items) catch null;
  831. }
  832. /// Is `child` the directory `root`, or somewhere under it? Both must already
  833. /// be normalised. A bare `startsWith` would call `/a/sessions-old` a child of
  834. /// `/a/sessions`, which is the whole reason this is a function: the byte after
  835. /// the prefix has to BE a separator.
  836. fn pathIsInside(child: []const u8, root: []const u8) bool {
  837. if (root.len == 0) return false;
  838. if (std.mem.eql(u8, child, root)) return true;
  839. if (child.len <= root.len) return false;
  840. if (!std.mem.startsWith(u8, child, root)) return false;
  841. if (root[root.len - 1] == '/') return true; // root is "/" itself
  842. return child[root.len] == '/';
  843. }
  844. fn addWatchesRecursive(ifd: i32, dir_path: []const u8, depth: u32, excludes: []const []const u8) void {
  845. if (depth > 8) return;
  846. // The SECOND reason to skip a directory (mission 266). `dir_path` is
  847. // normalised: the root was normalised before the first call and every
  848. // child below is that root plus one plain name.
  849. for (excludes) |ex| if (pathIsInside(dir_path, ex)) return;
  850. const path_z = allocator.dupeZ(u8, dir_path) catch return;
  851. defer allocator.free(path_z);
  852. const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_TO | linux.IN.MOVED_FROM;
  853. _ = linux.inotify_add_watch(ifd, path_z, mask);
  854. // The descent walks getdents64 directly, like hl_fs_list_dir does — this
  855. // plugin speaks raw syscalls throughout and never pulls in std.fs.
  856. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  857. if (rc < 0) return;
  858. const fd: i32 = @intCast(rc);
  859. defer _ = linux.close(fd);
  860. var dents: [4096]u8 align(8) = undefined;
  861. while (true) {
  862. const got = linux.getdents64(fd, &dents, dents.len);
  863. if (@as(isize, @bitCast(got)) <= 0) break;
  864. var pos: usize = 0;
  865. while (pos < got) {
  866. const entry: *align(1) linux.dirent64 = @ptrCast(&dents[pos]);
  867. pos += entry.reclen;
  868. if (entry.type != linux.DT.DIR) continue;
  869. const name_ptr: [*]const u8 = @ptrCast(&entry.name);
  870. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  871. const name = name_ptr[0..name_len];
  872. // "." and ".." would recurse forever; every other dot-dir is noise
  873. // for a dev watcher (.git alone would cost thousands of watches).
  874. if (name.len == 0 or name[0] == '.') continue;
  875. const child = std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir_path, name }) catch continue;
  876. defer allocator.free(child);
  877. addWatchesRecursive(ifd, child, depth + 1, excludes);
  878. }
  879. }
  880. }
  881. /// One exclusion, resolved against the script dir like every other hl:fs path
  882. /// and then normalised. Appends nothing on an empty string.
  883. fn appendExclusion(list: *std.ArrayListUnmanaged([]u8), raw: []const u8) bool {
  884. if (raw.len == 0) return true;
  885. const resolved = resolvePath(raw) orelse return false;
  886. defer allocator.free(resolved);
  887. const norm = normalizePath(resolved) orelse return false;
  888. list.append(allocator, norm) catch {
  889. allocator.free(norm);
  890. return false;
  891. };
  892. return true;
  893. }
  894. export fn hl_fs_watch(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  895. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:fs: watch(path) needs a path string");
  896. const raw = argv[0].data.string.ptr[0..argv[0].data.string.len];
  897. const resolved = resolvePath(raw) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  898. defer allocator.free(resolved);
  899. const path = normalizePath(resolved) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  900. defer allocator.free(path);
  901. // THE OPTIONAL SECOND ARGUMENT: absent or null → watch everything, exactly
  902. // as before. A string is one directory; an object with numeric keys is the
  903. // loader's list shape (`hl_proc_spawn` reads its argv list the same way).
  904. var excludes = std.ArrayListUnmanaged([]u8).empty;
  905. defer {
  906. for (excludes.items) |e| allocator.free(e);
  907. excludes.deinit(allocator);
  908. }
  909. if (argc >= 2) {
  910. switch (argv[1].type) {
  911. .hl_null => {},
  912. .hl_string => {
  913. const sv = argv[1].data.string;
  914. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  915. },
  916. .hl_object => {
  917. const obj_in = argv[1].data.object;
  918. for (obj_in.fields[0..obj_in.field_count]) |field| {
  919. if (field.value.type == .hl_null) continue;
  920. if (field.value.type != .hl_string) return api.makeError("hl:fs: watch(path, exclude): every exclusion must be a path string");
  921. const sv = field.value.data.string;
  922. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  923. }
  924. },
  925. else => return api.makeError("hl:fs: watch(path, exclude): exclude is a path string or a list of path strings"),
  926. }
  927. }
  928. const rc = linux.inotify_init1(linux.IN.NONBLOCK);
  929. const ifd: i32 = @intCast(@as(isize, @bitCast(rc)));
  930. if (ifd < 0) return api.makeError("hl:fs: watch: inotify unavailable");
  931. addWatchesRecursive(ifd, path, 0, excludes.items);
  932. const state = allocator.create(WatchState) catch return api.makeError("hl:fs: out of memory");
  933. state.* = .{ .ifd = ifd };
  934. watchWakeInit(state);
  935. const iter = allocator.create(HlIterator) catch {
  936. watchDeinit(state);
  937. return api.makeError("hl:fs: out of memory");
  938. };
  939. iter.* = .{
  940. .context = @ptrCast(state),
  941. .next_fn = &watchTryNext, // non-blocking either way — event loop only
  942. .try_next_fn = &watchTryNext,
  943. .deinit_fn = &watchDeinit,
  944. .wake_fd = state.wake_fd,
  945. };
  946. return api.makeIterator(iter);
  947. }
  948. // An epoll fd is itself pollable. The runtime's eight-byte bell read on it
  949. // fails harmlessly, leaving protocol bytes to this source alone. No thread is
  950. // needed: the inotify fd wakes for new events, the bell for buffered events.
  951. fn watchWakeInit(st: *WatchState) void {
  952. const erc: isize = @bitCast(linux.epoll_create1(linux.EPOLL.CLOEXEC));
  953. if (erc < 0) return; // -1 retains the runtime's polled fallback
  954. const ep: i32 = @intCast(erc);
  955. const brc: isize = @bitCast(linux.eventfd(0, linux.EFD.NONBLOCK | linux.EFD.CLOEXEC));
  956. if (brc < 0) { _ = linux.close(ep); return; }
  957. const bell: i32 = @intCast(brc);
  958. for ([_]i32{ st.ifd, bell }) |fd| {
  959. var ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = fd } };
  960. const rc: isize = @bitCast(linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, fd, &ev));
  961. if (rc < 0) {
  962. _ = linux.close(bell);
  963. _ = linux.close(ep);
  964. return;
  965. }
  966. }
  967. st.wake_fd = ep;
  968. st.bell_fd = bell;
  969. }
  970. fn watchTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  971. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  972. var sink: u64 = 0;
  973. if (st.bell_fd >= 0) _ = linux.read(st.bell_fd, @ptrCast(&sink), 8);
  974. if (st.pos >= st.len) {
  975. const r = linux.read(st.ifd, &st.buf, st.buf.len);
  976. const n: isize = @bitCast(r);
  977. if (n <= 0) return api.makeNull(); // EAGAIN: drained
  978. st.len = @intCast(n);
  979. st.pos = 0;
  980. }
  981. // one inotify_event: wd(i32) mask(u32) cookie(u32) len(u32) name[len]
  982. const base = st.pos;
  983. if (st.len - base < 16) {
  984. st.pos = st.len;
  985. return api.makeNull();
  986. }
  987. const name_len = std.mem.readInt(u32, st.buf[base + 12 ..][0..4], .little);
  988. const name_start = base + 16;
  989. var name: []const u8 = "";
  990. if (name_len > 0 and name_start + name_len <= st.len) {
  991. const raw_name = st.buf[name_start .. name_start + name_len];
  992. name = std.mem.sliceTo(raw_name, 0);
  993. }
  994. st.pos = name_start + name_len;
  995. if (st.pos < st.len and st.bell_fd >= 0) {
  996. const one: u64 = 1;
  997. _ = linux.write(st.bell_fd, @ptrCast(&one), 8);
  998. }
  999. const fields = allocator.alloc(api.HlField, 1) catch return api.makeNull();
  1000. const name_copy = allocator.dupe(u8, name) catch {
  1001. allocator.free(fields);
  1002. return api.makeNull();
  1003. };
  1004. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  1005. const obj = allocator.create(api.HlObject) catch {
  1006. allocator.free(name_copy);
  1007. allocator.free(fields);
  1008. return api.makeNull();
  1009. };
  1010. obj.* = .{ .fields = fields.ptr, .field_count = 1, .deinit_fn = &watchEventDeinit };
  1011. return api.makeObject(obj);
  1012. }
  1013. /// An event is the loader's to copy and ours to free (the emit soak, 2026-10-02): with
  1014. /// no deinit, every inotify event of the dev watcher — each write a db makes under the
  1015. /// watched root — kept its name, its field and its object for good.
  1016. fn watchEventDeinit(obj: *api.HlObject) callconv(.c) void {
  1017. const sv = obj.fields[0].value.data.string;
  1018. allocator.free(@constCast(sv.ptr)[0..sv.len]);
  1019. allocator.free(obj.fields[0..obj.field_count]);
  1020. allocator.destroy(obj);
  1021. }
  1022. fn watchDeinit(ctx: ?*anyopaque) callconv(.c) void {
  1023. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return));
  1024. if (st.wake_fd >= 0) _ = linux.close(st.wake_fd);
  1025. if (st.bell_fd >= 0) _ = linux.close(st.bell_fd);
  1026. _ = linux.close(st.ifd);
  1027. allocator.destroy(st);
  1028. }
  1029. // =========================================================================
  1030. // THE WRITE SURFACE (2026-08-28)
  1031. //
  1032. // hl:fs was READ-ONLY until this block: file, readFile, listDir, exists,
  1033. // watch. It could report a file's `chmod` and never set one. Session
  1034. // persistence is the first thing in this tree that has to put bytes on a
  1035. // disk, and the rule when the framework can do something the language
  1036. // cannot is that the LANGUAGE is missing it — so the capability lands here,
  1037. // as an ordinary hl:fs surface any program can use, not as a private hook
  1038. // the session store reaches through.
  1039. //
  1040. // Three calls, and the shape of each is a decision:
  1041. //
  1042. // writeFile(path, contents, mode?) ATOMIC. Writes a sibling temp file,
  1043. // fsyncs it, then rename()s it over the target — so a reader sees
  1044. // either the whole previous file or the whole new one, never a torn
  1045. // one. A half-written session file that revives as garbage is a
  1046. // silent logout, and the crash that produces it is exactly the crash
  1047. // nobody can reproduce. rename(2) within one directory is atomic on
  1048. // every filesystem Linux ships; that is the whole reason the temp
  1049. // file is a SIBLING rather than in /tmp (a cross-device rename fails).
  1050. // mkDir(path, mode?) recursive, and succeeds when the
  1051. // directory is already there — the caller wants it to exist, not to
  1052. // be the one who created it.
  1053. // remove(path) IDEMPOTENT: true when the path is
  1054. // gone on return, including when it was already gone. A sweep
  1055. // deleting an expired file must not fail because something else
  1056. // deleted it first.
  1057. //
  1058. // MODES ARE EXPLICIT AND DEFAULT TIGHT. hybrilior passes no mode anywhere,
  1059. // so its session files land at whatever the umask says — 0644 on a shared
  1060. // box, i.e. every session on the machine readable by every other tenant.
  1061. // Here the default is 0600 for a file and 0700 for a directory, and a
  1062. // caller who wants them looser has to say so. This is not the kind of bug
  1063. // that shows up in a test; it shows up in someone else's logs.
  1064. // =========================================================================
  1065. fn makeWriteError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  1066. const msg = std.fmt.allocPrint(allocator, "{s}: cannot write '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  1067. return api.makeError("fs: write failed");
  1068. var v = api.makeError(msg);
  1069. v.deinit_fn = &errDeinit;
  1070. return v;
  1071. }
  1072. /// mkdir every missing component of `path`. Returns 0, or the errno of the
  1073. /// first component that could not be created for a reason other than "it is
  1074. /// already there".
  1075. fn mkdirRecursive(path: []const u8, mode: u32) usize {
  1076. if (path.len == 0) return 0;
  1077. const buf = allocator.dupeZ(u8, path) catch return 12; // ENOMEM
  1078. defer allocator.free(buf);
  1079. // Walk the separators left to right, creating each prefix in turn. Index
  1080. // 0 is skipped so a leading '/' is never itself a component to create.
  1081. var i: usize = 1;
  1082. while (i <= buf.len) : (i += 1) {
  1083. const at_end = i == buf.len;
  1084. if (!at_end and buf[i] != '/') continue;
  1085. if (!at_end) buf[i] = 0;
  1086. const rc: isize = @bitCast(linux.mkdir(buf.ptr, mode));
  1087. if (!at_end) buf[i] = '/';
  1088. if (rc < 0) {
  1089. const errno: usize = @intCast(-rc);
  1090. // EEXIST is the success case: the caller wants it to exist.
  1091. if (errno != 17) return errno;
  1092. }
  1093. }
  1094. return 0;
  1095. }
  1096. export fn hl_fs_mk_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1097. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.mkDir expects a string path");
  1098. const path_str = argv[0].data.string;
  1099. const path = path_str.ptr[0..path_str.len];
  1100. var mode: u32 = 0o700;
  1101. if (argc >= 2 and argv[1].type == .hl_number) mode = @intFromFloat(argv[1].data.number);
  1102. const resolved = resolvePath(path) orelse return api.makeError("fs.mkDir: out of memory");
  1103. defer allocator.free(resolved);
  1104. const errno = mkdirRecursive(resolved, mode);
  1105. if (errno != 0) return makeWriteError("fs.mkDir", path, errno);
  1106. return api.makeBool(true);
  1107. }
  1108. const write_usage = "fs.writeFile expects (String path, String or Bytes contents, Number mode?)";
  1109. export fn hl_fs_write_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1110. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1111. return api.makeError(write_usage);
  1112. }
  1113. const path_str = argv[0].data.string;
  1114. const body_str = argv[1].data.string;
  1115. return writeWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1116. }
  1117. /// hl_fs_write_file_hex(path, hex, mode?) — writeFile with a Bytes (ticket
  1118. /// #88): a Bytes crosses the plugin boundary as its hex text (the ABI has no
  1119. /// Bytes, as hl:proc's write_hex says), is decoded here and written raw.
  1120. export fn hl_fs_write_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1121. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1122. return api.makeError(write_usage);
  1123. }
  1124. const path_str = argv[0].data.string;
  1125. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1126. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.writeFile: out of memory");
  1127. defer allocator.free(raw);
  1128. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.writeFile: not a Bytes");
  1129. return writeWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1130. }
  1131. fn modeArg(argc: u32, argv: [*]const HlValue) u32 {
  1132. if (argc >= 3 and argv[2].type == .hl_number) return @intFromFloat(argv[2].data.number);
  1133. return 0o600;
  1134. }
  1135. fn writeWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1136. const resolved = resolvePath(path) orelse return api.makeError("fs.writeFile: out of memory");
  1137. defer allocator.free(resolved);
  1138. // The temp name is a SIBLING (see the block comment): rename(2) is only
  1139. // atomic within one filesystem, and /tmp is routinely a different one.
  1140. // The pid keeps two processes writing the same path off each other's temp
  1141. // file; the rename itself settles who wins the target.
  1142. const pid = linux.getpid();
  1143. const tmp = std.fmt.allocPrintSentinel(allocator, "{s}.hltmp{d}", .{ resolved, pid }, 0) catch
  1144. return api.makeError("fs.writeFile: out of memory");
  1145. defer allocator.free(tmp);
  1146. const rc = linuxOpenRc(tmp.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode);
  1147. if (rc < 0) return makeWriteError("fs.writeFile", path, @intCast(-rc));
  1148. const fd: i32 = @intCast(rc);
  1149. var wrote: usize = 0;
  1150. while (wrote < body.len) {
  1151. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1152. if (n <= 0) {
  1153. _ = linux.close(fd);
  1154. _ = linux.unlink(tmp.ptr);
  1155. return makeWriteError("fs.writeFile", path, if (n < 0) @intCast(-n) else 5);
  1156. }
  1157. wrote += @intCast(n);
  1158. }
  1159. // fsync BEFORE the rename, or the rename can land while the bytes are
  1160. // still only in the page cache — a power cut then leaves an EMPTY file
  1161. // where a complete one used to be, which is worse than either outcome.
  1162. _ = linux.fsync(fd);
  1163. _ = linux.close(fd);
  1164. // O_CREAT honours the mode only through the umask; say it outright so a
  1165. // 0600 request is 0600 whatever the process umask happens to be.
  1166. _ = linux.chmod(tmp.ptr, mode);
  1167. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.writeFile: out of memory");
  1168. defer allocator.free(path_z);
  1169. const ren: isize = @bitCast(linux.rename(tmp.ptr, path_z.ptr));
  1170. if (ren < 0) {
  1171. _ = linux.unlink(tmp.ptr);
  1172. return makeWriteError("fs.writeFile", path, @intCast(-ren));
  1173. }
  1174. return api.makeBool(true);
  1175. }
  1176. const create_usage = "fs.createFile expects (String path, String or Bytes contents, Number mode?)";
  1177. export fn hl_fs_create_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1178. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1179. return api.makeError(create_usage);
  1180. }
  1181. const path_str = argv[0].data.string;
  1182. const body_str = argv[1].data.string;
  1183. return createWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1184. }
  1185. /// Bytes cross the plugin ABI as hex, just as writeFile does.
  1186. export fn hl_fs_create_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1187. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1188. return api.makeError(create_usage);
  1189. }
  1190. const path_str = argv[0].data.string;
  1191. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1192. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.createFile: out of memory");
  1193. defer allocator.free(raw);
  1194. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.createFile: not a Bytes");
  1195. return createWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1196. }
  1197. /// Exclusive creation publishes the path before writing its content.
  1198. fn createWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1199. const resolved = resolvePath(path) orelse return api.makeError("fs.createFile: out of memory");
  1200. defer allocator.free(resolved);
  1201. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.createFile: out of memory");
  1202. defer allocator.free(path_z);
  1203. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, mode);
  1204. if (rc == -17) return api.makeBool(false); // EEXIST: another creator won.
  1205. if (rc < 0) return makeWriteError("fs.createFile", path, @intCast(-rc));
  1206. const fd: i32 = @intCast(rc);
  1207. defer _ = linux.close(fd);
  1208. // Set the requested mode through the descriptor, even with a restrictive umask.
  1209. const chmod_rc: isize = @bitCast(linux.fchmod(fd, mode));
  1210. if (chmod_rc < 0) return makeWriteError("fs.createFile", path, @intCast(-chmod_rc));
  1211. var wrote: usize = 0;
  1212. while (wrote < body.len) {
  1213. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1214. if (n == -4) continue; // EINTR
  1215. if (n <= 0) {
  1216. return makeWriteError("fs.createFile", path, if (n < 0) @intCast(-n) else 5);
  1217. }
  1218. wrote += @intCast(n);
  1219. }
  1220. return api.makeBool(true);
  1221. }
  1222. const append_usage = "fs.appendFile expects (String path, String or Bytes contents, Number mode?)";
  1223. export fn hl_fs_append_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1224. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1225. return api.makeError(append_usage);
  1226. }
  1227. const path_str = argv[0].data.string;
  1228. const body_str = argv[1].data.string;
  1229. return appendWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1230. }
  1231. /// hl_fs_append_file_hex(path, hex, mode?) — appendFile with a Bytes (ticket
  1232. /// #88), the same hex-text crossing writeFile's hex sibling uses.
  1233. export fn hl_fs_append_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1234. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1235. return api.makeError(append_usage);
  1236. }
  1237. const path_str = argv[0].data.string;
  1238. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1239. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.appendFile: out of memory");
  1240. defer allocator.free(raw);
  1241. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.appendFile: not a Bytes");
  1242. return appendWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1243. }
  1244. /// APPEND, NOT ATOMIC BY RENAME (writeFile's block comment above): an append
  1245. /// MUTATES the file that is already there, so there is no whole "old" or
  1246. /// "new" version to swap in — O_APPEND gives a narrower guarantee instead.
  1247. /// The kernel positions a single write() at the file's CURRENT end and
  1248. /// performs it as one operation, so two processes each appending a line never
  1249. /// interleave their bytes mid-line and a reader never sees a torn append —
  1250. /// which is why this is ONE write() of the whole body where writeFile's is
  1251. /// (short-write retries aside). The file is created at `mode` (default 0600,
  1252. /// same default as writeFile) if it is not there yet; O_APPEND on an existing
  1253. /// file leaves its mode untouched, same as any other open of it.
  1254. fn appendWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1255. const resolved = resolvePath(path) orelse return api.makeError("fs.appendFile: out of memory");
  1256. defer allocator.free(resolved);
  1257. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.appendFile: out of memory");
  1258. defer allocator.free(path_z);
  1259. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, mode);
  1260. if (rc < 0) return makeWriteError("fs.appendFile", path, @intCast(-rc));
  1261. const fd: i32 = @intCast(rc);
  1262. defer _ = linux.close(fd);
  1263. var wrote: usize = 0;
  1264. while (wrote < body.len) {
  1265. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1266. if (n <= 0) {
  1267. return makeWriteError("fs.appendFile", path, if (n < 0) @intCast(-n) else 5);
  1268. }
  1269. wrote += @intCast(n);
  1270. }
  1271. return api.makeBool(true);
  1272. }
  1273. export fn hl_fs_remove(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1274. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.remove expects a string path");
  1275. const path_str = argv[0].data.string;
  1276. const path = path_str.ptr[0..path_str.len];
  1277. const resolved = resolvePath(path) orelse return api.makeError("fs.remove: out of memory");
  1278. defer allocator.free(resolved);
  1279. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.remove: out of memory");
  1280. defer allocator.free(path_z);
  1281. var rc: isize = @bitCast(linux.unlink(path_z.ptr));
  1282. // an empty directory goes too (EISDIR): hybriel.hl's scratch directories
  1283. // (mission 326 rung 12), with no `rmdir` to shell out to
  1284. if (rc == -21) rc = @bitCast(linux.rmdir(path_z.ptr));
  1285. if (rc < 0) {
  1286. const errno: usize = @intCast(-rc);
  1287. // ENOENT is success: the caller asked for the path to be gone.
  1288. if (errno == 2) return api.makeBool(true);
  1289. return makeWriteError("fs.remove", path, errno);
  1290. }
  1291. return api.makeBool(true);
  1292. }
  1293. /// realPath(path) → the canonical absolute path (symlinks resolved, `.`/`..`
  1294. /// folded; realpath(3)), or null when the path is not there or cannot be
  1295. /// resolved. `/proc/self/exe` answers the running binary without a shell.
  1296. export fn hl_fs_real_path(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1297. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  1298. const path_str = argv[0].data.string;
  1299. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  1300. defer allocator.free(resolved);
  1301. traceAccess('e', resolved);
  1302. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  1303. defer allocator.free(path_z);
  1304. var buf: [std.posix.PATH_MAX]u8 = undefined;
  1305. const out = std.c.realpath(path_z.ptr, &buf) orelse return api.makeNull();
  1306. const text = allocator.dupe(u8, std.mem.span(out)) catch return api.makeNull();
  1307. var result = api.makeString(text);
  1308. result.deinit_fn = &readFileDeinit;
  1309. return result;
  1310. }
  1311. test "wake burst fs buffered inotify events" {
  1312. const w = @import("wake_test");
  1313. const tmp = std.c.getenv("TMPDIR") orelse return error.NoScratchDirectory;
  1314. const dir = try std.fmt.allocPrintSentinel(allocator, "{s}/fs-wake-{d}", .{ std.mem.span(tmp), linux.getpid() }, 0);
  1315. defer allocator.free(dir);
  1316. _ = linux.mkdir(dir, 0o700);
  1317. defer _ = linux.rmdir(dir);
  1318. var passed: usize = 0;
  1319. for (0..10) |_| {
  1320. const args = [_]api.HlValue{api.makeString(dir)};
  1321. const v = hl_fs_watch(1, &args);
  1322. try std.testing.expect(v.type == .hl_iterator);
  1323. const it = v.data.iterator;
  1324. defer allocator.destroy(it);
  1325. defer watchDeinit(it.context);
  1326. // 32 creates fit in one read. There are no writes/close-write events.
  1327. for (0..32) |i| {
  1328. const path = try std.fmt.allocPrintSentinel(allocator, "{s}/{d}", .{ dir, i }, 0);
  1329. defer allocator.free(path);
  1330. const fd = linuxOpenRc(path, .{ .CREAT = true, .ACCMODE = .RDONLY }, 0o600);
  1331. try std.testing.expect(fd >= 0);
  1332. _ = linux.close(@intCast(fd));
  1333. }
  1334. if (w.burst(it.wake_fd, it.context, &watchTryNext, 32)) passed += 1;
  1335. for (0..32) |i| {
  1336. const path = try std.fmt.allocPrintSentinel(allocator, "{s}/{d}", .{ dir, i }, 0);
  1337. defer allocator.free(path);
  1338. _ = linux.unlink(path);
  1339. }
  1340. }
  1341. try w.result("fs inotify buffer", passed);
  1342. try w.require(&.{passed});
  1343. }

Branches

Latest commits

  • 85fa6c9blog: CB68 result, CB69 startedmre
  • 2f07c1b7log: DP68 boot gate failed, CB68mre
  • 9652782dlog: HM59 merged, DP68 startedmre
  • 29867a75Merge hm59-logic: tracker#59 page logic moved to libmre
  • f7bfe90bMove remaining page builders into their topicsmre
  • 7c3991f9log: day46 from Antonmre
  • ec54fc35Move show page logic into the shows topicmre
  • c1a8d074log: correct timesmre
  • 5827eba9log: HM57 merged, HM59 startedmre
  • d1a91be9Merge hm57-let: tracker#57 let only for reassigned namesmre
  • a404ed75Report HM57 audit, gates and integration notesmre
  • 1dcb87a7Use plain declarations for unchanged bindingsmre
  • b90395e3log: HM51 mergedmre
  • 9888d076Merge hm51-classes: tracker#51 views use Style referencesmre
  • 4399bc2fReference remaining component-owned root Style rulesmre
  • 9edcc2dflog: #58 live, HM57 startedmre
  • 73fa20ddMerge hm49b-styles: tracker#49 rest of the component stylesmre
  • aed12917Reference owned Style rules in genres and searchmre
  • 14195720log: HM49B done, HM51 startedmre
  • 78ee6b56Move remaining component styles into Style blocksmre