gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit76e0587a76e0587aWIP gs 2mre76e0587a/plugins/proc/proc.zig

56.9 KB

  1. // hl:proc — CHILD PROCESSES as instance events (creator API ruling 2026-08-17:
  2. // no eventloop plumbing in app code — `spawn()` hands back a Process the app
  3. // subscribes with `on process.line` / `on process.exit`, and `process.kill()`
  4. // is the stop button).
  5. //
  6. // Exports:
  7. // hl_proc_spawn(argv_list) → { pid, events } — events is a LOOP SOURCE
  8. // (wake_fd bell, the fetch-completions pattern)
  9. // delivering { line, stream } per output line and
  10. // a final { exit } when the child is gone
  11. // hl_proc_run(argv_list, o) → { exit, out, err } — BLOCKING: the whole output
  12. // once the child is gone (ticket #80)
  13. // hl_proc_kill(pid) → SIGTERM the child; the exit event still arrives
  14. //
  15. // One worker thread per child reads BOTH pipes with poll(), line-buffers, and
  16. // posts events into the spawn's OWN queue — nothing global, nothing shared
  17. // between children. No shell anywhere: argv is exec'd verbatim.
  18. const std = @import("std");
  19. const api = @import("plugin_api");
  20. const linux = std.os.linux;
  21. const libc = std.c;
  22. const PthreadMutex = libc.pthread_mutex_t;
  23. fn mutexLock(m: *PthreadMutex) void {
  24. _ = libc.pthread_mutex_lock(m);
  25. }
  26. fn mutexUnlock(m: *PthreadMutex) void {
  27. _ = libc.pthread_mutex_unlock(m);
  28. }
  29. const HlValue = api.HlValue;
  30. const HlObject = api.HlObject;
  31. const HlField = api.HlField;
  32. const HlIterator = api.HlIterator;
  33. const HlString = api.HlString;
  34. // the plugins' allocator (plugin_api.zig)
  35. const allocator = api.allocator;
  36. // SCRIPT-RELATIVE program paths (the Hybriel path rule — imports, hl:fs and
  37. // now spawn all resolve against the SCRIPT, not the process cwd): the loader
  38. // installs the script dir right after dlopen.
  39. var script_dir: ?[]u8 = null;
  40. export fn hl_proc_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  41. if (script_dir) |old| allocator.free(old);
  42. script_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  43. }
  44. // THE PROGRAM'S OWN DIRECTORY (ticket #37), absolute: the entry script's
  45. // directory on the interpreter, the executable's for a compiled binary. The
  46. // runtime hands it over right after dlopen; realpath makes it absolute.
  47. var program_dir: ?[]u8 = null;
  48. export fn hl_proc_set_program_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  49. const z = allocator.dupeZ(u8, ptr[0..len]) catch return;
  50. defer allocator.free(z);
  51. var buf: [4096]u8 = undefined;
  52. const r = c.realpath(z.ptr, &buf) orelse return;
  53. if (program_dir) |old| allocator.free(old);
  54. program_dir = allocator.dupe(u8, std.mem.span(r)) catch null;
  55. }
  56. /// hl_proc_dir() → the program's own directory, absolute.
  57. export fn hl_proc_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  58. _ = argc;
  59. _ = argv;
  60. const d = program_dir orelse return api.makeError("hl:proc dir: the runtime did not say where this program is");
  61. const copy = allocator.dupe(u8, d) catch return api.makeNull();
  62. return api.makeString(copy);
  63. }
  64. const c = struct {
  65. extern "c" fn realpath(path: [*:0]const u8, resolved: [*]u8) ?[*:0]u8;
  66. extern "c" fn fork() c_int;
  67. extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
  68. extern "c" fn execvpe(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int;
  69. extern "c" fn chdir(path: [*:0]const u8) c_int;
  70. extern "c" fn open(path: [*:0]const u8, flags: c_int, ...) c_int;
  71. extern "c" var environ: [*:null]?[*:0]const u8;
  72. extern "c" fn pipe(fds: *[2]c_int) c_int;
  73. extern "c" fn close(fd: c_int) c_int;
  74. extern "c" fn dup2(old: c_int, new: c_int) c_int;
  75. extern "c" fn kill(pid: c_int, sig: c_int) c_int;
  76. extern "c" fn waitpid(pid: c_int, status: ?*c_int, options: c_int) c_int;
  77. extern "c" fn _exit(code: c_int) noreturn;
  78. extern "c" fn fflush(stream: ?*anyopaque) c_int;
  79. extern "c" fn eventfd(initval: c_uint, flags: c_int) c_int;
  80. extern "c" fn fcntl(fd: c_int, cmd: c_int, arg: c_int) c_int;
  81. extern "c" fn strerror(errnum: c_int) [*:0]const u8;
  82. extern "c" fn signal(sig: c_int, handler: ?*const anyopaque) ?*const anyopaque;
  83. extern "c" fn write(fd: c_int, buf: [*]const u8, n: usize) isize;
  84. extern "c" fn read(fd: c_int, buf: [*]u8, n: usize) isize;
  85. extern "c" fn poll(fds: [*]PollFd, n: c_ulong, timeout: c_int) c_int;
  86. const PollFd = extern struct { fd: c_int, events: c_short, revents: c_short };
  87. };
  88. const POLLIN: c_short = 0x001;
  89. const POLLOUT: c_short = 0x004;
  90. const O_NONBLOCK: c_int = 0o4000;
  91. const EFD_NONBLOCK: c_int = 0o4000;
  92. fn hlStr(s: []const u8) HlString {
  93. return .{ .ptr = s.ptr, .len = s.len };
  94. }
  95. // ── one spawned child ────────────────────────────────────────────────────────
  96. const Event = struct {
  97. line: ?[]u8 = null, // owned
  98. /// `line` is a raw CHUNK of a binary child, not a line (ticket #42)
  99. chunk: bool = false,
  100. stream: []const u8 = "", // "out" | "err"
  101. exit_code: ?i32 = null,
  102. /// exec NEVER HAPPENED: the errno text. The child has no exit — this is
  103. /// the ONLY event, delivered as an hl_error so the loop routes it through
  104. /// `on x.Error` → `on Error` → located crash (creator ruling 2026-08-17).
  105. spawn_err: ?[]u8 = null,
  106. };
  107. const Child = struct {
  108. mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER,
  109. queue: std.ArrayListUnmanaged(Event) = .empty,
  110. wake_fd: i32 = -1,
  111. pid: i32 = 0,
  112. out_fd: i32 = -1,
  113. err_fd: i32 = -1,
  114. exec_fd: i32 = -1,
  115. argv0: []const u8 = "",
  116. /// `binary = true` (ticket #42): output goes out as raw chunks, never
  117. /// split into lines
  118. binary: bool = false,
  119. thread: ?std.Thread = null,
  120. /// the iterator was closed by the loop — the worker frees the Child when done
  121. done: bool = false,
  122. /// TWO OWNERS (efd439): the worker thread and the loop's iterator. Whoever lets go
  123. /// last closes the bell and frees the Child — before this, every spawn leaked its
  124. /// eventfd (hycon died of EMFILE with 1005 eventfds after two days).
  125. refs: std.atomic.Value(u32) = .init(2),
  126. fn release(self: *Child) void {
  127. if (self.refs.fetchSub(1, .acq_rel) != 1) return;
  128. if (self.wake_fd >= 0) _ = c.close(self.wake_fd);
  129. for (self.queue.items) |ev| {
  130. if (ev.line) |l| allocator.free(l);
  131. }
  132. self.queue.deinit(allocator);
  133. if (self.argv0.len > 0) allocator.free(self.argv0);
  134. allocator.destroy(self);
  135. }
  136. fn post(self: *Child, ev: Event) void {
  137. mutexLock(&self.mutex);
  138. self.queue.append(allocator, ev) catch {};
  139. mutexUnlock(&self.mutex);
  140. const one: u64 = 1;
  141. _ = c.write(self.wake_fd, @ptrCast(&one), 8);
  142. }
  143. };
  144. fn workerMain(ch: *Child) void {
  145. // the exec verdict first: BYTES on the CLOEXEC pipe = exec never happened
  146. {
  147. var eno: i32 = 0;
  148. const got = c.read(ch.exec_fd, @ptrCast(&eno), 4);
  149. _ = c.close(ch.exec_fd);
  150. if (got == 4) {
  151. var status: c_int = 0;
  152. _ = c.waitpid(ch.pid, &status, 0); // reap the stillborn child
  153. stdinClose(ch.pid);
  154. _ = c.close(ch.out_fd);
  155. _ = c.close(ch.err_fd);
  156. const msg = std.fmt.allocPrint(allocator, "hl:proc spawn: cannot start '{s}': {s}", .{ ch.argv0, std.mem.span(c.strerror(eno)) }) catch null;
  157. ch.post(.{ .spawn_err = msg orelse @constCast("hl:proc spawn failed") });
  158. ch.release();
  159. return;
  160. }
  161. }
  162. var bufs = [2]std.ArrayListUnmanaged(u8){ .empty, .empty };
  163. defer for (&bufs) |*b| b.deinit(allocator);
  164. const names = [2][]const u8{ "stdout", "stderr" };
  165. var fds = [2]i32{ ch.out_fd, ch.err_fd };
  166. var open_count: usize = 2;
  167. var rd: [4096]u8 = undefined;
  168. while (open_count > 0) {
  169. var pfds: [2]c.PollFd = undefined;
  170. var map: [2]usize = undefined;
  171. var n: usize = 0;
  172. for (fds, 0..) |fd, i| {
  173. if (fd < 0) continue;
  174. pfds[n] = .{ .fd = fd, .events = POLLIN, .revents = 0 };
  175. map[n] = i;
  176. n += 1;
  177. }
  178. const pr = c.poll(&pfds, n, -1);
  179. if (pr <= 0) continue;
  180. for (pfds[0..n], 0..) |pfd, pi| {
  181. if (pfd.revents == 0) continue;
  182. const i = map[pi];
  183. const got = c.read(pfd.fd, &rd, rd.len);
  184. if (got <= 0) {
  185. // EOF on this stream: flush a trailing unterminated line
  186. if (bufs[i].items.len > 0) {
  187. const line = textLine(bufs[i].items);
  188. if (line) |l| ch.post(.{ .line = l, .stream = names[i] });
  189. bufs[i].clearRetainingCapacity();
  190. }
  191. _ = c.close(pfd.fd);
  192. fds[i] = -1;
  193. open_count -= 1;
  194. continue;
  195. }
  196. const chunk = rd[0..@intCast(got)];
  197. if (ch.binary) {
  198. const copy = allocator.dupe(u8, chunk) catch null;
  199. if (copy) |b| ch.post(.{ .line = b, .stream = names[i], .chunk = true });
  200. continue;
  201. }
  202. var start: usize = 0;
  203. for (chunk, 0..) |ch2, k| {
  204. if (ch2 != '\n') continue;
  205. bufs[i].appendSlice(allocator, chunk[start..k]) catch {};
  206. const line = textLine(bufs[i].items);
  207. if (line) |l| ch.post(.{ .line = l, .stream = names[i] });
  208. bufs[i].clearRetainingCapacity();
  209. start = k + 1;
  210. }
  211. bufs[i].appendSlice(allocator, chunk[start..]) catch {};
  212. }
  213. }
  214. var status: c_int = 0;
  215. _ = c.waitpid(ch.pid, &status, 0);
  216. stdinClose(ch.pid);
  217. // POSIX status decode: exited → code, signalled → 128+sig (the shell rule)
  218. const code: i32 = if ((status & 0x7f) == 0) @intCast((status >> 8) & 0xff) else 128 + @as(i32, @intCast(status & 0x7f));
  219. ch.post(.{ .exit_code = code });
  220. ch.release();
  221. }
  222. // ── the loop source ──────────────────────────────────────────────────────────
  223. fn eventsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  224. const ch: *Child = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  225. // drain the bell (read may fail with EAGAIN — fine)
  226. var eat: [8]u8 = undefined;
  227. _ = c.read(ch.wake_fd, &eat, 8);
  228. mutexLock(&ch.mutex);
  229. if (ch.queue.items.len == 0) {
  230. mutexUnlock(&ch.mutex);
  231. return api.makeNull();
  232. }
  233. const ev = ch.queue.orderedRemove(0);
  234. mutexUnlock(&ch.mutex);
  235. if (ev.spawn_err) |msg| {
  236. return api.makeError(msg);
  237. }
  238. if (ev.exit_code) |code| {
  239. const fields = allocator.alloc(HlField, 2) catch return api.makeNull();
  240. fields[0] = .{ .key = hlStr("exit"), .value = api.makeNumber(@floatFromInt(code)) };
  241. fields[1] = .{ .key = hlStr("pid"), .value = api.makeNumber(@floatFromInt(ch.pid)) };
  242. const obj = allocator.create(HlObject) catch return api.makeNull();
  243. obj.* = .{ .fields = fields.ptr, .field_count = 2, .deinit_fn = null };
  244. return api.makeObject(obj);
  245. }
  246. const fields = allocator.alloc(HlField, 2) catch return api.makeNull();
  247. fields[0] = .{ .key = hlStr(if (ev.chunk) "chunk" else "line"), .value = api.makeString(ev.line orelse "") };
  248. fields[1] = .{ .key = hlStr("stream"), .value = api.makeString(ev.stream) };
  249. const obj = allocator.create(HlObject) catch return api.makeNull();
  250. obj.* = .{ .fields = fields.ptr, .field_count = 2, .deinit_fn = null };
  251. return api.makeObject(obj);
  252. }
  253. fn eventsDeinit(ctx: ?*anyopaque) callconv(.c) void {
  254. const ch: *Child = @ptrCast(@alignCast(ctx orelse return));
  255. ch.done = true;
  256. ch.release();
  257. }
  258. /// The child's environment: this process's own, with `overrides` applied —
  259. /// a String value sets NAME, a null removes it.
  260. fn buildEnv(overrides: *const HlObject) error{ NotAString, OutOfMemory }![:null]?[*:0]const u8 {
  261. var list = std.ArrayListUnmanaged(?[*:0]const u8).empty;
  262. var i: usize = 0;
  263. outer: while (c.environ[i]) |entry| : (i += 1) {
  264. const text = std.mem.span(entry);
  265. const eq = std.mem.indexOfScalar(u8, text, '=') orelse text.len;
  266. for (overrides.fields[0..overrides.field_count]) |f| {
  267. if (std.mem.eql(u8, f.key.ptr[0..f.key.len], text[0..eq])) continue :outer;
  268. }
  269. try list.append(allocator, entry);
  270. }
  271. for (overrides.fields[0..overrides.field_count]) |f| {
  272. if (f.value.type == .hl_null) continue;
  273. if (f.value.type != .hl_string) return error.NotAString;
  274. const v = f.value.data.string;
  275. const kv = try std.fmt.allocPrintSentinel(allocator, "{s}={s}", .{ f.key.ptr[0..f.key.len], v.ptr[0..v.len] }, 0);
  276. try list.append(allocator, kv.ptr);
  277. }
  278. return try list.toOwnedSliceSentinel(allocator, null);
  279. }
  280. // ── the children's stdin (ruling on ticket #42) ───────────────────────────────
  281. //
  282. // pid → our write end of that child's stdin pipe. Closed by end(), or when
  283. // the child exits (the worker reaps it).
  284. var stdin_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  285. var stdin_fds: std.AutoHashMapUnmanaged(i32, c_int) = .empty;
  286. var sigpipe_ignored = false;
  287. fn stdinRegister(pid: i32, fd: c_int) void {
  288. mutexLock(&stdin_mutex);
  289. defer mutexUnlock(&stdin_mutex);
  290. stdin_fds.put(allocator, pid, fd) catch {
  291. _ = c.close(fd);
  292. };
  293. }
  294. fn stdinClose(pid: i32) void {
  295. mutexLock(&stdin_mutex);
  296. defer mutexUnlock(&stdin_mutex);
  297. if (stdin_fds.fetchRemove(pid)) |kv| _ = c.close(kv.value);
  298. }
  299. fn stdinWrite(pid: i32, bytes: []const u8) HlValue {
  300. mutexLock(&stdin_mutex);
  301. const fd = stdin_fds.get(pid);
  302. if (!sigpipe_ignored) {
  303. _ = c.signal(13, @ptrFromInt(1)); // SIG_IGN: a closed pipe is EPIPE, not death
  304. sigpipe_ignored = true;
  305. }
  306. mutexUnlock(&stdin_mutex);
  307. const w = fd orelse return api.makeError("hl:proc write: this child's stdin is not open — spawn it with { stdin = 'pipe' }; end() or its exit closes it");
  308. var off: usize = 0;
  309. while (off < bytes.len) {
  310. const r = c.write(w, bytes[off..].ptr, bytes.len - off);
  311. if (r < 0) {
  312. const e: i32 = std.c._errno().*;
  313. if (e == 4) continue; // EINTR
  314. var buf: [160]u8 = undefined;
  315. const m = std.fmt.bufPrint(&buf, "hl:proc write: the child's stdin refused the bytes: {s}", .{std.mem.span(c.strerror(e))}) catch "hl:proc write failed";
  316. return api.makeError(m);
  317. }
  318. off += @intCast(r);
  319. }
  320. return api.makeNumber(@floatFromInt(bytes.len));
  321. }
  322. fn pidArg(argc: u32, argv: [*]const HlValue) ?i32 {
  323. if (argc < 1 or argv[0].type != .hl_number) return null;
  324. return @intFromFloat(argv[0].data.number);
  325. }
  326. /// hl_proc_write(pid, text) → bytes written; the String's bytes go as they are.
  327. export fn hl_proc_write(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  328. const pid = pidArg(argc, argv) orelse return api.makeError("hl:proc write: pass the pid spawn() returned");
  329. if (argc < 2 or argv[1].type != .hl_string) return api.makeError("hl:proc write: pass a String or a Bytes");
  330. const sv = argv[1].data.string;
  331. return stdinWrite(pid, sv.ptr[0..sv.len]);
  332. }
  333. /// A LINE IS TEXT, AND TEXT IS UTF-8 (ticket #47): a child printing latin-1 or
  334. /// binary bytes in text mode got them into a String unchecked, and the first
  335. /// such String that reached a page broke its WebSocket ("Could not decode a
  336. /// text frame as UTF-8"). Every byte that does not begin a valid sequence is
  337. /// replaced by U+FFFD here, where the bytes become text; `binary = true` is
  338. /// the way to the bytes themselves. Answers an owned copy, null on OOM.
  339. fn textLine(bytes: []const u8) ?[]u8 {
  340. if (std.unicode.utf8ValidateSlice(bytes)) return allocator.dupe(u8, bytes) catch null;
  341. var out = std.ArrayListUnmanaged(u8).empty;
  342. var k: usize = 0;
  343. while (k < bytes.len) {
  344. const n = std.unicode.utf8ByteSequenceLength(bytes[k]) catch 0;
  345. if (n > 0 and k + n <= bytes.len) {
  346. if (std.unicode.utf8Decode(bytes[k .. k + n])) |_| {
  347. out.appendSlice(allocator, bytes[k .. k + n]) catch return null;
  348. k += n;
  349. continue;
  350. } else |_| {}
  351. }
  352. out.appendSlice(allocator, "\xEF\xBF\xBD") catch return null;
  353. k += 1;
  354. }
  355. return out.toOwnedSlice(allocator) catch null;
  356. }
  357. /// hl_proc_write_hex(pid, hex) — a Bytes crosses the plugin boundary as its
  358. /// hex text (the ABI has no Bytes); decoded here, written raw.
  359. export fn hl_proc_write_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  360. const pid = pidArg(argc, argv) orelse return api.makeError("hl:proc write: pass the pid spawn() returned");
  361. if (argc < 2 or argv[1].type != .hl_string) return api.makeError("hl:proc write: pass a String or a Bytes");
  362. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  363. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("hl:proc: out of memory");
  364. defer allocator.free(raw);
  365. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("hl:proc write: not a Bytes");
  366. return stdinWrite(pid, raw);
  367. }
  368. /// This program's OWN stdout (fd 1) or stderr (fd 2), raw (ruling on ticket
  369. /// #42): the bytes go out as they are — no newline, no text form — so a
  370. /// program can speak a binary protocol on its stdout (git's stateless-rpc, a
  371. /// pipe to another tool) and report on stderr without mixing into it.
  372. fn fdWrite(fd: c_int, comptime name: []const u8, bytes: []const u8) HlValue {
  373. var off: usize = 0;
  374. while (off < bytes.len) {
  375. const r = c.write(fd, bytes[off..].ptr, bytes.len - off);
  376. if (r < 0) {
  377. const e: i32 = std.c._errno().*;
  378. if (e == 4) continue; // EINTR
  379. var buf: [160]u8 = undefined;
  380. const m = std.fmt.bufPrint(&buf, "hl:proc " ++ name ++ ": the stream refused the bytes: {s}", .{std.mem.span(c.strerror(e))}) catch "hl:proc " ++ name ++ " failed";
  381. return api.makeError(m);
  382. }
  383. off += @intCast(r);
  384. }
  385. return api.makeNumber(@floatFromInt(bytes.len));
  386. }
  387. fn textWrite(fd: c_int, comptime name: []const u8, argc: u32, argv: [*]const HlValue) HlValue {
  388. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:proc " ++ name ++ ": pass a String or a Bytes");
  389. const sv = argv[0].data.string;
  390. return fdWrite(fd, name, sv.ptr[0..sv.len]);
  391. }
  392. fn hexWrite(fd: c_int, comptime name: []const u8, argc: u32, argv: [*]const HlValue) HlValue {
  393. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:proc " ++ name ++ ": pass a String or a Bytes");
  394. const hex = argv[0].data.string.ptr[0..argv[0].data.string.len];
  395. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("hl:proc: out of memory");
  396. defer allocator.free(raw);
  397. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("hl:proc " ++ name ++ ": not a Bytes");
  398. return fdWrite(fd, name, raw);
  399. }
  400. /// hl_proc_write_stdout(text) / hl_proc_write_stdout_hex(hex) — see fdWrite.
  401. export fn hl_proc_write_stdout(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  402. return textWrite(1, "writeStdout", argc, argv);
  403. }
  404. export fn hl_proc_write_stdout_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  405. return hexWrite(1, "writeStdout", argc, argv);
  406. }
  407. /// hl_proc_write_stderr(text) / hl_proc_write_stderr_hex(hex) — the same on fd 2.
  408. export fn hl_proc_write_stderr(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  409. return textWrite(2, "writeStderr", argc, argv);
  410. }
  411. export fn hl_proc_write_stderr_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  412. return hexWrite(2, "writeStderr", argc, argv);
  413. }
  414. /// hl_proc_end(pid) — close the child's stdin: it reads EOF.
  415. export fn hl_proc_end(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  416. const pid = pidArg(argc, argv) orelse return api.makeError("hl:proc end: pass the pid spawn() returned");
  417. stdinClose(pid);
  418. return api.makeNull();
  419. }
  420. // ── exports ──────────────────────────────────────────────────────────────────
  421. /// A command, parsed and resolved, ready to fork: what `spawn` and `run` share.
  422. /// Everything is allocated BEFORE the fork; the child only calls chdir and exec.
  423. const Prepared = struct {
  424. cargv: []?[*:0]const u8 = &.{},
  425. cwd_z: ?[:0]u8 = null,
  426. envp: ?[:null]?[*:0]const u8 = null,
  427. binary: bool = false,
  428. stdin_pipe: bool = false,
  429. /// `run` only: milliseconds, or -1 for no limit
  430. timeout_ms: i64 = -1,
  431. /// `run` only (ticket #91): the bytes its stdin reads, then EOF; null is /dev/null
  432. stdin_data: ?[]u8 = null,
  433. fn deinit(self: *Prepared) void {
  434. for (self.cargv) |a| if (a) |z| allocator.free(std.mem.span(z));
  435. if (self.cargv.len > 0) allocator.free(self.cargv);
  436. if (self.cwd_z) |d| allocator.free(d);
  437. if (self.envp) |ev| allocator.free(ev);
  438. if (self.stdin_data) |d| allocator.free(d);
  439. }
  440. };
  441. /// Parse the command (a STRING or a LIST) and the options for `verb`
  442. /// ("spawn" or "run"). Answers null when `out` is ready, or the Error to hand
  443. /// back. `spawn` takes `stdin` ('pipe' or 'inherit'), `run` takes `timeout`
  444. /// and `stdin` (its bytes — server.hl hands them as argv[2], hex); both take
  445. /// cwd, env and binary.
  446. fn prepare(comptime verb: []const u8, argc: u32, argv: [*]const HlValue, out: *Prepared) ?HlValue {
  447. const is_run = comptime std.mem.eql(u8, verb, "run");
  448. // Accepts BOTH forms: a STRING (split on ANY whitespace run — spaces,
  449. // tabs, NEWLINES: a long command written across lines, the multi-line-
  450. // string way, is one command) or a LIST (an object with numeric keys —
  451. // the loader's valueArrayToHl contract) for arguments that contain spaces.
  452. if (argc < 1) return api.makeError("hl:proc " ++ verb ++ ": pass a command string or an argv list");
  453. var parts = std.ArrayListUnmanaged([]const u8).empty;
  454. defer parts.deinit(allocator);
  455. if (argv[0].type == .hl_string) {
  456. // whitespace-run tokens, with QUOTE GROUPING: a token opening with
  457. // ' or " runs (whitespace included) to the matching close, quotes
  458. // stripped — one argument. NOT a shell: no expansion, no nesting,
  459. // no substitution; just grouping, the way a command line reads.
  460. const sv0 = argv[0].data.string;
  461. const text0 = sv0.ptr[0..sv0.len];
  462. var pos: usize = 0;
  463. while (pos < text0.len) {
  464. const chx = text0[pos];
  465. if (chx == ' ' or chx == '\t' or chx == '\r' or chx == '\n') {
  466. pos += 1;
  467. continue;
  468. }
  469. if (chx == '\'' or chx == '"') {
  470. const close = std.mem.indexOfScalarPos(u8, text0, pos + 1, chx) orelse
  471. return api.makeError("hl:proc " ++ verb ++ ": unclosed quote in the command string");
  472. parts.append(allocator, text0[pos + 1 .. close]) catch return api.makeError("hl:proc: out of memory");
  473. pos = close + 1;
  474. continue;
  475. }
  476. var end = pos;
  477. while (end < text0.len and text0[end] != ' ' and text0[end] != '\t' and text0[end] != '\r' and text0[end] != '\n') end += 1;
  478. parts.append(allocator, text0[pos..end]) catch return api.makeError("hl:proc: out of memory");
  479. pos = end;
  480. }
  481. } else if (argv[0].type == .hl_object) {
  482. const obj_in = argv[0].data.object;
  483. for (obj_in.fields[0..obj_in.field_count]) |field| {
  484. if (field.value.type != .hl_string) return api.makeError("hl:proc " ++ verb ++ ": argv entries must be strings");
  485. const sv = field.value.data.string;
  486. parts.append(allocator, sv.ptr[0..sv.len]) catch return api.makeError("hl:proc: out of memory");
  487. }
  488. } else {
  489. return api.makeError("hl:proc " ++ verb ++ ": pass a command string or an argv list");
  490. }
  491. const n_args: usize = parts.items.len;
  492. if (n_args == 0) return api.makeError("hl:proc " ++ verb ++ ": empty command");
  493. // NUL-terminated argv for exec, before the fork (no allocation after fork)
  494. const cargv = allocator.alloc(?[*:0]const u8, n_args + 1) catch return api.makeError("hl:proc: out of memory");
  495. @memset(cargv, null);
  496. out.cargv = cargv;
  497. for (parts.items, 0..) |part, i| {
  498. var text: []const u8 = part;
  499. // THE PROGRAM (argv[0]): a path containing '/' that is not absolute
  500. // resolves against the SCRIPT's directory — the same rule every other
  501. // Hybriel path follows. A bare name searches PATH (exec semantics).
  502. var resolved: ?[]u8 = null;
  503. defer if (resolved) |r| allocator.free(r);
  504. if (i == 0 and text.len > 0 and text[0] != '/' and std.mem.indexOfScalar(u8, text, '/') != null) {
  505. if (script_dir) |sd| {
  506. resolved = std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, text }) catch null;
  507. if (resolved) |r| text = r;
  508. }
  509. }
  510. const z = allocator.dupeZ(u8, text) catch return api.makeError("hl:proc: out of memory");
  511. cargv[i] = z.ptr;
  512. }
  513. // THE OPTIONS (ruling on ticket #37): `{ cwd, env }`, both optional.
  514. // `cwd` is where the child starts — a relative one resolves against the
  515. // SCRIPT's directory, like the program path. `env` is added to the
  516. // environment the child inherits: a String sets the variable, null
  517. // removes it.
  518. if (argc >= 2 and argv[1].type == .hl_object) {
  519. const opts = argv[1].data.object;
  520. for (opts.fields[0..opts.field_count]) |field| {
  521. const key = field.key.ptr[0..field.key.len];
  522. if (!is_run and std.mem.eql(u8, key, "stdin")) {
  523. if (field.value.type == .hl_null) continue;
  524. const v = if (field.value.type == .hl_string) field.value.data.string.ptr[0..field.value.data.string.len] else "";
  525. if (std.mem.eql(u8, v, "pipe")) {
  526. out.stdin_pipe = true;
  527. } else if (!std.mem.eql(u8, v, "inherit")) {
  528. return api.makeError("hl:proc spawn: options.stdin is 'pipe' (write() and end() feed it) or 'inherit' (the default)");
  529. }
  530. } else if (is_run and std.mem.eql(u8, key, "stdin")) {
  531. // server.hl moved a String or a Bytes out to argv[2]; anything left here is neither
  532. if (field.value.type == .hl_null) continue;
  533. return api.makeError("hl:proc run: options.stdin is a String or a Bytes — what the program reads before EOF");
  534. } else if (is_run and std.mem.eql(u8, key, "timeout")) {
  535. if (field.value.type == .hl_null) continue;
  536. if (field.value.type != .hl_number or !(field.value.data.number > 0)) return api.makeError("hl:proc run: options.timeout is a Number of seconds greater than 0");
  537. out.timeout_ms = @intFromFloat(@ceil(field.value.data.number * 1000));
  538. } else if (std.mem.eql(u8, key, "binary")) {
  539. if (field.value.type == .hl_null) continue;
  540. if (field.value.type != .hl_bool) return api.makeError("hl:proc " ++ verb ++ ": options.binary must be true or false");
  541. out.binary = field.value.data.boolean;
  542. } else if (std.mem.eql(u8, key, "cwd")) {
  543. if (field.value.type == .hl_null) continue;
  544. if (field.value.type != .hl_string) return api.makeError("hl:proc " ++ verb ++ ": options.cwd must be a String");
  545. const d = field.value.data.string.ptr[0..field.value.data.string.len];
  546. out.cwd_z = if (d.len > 0 and d[0] != '/' and script_dir != null)
  547. std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ script_dir.?, d }, 0) catch return api.makeError("hl:proc: out of memory")
  548. else
  549. allocator.dupeZ(u8, d) catch return api.makeError("hl:proc: out of memory");
  550. } else if (std.mem.eql(u8, key, "env")) {
  551. if (field.value.type == .hl_null) continue;
  552. if (field.value.type != .hl_object) return api.makeError("hl:proc " ++ verb ++ ": options.env must be a hybrid of NAME = value");
  553. out.envp = buildEnv(field.value.data.object) catch |e| return api.makeError(switch (e) {
  554. error.NotAString => "hl:proc " ++ verb ++ ": an options.env value must be a String (or null to remove the variable)",
  555. else => "hl:proc: out of memory",
  556. });
  557. } else {
  558. const known = if (is_run) "cwd, env, binary, stdin and timeout" else "cwd, env, stdin and binary";
  559. // allocated, not on this stack: the runtime reads the message after we return
  560. const m = std.fmt.allocPrint(allocator, "hl:proc " ++ verb ++ ": unknown option '{s}' — the options are {s}", .{ key, known }) catch "hl:proc " ++ verb ++ ": unknown option";
  561. return api.makeError(m);
  562. }
  563. }
  564. }
  565. // run's stdin (ticket #91): a String's or a Bytes' bytes, crossing as hex
  566. if (is_run and argc >= 3 and argv[2].type == .hl_string) {
  567. const hex = argv[2].data.string.ptr[0..argv[2].data.string.len];
  568. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("hl:proc: out of memory");
  569. out.stdin_data = raw;
  570. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("hl:proc run: options.stdin is a String or a Bytes");
  571. }
  572. return null;
  573. }
  574. fn monoMs() i64 {
  575. var ts: linux.timespec = undefined;
  576. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  577. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  578. }
  579. /// What the forked child does with its stdin: the parent's (spawn's default),
  580. /// a pipe the program writes (spawn's `stdin = 'pipe'`, run's `stdin = data`),
  581. /// or nothing at all — `run` without `stdin` gives /dev/null, because a child
  582. /// that waited for input would hold the caller for as long as nobody typed.
  583. const StdinMode = enum { inherit, pipe, devnull };
  584. /// The pipes of one fork: our ends are out[0], err[0], exec[0] and in[1].
  585. const Pipes = struct {
  586. out: [2]c_int = .{ -1, -1 },
  587. err: [2]c_int = .{ -1, -1 },
  588. exec: [2]c_int = .{ -1, -1 }, // the exec-failure channel (CLOEXEC)
  589. in: [2]c_int = .{ -1, -1 },
  590. };
  591. /// fork + exec the prepared command. Answers the pid (< 0: fork failed) with
  592. /// the parent's ends of `pipes` open and the child's closed.
  593. fn forkExec(p: *const Prepared, mode: StdinMode, pipes: *Pipes) c_int {
  594. const parent = linux.getpid();
  595. const pid = c.fork();
  596. if (pid != 0) return pid;
  597. // DIE WITH THE PARENT (2026-08-17): a supervisor that crashes or is
  598. // Ctrl-C'd must not leave orphaned llama-servers squatting on ports —
  599. // the kernel sends the child SIGTERM when hybriel exits, any exit.
  600. _ = linux.prctl(1, 15, 0, 0, 0); // PR_SET_PDEATHSIG = 1, SIGTERM = 15
  601. // the parent may have died BEFORE the prctl above (the signal is only for a death after it):
  602. // then this child is already adopted by init and must not run on
  603. if (linux.getppid() != parent) c._exit(143);
  604. // the CHILD: pipes onto stdout/stderr, exec verbatim — no shell
  605. _ = c.dup2(pipes.out[1], 1);
  606. _ = c.dup2(pipes.err[1], 2);
  607. switch (mode) {
  608. .inherit => {},
  609. .pipe => {
  610. _ = c.dup2(pipes.in[0], 0);
  611. _ = c.close(pipes.in[0]);
  612. _ = c.close(pipes.in[1]);
  613. },
  614. .devnull => {
  615. const fd = c.open("/dev/null", 0);
  616. if (fd >= 0) {
  617. _ = c.dup2(fd, 0);
  618. _ = c.close(fd);
  619. }
  620. },
  621. }
  622. // this process ignores SIGPIPE once it has written to a child (a
  623. // child that stopped reading must not kill it); an ignored signal
  624. // survives exec, so the child gets the default back.
  625. _ = c.signal(13, null);
  626. _ = c.close(pipes.out[0]);
  627. _ = c.close(pipes.out[1]);
  628. _ = c.close(pipes.err[0]);
  629. _ = c.close(pipes.err[1]);
  630. _ = c.close(pipes.exec[0]);
  631. if (p.cwd_z) |d| {
  632. if (c.chdir(d.ptr) != 0) {
  633. const e: i32 = std.c._errno().*;
  634. _ = c.write(pipes.exec[1], @ptrCast(&e), 4);
  635. c._exit(127);
  636. }
  637. }
  638. if (p.envp) |ev| {
  639. _ = c.execvpe(p.cargv[0].?, @ptrCast(p.cargv.ptr), @ptrCast(ev.ptr));
  640. } else {
  641. _ = c.execvp(p.cargv[0].?, @ptrCast(p.cargv.ptr));
  642. }
  643. // exec failed: write errno through the CLOEXEC pipe — a successful
  644. // exec closed it, so the parent reading BYTES means "never started"
  645. const e: i32 = std.c._errno().*;
  646. _ = c.write(pipes.exec[1], @ptrCast(&e), 4);
  647. c._exit(127);
  648. }
  649. /// hl_proc_spawn(argvList) → { pid, events }
  650. export fn hl_proc_spawn(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  651. // the child never returns here (exec or _exit), and the argv strings stay
  652. // with the spawn for its lifetime; the options' allocations are the parent's
  653. var p = Prepared{};
  654. if (prepare("spawn", argc, argv, &p)) |err| return err;
  655. defer if (p.cwd_z) |d| allocator.free(d);
  656. defer if (p.envp) |ev| allocator.free(ev);
  657. var pipes = Pipes{};
  658. // the child's stdin (ticket #42): INHERITED unless `stdin = 'pipe'`, so a
  659. // child that reads until EOF never waits on a pipe nobody asked for
  660. if (c.pipe(&pipes.out) != 0 or c.pipe(&pipes.err) != 0 or c.pipe(&pipes.exec) != 0 or (p.stdin_pipe and c.pipe(&pipes.in) != 0)) {
  661. return api.makeError("hl:proc spawn: pipe() failed");
  662. }
  663. _ = c.fcntl(pipes.exec[1], 2, 1); // F_SETFD FD_CLOEXEC: closes ITSELF on a successful exec
  664. // OUR end of the child's stdin must not leak into LATER children, or the
  665. // child never sees EOF while a sibling still holds a copy of it.
  666. if (p.stdin_pipe) _ = c.fcntl(pipes.in[1], 2, 1);
  667. const pid = forkExec(&p, if (p.stdin_pipe) .pipe else .inherit, &pipes);
  668. if (pid < 0) return api.makeError("hl:proc spawn: fork() failed");
  669. _ = c.close(pipes.out[1]);
  670. _ = c.close(pipes.err[1]);
  671. _ = c.close(pipes.exec[1]);
  672. if (p.stdin_pipe) {
  673. _ = c.close(pipes.in[0]);
  674. stdinRegister(pid, pipes.in[1]);
  675. }
  676. const ch = allocator.create(Child) catch return api.makeError("hl:proc: out of memory");
  677. ch.* = .{
  678. .wake_fd = c.eventfd(0, EFD_NONBLOCK),
  679. .pid = pid,
  680. .out_fd = pipes.out[0],
  681. .err_fd = pipes.err[0],
  682. .exec_fd = pipes.exec[0],
  683. .argv0 = allocator.dupe(u8, std.mem.span(p.cargv[0].?)) catch "",
  684. .binary = p.binary,
  685. };
  686. ch.thread = std.Thread.spawn(.{}, workerMain, .{ch}) catch {
  687. return api.makeError("hl:proc spawn: worker thread failed");
  688. };
  689. if (ch.thread) |t| t.detach();
  690. const iter = allocator.create(HlIterator) catch return api.makeError("hl:proc: out of memory");
  691. iter.* = .{
  692. .context = @ptrCast(ch),
  693. .next_fn = &eventsTryNext,
  694. .deinit_fn = &eventsDeinit,
  695. .try_next_fn = &eventsTryNext,
  696. .wake_fd = ch.wake_fd,
  697. };
  698. const fields = allocator.alloc(HlField, 2) catch return api.makeNull();
  699. fields[0] = .{ .key = hlStr("pid"), .value = api.makeNumber(@floatFromInt(pid)) };
  700. fields[1] = .{ .key = hlStr("events"), .value = api.makeIterator(iter) };
  701. const obj = allocator.create(HlObject) catch return api.makeNull();
  702. obj.* = .{ .fields = fields.ptr, .field_count = 2, .deinit_fn = null };
  703. return api.makeObject(obj);
  704. }
  705. /// hl_proc_run(argvList, options) → { exit, out, err } — THE BLOCKING RUN
  706. /// (ticket #80). Starts the command like spawn, reads BOTH pipes to their end
  707. /// on the calling thread, reaps the child and answers everything at once:
  708. /// `out` and `err` are the whole streams as they were written (server.hl
  709. /// splits them into lines, or hands `out` over as Bytes). The wait is a wait
  710. /// like fetch's `result()`: it holds the fiber that asked, which is what lets
  711. /// a page's root read a program's output while it is being constructed.
  712. ///
  713. /// `timeout` (seconds) bounds the whole run: past it the child is killed
  714. /// (SIGKILL — a program that ignores SIGTERM must not hold the caller) and the
  715. /// call is an Error naming the program and the limit.
  716. ///
  717. /// `stdin` (ticket #91): the bytes are written to the child's stdin in the
  718. /// same poll loop that drains its output — a program that answers as it reads
  719. /// (cat, git upload-pack) fills its stdout pipe long before it has read a big
  720. /// input, and a write-everything-first would wait on it forever — and the pipe
  721. /// is closed once they are all written, so the program reads EOF. A program
  722. /// that exits or closes its stdin without reading them all is not an error:
  723. /// the rest is dropped and its `exit` says what happened.
  724. export fn hl_proc_run(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  725. var p = Prepared{};
  726. defer p.deinit();
  727. if (prepare("run", argc, argv, &p)) |err| return err;
  728. var pipes = Pipes{};
  729. const feed = p.stdin_data != null;
  730. if (c.pipe(&pipes.out) != 0 or c.pipe(&pipes.err) != 0 or c.pipe(&pipes.exec) != 0 or (feed and c.pipe(&pipes.in) != 0)) {
  731. return api.makeError("hl:proc run: pipe() failed");
  732. }
  733. // ALL of our ends are close-on-exec: a child that a spawn() starts while
  734. // this run is reading must not hold our pipes open past our child's exit
  735. _ = c.fcntl(pipes.exec[1], 2, 1);
  736. _ = c.fcntl(pipes.out[0], 2, 1);
  737. _ = c.fcntl(pipes.err[0], 2, 1);
  738. _ = c.fcntl(pipes.exec[0], 2, 1);
  739. if (feed) {
  740. _ = c.fcntl(pipes.in[1], 2, 1);
  741. // a child that stops reading must not kill this process (EPIPE instead)
  742. mutexLock(&stdin_mutex);
  743. if (!sigpipe_ignored) {
  744. _ = c.signal(13, @ptrFromInt(1)); // SIG_IGN
  745. sigpipe_ignored = true;
  746. }
  747. mutexUnlock(&stdin_mutex);
  748. }
  749. const pid = forkExec(&p, if (feed) .pipe else .devnull, &pipes);
  750. if (pid < 0) return api.makeError("hl:proc run: fork() failed");
  751. _ = c.close(pipes.out[1]);
  752. _ = c.close(pipes.err[1]);
  753. _ = c.close(pipes.exec[1]);
  754. var in_fd: c_int = -1;
  755. if (feed) {
  756. _ = c.close(pipes.in[0]);
  757. in_fd = pipes.in[1];
  758. _ = c.fcntl(in_fd, 4, O_NONBLOCK); // F_SETFL: written as the pipe takes it
  759. }
  760. defer if (in_fd >= 0) {
  761. _ = c.close(in_fd);
  762. };
  763. const in_data: []const u8 = p.stdin_data orelse "";
  764. var in_off: usize = 0;
  765. if (feed and in_data.len == 0) {
  766. _ = c.close(in_fd);
  767. in_fd = -1;
  768. }
  769. const argv0 = std.mem.span(p.cargv[0].?);
  770. // the exec verdict first: BYTES on the CLOEXEC pipe = exec never happened
  771. {
  772. var eno: i32 = 0;
  773. const got = c.read(pipes.exec[0], @ptrCast(&eno), 4);
  774. _ = c.close(pipes.exec[0]);
  775. if (got == 4) {
  776. var status: c_int = 0;
  777. _ = c.waitpid(pid, &status, 0);
  778. _ = c.close(pipes.out[0]);
  779. _ = c.close(pipes.err[0]);
  780. if (in_fd >= 0) _ = c.close(in_fd);
  781. in_fd = -1;
  782. const m = std.fmt.allocPrint(allocator, "hl:proc run: cannot start '{s}': {s}", .{ argv0, std.mem.span(c.strerror(eno)) }) catch "hl:proc run: cannot start the program";
  783. return api.makeError(m);
  784. }
  785. }
  786. var bufs = [2]std.ArrayListUnmanaged(u8){ .empty, .empty };
  787. defer for (&bufs) |*b| b.deinit(allocator);
  788. var fds = [2]i32{ pipes.out[0], pipes.err[0] };
  789. var open_count: usize = 2;
  790. const started = monoMs();
  791. var timed_out = false;
  792. var rd: [8192]u8 = undefined;
  793. // a child may close its output and still be reading: feeding ends it, not the pipes
  794. while (open_count > 0 or in_fd >= 0) {
  795. var wait_ms: c_int = -1;
  796. if (p.timeout_ms >= 0) {
  797. const left = p.timeout_ms - (monoMs() - started);
  798. if (left <= 0) {
  799. timed_out = true;
  800. break;
  801. }
  802. wait_ms = @intCast(@min(left, std.math.maxInt(c_int)));
  803. }
  804. var pfds: [3]c.PollFd = undefined;
  805. var map: [3]usize = undefined;
  806. var n: usize = 0;
  807. for (fds, 0..) |fd, i| {
  808. if (fd < 0) continue;
  809. pfds[n] = .{ .fd = fd, .events = POLLIN, .revents = 0 };
  810. map[n] = i;
  811. n += 1;
  812. }
  813. if (in_fd >= 0) {
  814. pfds[n] = .{ .fd = in_fd, .events = POLLOUT, .revents = 0 };
  815. map[n] = 2;
  816. n += 1;
  817. }
  818. const pr = c.poll(&pfds, n, wait_ms);
  819. if (pr <= 0) continue; // a timeout is decided at the top; EINTR retries
  820. for (pfds[0..n], 0..) |pfd, pi| {
  821. if (pfd.revents == 0) continue;
  822. const i = map[pi];
  823. if (i == 2) {
  824. // the child's stdin has room (or is gone: the write says EPIPE)
  825. const w = c.write(in_fd, in_data[in_off..].ptr, in_data.len - in_off);
  826. if (w > 0) in_off += @intCast(w);
  827. const e: i32 = if (w < 0) std.c._errno().* else 0;
  828. if (in_off >= in_data.len or (w < 0 and e != 4 and e != 11)) { // done, or not EINTR/EAGAIN
  829. _ = c.close(in_fd);
  830. in_fd = -1;
  831. }
  832. continue;
  833. }
  834. const got = c.read(pfd.fd, &rd, rd.len);
  835. if (got <= 0) {
  836. _ = c.close(pfd.fd);
  837. fds[i] = -1;
  838. open_count -= 1;
  839. continue;
  840. }
  841. bufs[i].appendSlice(allocator, rd[0..@intCast(got)]) catch return api.makeError("hl:proc: out of memory");
  842. }
  843. }
  844. for (fds) |fd| if (fd >= 0) {
  845. _ = c.close(fd);
  846. };
  847. if (in_fd >= 0) {
  848. _ = c.close(in_fd);
  849. in_fd = -1;
  850. }
  851. if (timed_out) _ = c.kill(pid, 9);
  852. var status: c_int = 0;
  853. _ = c.waitpid(pid, &status, 0);
  854. if (timed_out) {
  855. const secs = @as(f64, @floatFromInt(p.timeout_ms)) / 1000.0;
  856. const m = std.fmt.allocPrint(allocator, "hl:proc run: '{s}' did not finish within {d} s (options.timeout) — it was killed", .{ argv0, secs }) catch "hl:proc run: the program did not finish within its timeout";
  857. return api.makeError(m);
  858. }
  859. // POSIX status decode: exited → code, signalled → 128+sig (the shell rule)
  860. const code: i32 = if ((status & 0x7f) == 0) @intCast((status >> 8) & 0xff) else 128 + @as(i32, @intCast(status & 0x7f));
  861. const fields = allocator.alloc(HlField, 3) catch return api.makeError("hl:proc: out of memory");
  862. fields[0] = .{ .key = hlStr("exit"), .value = api.makeNumber(@floatFromInt(code)) };
  863. fields[1] = .{ .key = hlStr("out"), .value = api.makeString(bufs[0].toOwnedSlice(allocator) catch "") };
  864. fields[2] = .{ .key = hlStr("err"), .value = api.makeString(bufs[1].toOwnedSlice(allocator) catch "") };
  865. const obj = allocator.create(HlObject) catch return api.makeError("hl:proc: out of memory");
  866. obj.* = .{ .fields = fields.ptr, .field_count = 3, .deinit_fn = null };
  867. return api.makeObject(obj);
  868. }
  869. /// hl_proc_exit(code) — end this program now with that exit status (ruling
  870. /// on ticket #36). The buffered C streams are flushed, then _exit (ticket
  871. /// #420): libc's exit would run OPENSSL_cleanup and the other destructors
  872. /// under live worker threads (fetch/TLS, detached readers), which crashed a
  873. /// production shutdown. Nothing the program would have done later runs.
  874. export fn hl_proc_exit(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  875. var code: c_int = 0;
  876. if (argc >= 1) {
  877. if (argv[0].type != .hl_number) return api.makeError("hl:proc exit: the status must be a Number (0-255)");
  878. const n = argv[0].data.number;
  879. if (n != @floor(n) or n < 0 or n > 255) return api.makeError("hl:proc exit: the status must be a whole Number from 0 to 255");
  880. code = @intFromFloat(n);
  881. }
  882. _ = c.fflush(null);
  883. c._exit(code);
  884. }
  885. /// hl_proc_exec(argv, options?) — THIS PROCESS BECOMES THE PROGRAM (mission
  886. /// 326 rung 12: hybriel's run form hands the terminal to the binary it built,
  887. /// so its output streams, its stdin is the caller's and its exit status is
  888. /// the run's). `argv` is a list; argv[0] is a path (resolved like spawn's) or
  889. /// a name searched on PATH. `{ cwd }` is where it starts; `{ unlink = true }`
  890. /// opens argv[0], removes the file and runs it from the open descriptor, so
  891. /// a scratch binary leaves nothing behind. Answers only when exec failed: an
  892. /// Error naming why.
  893. export fn hl_proc_exec(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  894. if (argc < 1 or argv[0].type != .hl_object) return api.makeError("hl:proc exec: pass an argv list");
  895. const list = argv[0].data.object;
  896. if (list.field_count == 0) return api.makeError("hl:proc exec: empty argv");
  897. const cargv = allocator.alloc(?[*:0]const u8, list.field_count + 1) catch return api.makeError("hl:proc: out of memory");
  898. @memset(cargv, null);
  899. for (list.fields[0..list.field_count], 0..) |field, i| {
  900. if (field.value.type != .hl_string) return api.makeError("hl:proc exec: argv entries must be strings");
  901. const sv = field.value.data.string;
  902. var text: []const u8 = sv.ptr[0..sv.len];
  903. if (i == 0 and text.len > 0 and text[0] != '/' and std.mem.indexOfScalar(u8, text, '/') != null) {
  904. if (script_dir) |sd| text = std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, text }) catch return api.makeError("hl:proc: out of memory");
  905. }
  906. cargv[i] = (allocator.dupeZ(u8, text) catch return api.makeError("hl:proc: out of memory")).ptr;
  907. }
  908. var unlink_it = false;
  909. var argv0_z: ?[:0]u8 = null;
  910. var cwd_z: ?[:0]u8 = null;
  911. if (argc >= 2 and argv[1].type == .hl_object) {
  912. const opts = argv[1].data.object;
  913. for (opts.fields[0..opts.field_count]) |field| {
  914. const key = field.key.ptr[0..field.key.len];
  915. if (field.value.type == .hl_null) continue;
  916. if (std.mem.eql(u8, key, "unlink")) {
  917. if (field.value.type != .hl_bool) return api.makeError("hl:proc exec: options.unlink must be true or false");
  918. unlink_it = field.value.data.boolean;
  919. } else if (std.mem.eql(u8, key, "argv0")) {
  920. if (field.value.type != .hl_string) return api.makeError("hl:proc exec: options.argv0 must be a String");
  921. argv0_z = allocator.dupeZ(u8, field.value.data.string.ptr[0..field.value.data.string.len]) catch return api.makeError("hl:proc: out of memory");
  922. } else if (std.mem.eql(u8, key, "cwd")) {
  923. if (field.value.type != .hl_string) return api.makeError("hl:proc exec: options.cwd must be a String");
  924. const d = field.value.data.string.ptr[0..field.value.data.string.len];
  925. cwd_z = if (d.len > 0 and d[0] != '/' and script_dir != null)
  926. std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ script_dir.?, d }, 0) catch return api.makeError("hl:proc: out of memory")
  927. else
  928. allocator.dupeZ(u8, d) catch return api.makeError("hl:proc: out of memory");
  929. } else {
  930. return api.makeError("hl:proc exec: the options are cwd, unlink and argv0");
  931. }
  932. }
  933. }
  934. const prog = cargv[0].?;
  935. var fd: isize = -1;
  936. if (unlink_it) {
  937. fd = @bitCast(linux.open(prog, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0));
  938. if (fd < 0) return execError(prog, @intCast(-fd));
  939. _ = linux.unlink(prog);
  940. }
  941. if (cwd_z) |d| {
  942. const rc: isize = @bitCast(linux.chdir(d.ptr));
  943. if (rc < 0) return execError(prog, @intCast(-rc));
  944. }
  945. if (fd >= 0) {
  946. // the name the program sees (`ps`, /proc/<pid>/cmdline), the file
  947. // being open already
  948. if (argv0_z) |a0| cargv[0] = a0.ptr;
  949. // execveat(fd, "", argv, envp, AT_EMPTY_PATH)
  950. const rc: isize = @bitCast(linux.syscall5(.execveat, @intCast(fd), @intFromPtr(""), @intFromPtr(cargv.ptr), @intFromPtr(c.environ), 0x1000));
  951. return execError(prog, @intCast(-rc));
  952. }
  953. _ = c.execvp(prog, @ptrCast(cargv.ptr));
  954. return execError(prog, @intCast(std.c._errno().*));
  955. }
  956. fn execError(prog: [*:0]const u8, errno: c_int) HlValue {
  957. const m = std.fmt.allocPrint(allocator, "hl:proc exec: cannot start '{s}': {s}", .{ std.mem.span(prog), std.mem.span(c.strerror(errno)) }) catch "hl:proc exec: cannot start the program";
  958. return api.makeError(m);
  959. }
  960. /// hl_proc_kill(pid, signal?) — SIGTERM by default; the exit event still arrives
  961. export fn hl_proc_kill(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  962. if (argc < 1 or argv[0].type != .hl_number) {
  963. return api.makeError("hl:proc kill: pass the pid spawn() returned");
  964. }
  965. const pid: c_int = @intFromFloat(argv[0].data.number);
  966. var sig: c_int = 15; // SIGTERM
  967. if (argc >= 2 and argv[1].type == .hl_number) sig = @intFromFloat(argv[1].data.number);
  968. if (pid <= 1) return api.makeError("hl:proc kill: refusing pid <= 1");
  969. const r = c.kill(pid, sig);
  970. return api.makeBool(r == 0);
  971. }
  972. /// hl_proc_env(name) — one environment variable, null when unset. The
  973. /// environment is PROCESS surface, which is why it lives in hl:proc.
  974. export fn hl_proc_env(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  975. if (argc < 1 or argv[0].type != .hl_string) {
  976. return api.makeError("hl:proc env: pass the variable name");
  977. }
  978. const name = argv[0].data.string;
  979. const z = allocator.dupeZ(u8, name.ptr[0..name.len]) catch return api.makeNull();
  980. defer allocator.free(z);
  981. const v = std.c.getenv(z.ptr) orelse return api.makeNull();
  982. const copy = allocator.dupe(u8, std.mem.span(v)) catch return api.makeNull();
  983. return api.makeString(copy);
  984. }
  985. extern "c" fn unsetenv(name: [*:0]const u8) c_int;
  986. extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
  987. /// hl_proc_set_env(name, value) — set one variable of this process's
  988. /// environment (null removes it); the programs it then starts inherit it.
  989. export fn hl_proc_set_env(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  990. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:proc setEnv: pass the variable name");
  991. const name = argv[0].data.string;
  992. const nz = allocator.dupeZ(u8, name.ptr[0..name.len]) catch return api.makeError("hl:proc: out of memory");
  993. defer allocator.free(nz);
  994. if (argc < 2 or argv[1].type == .hl_null) {
  995. _ = unsetenv(nz.ptr);
  996. return api.makeNull();
  997. }
  998. if (argv[1].type != .hl_string) return api.makeError("hl:proc setEnv: the value must be a String (or null to remove the variable)");
  999. const val = argv[1].data.string;
  1000. const vz = allocator.dupeZ(u8, val.ptr[0..val.len]) catch return api.makeError("hl:proc: out of memory");
  1001. defer allocator.free(vz);
  1002. _ = setenv(nz.ptr, vz.ptr, 1);
  1003. return api.makeNull();
  1004. }
  1005. // ── the program's own arguments (mission 317) ────────────────────────────────
  1006. // The host installs them right after dlopen, the same way it installs the
  1007. // script directory: one NUL-separated blob and a count. WHAT they are is the
  1008. // host's ruling, not this plugin's — the interpreter hands over the positionals
  1009. // that follow a FILE entry, and a compiled binary hands over its own argv minus
  1010. // argv[0]. A program started with none simply gets none.
  1011. var arg_blob: ?[]u8 = null;
  1012. var arg_count: usize = 0;
  1013. export fn hl_proc_set_args(ptr: [*]const u8, len: usize, count: usize) callconv(.c) void {
  1014. if (arg_blob) |old| allocator.free(old);
  1015. arg_blob = allocator.dupe(u8, ptr[0..len]) catch null;
  1016. arg_count = if (arg_blob == null) 0 else count;
  1017. }
  1018. /// hl_proc_argc() — how many arguments the program was given.
  1019. export fn hl_proc_argc(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1020. _ = argc;
  1021. _ = argv;
  1022. return api.makeNumber(@floatFromInt(arg_count));
  1023. }
  1024. /// hl_proc_arg(i) — the i-th argument, null when there is none. `args()` in
  1025. /// server.hl walks these into the list the language hands back; the pair exists
  1026. /// because a plugin's return value is one value, and a LIST is what the caller
  1027. /// wants.
  1028. export fn hl_proc_arg(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1029. if (argc < 1 or argv[0].type != .hl_number) {
  1030. return api.makeError("hl:proc arg: pass the index");
  1031. }
  1032. const n = argv[0].data.number;
  1033. if (n < 0 or n != @floor(n)) return api.makeNull();
  1034. const want: usize = @intFromFloat(n);
  1035. if (want >= arg_count) return api.makeNull();
  1036. const blob = arg_blob orelse return api.makeNull();
  1037. var seen: usize = 0;
  1038. var start: usize = 0;
  1039. for (blob, 0..) |ch, i| {
  1040. if (ch != 0) continue;
  1041. if (seen == want) {
  1042. const copy = allocator.dupe(u8, blob[start..i]) catch return api.makeNull();
  1043. return api.makeString(copy);
  1044. }
  1045. seen += 1;
  1046. start = i + 1;
  1047. }
  1048. return api.makeNull();
  1049. }
  1050. /// hl_proc_cwd() — the process's current working directory, absolute. NOTE the
  1051. /// language's paths stay SCRIPT-relative; this is for tools that act where the
  1052. /// USER is standing (a CLI operating on "here"), not for resolving your own files.
  1053. export fn hl_proc_cwd(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1054. _ = argc;
  1055. _ = argv;
  1056. var buf: [4096]u8 = undefined;
  1057. const p = std.c.getcwd(&buf, buf.len) orelse return api.makeError("hl:proc cwd: getcwd failed");
  1058. const copy = allocator.dupe(u8, std.mem.sliceTo(p, 0)) catch return api.makeNull();
  1059. return api.makeString(copy);
  1060. }
  1061. // ── stdin as a LOOP SOURCE (realms, 2026-09-01) ──────────────────────────────
  1062. // hl_proc_stdin() → loop source of { line, eof }: one reader thread on fd 0,
  1063. // line-buffered, posting under a mutex with an eventfd bell — the same shape
  1064. // as a child's pipes above. A joined terminal realm reads its keyboard here.
  1065. const StdinSrc = struct {
  1066. mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER,
  1067. queue: std.ArrayListUnmanaged([]u8) = .empty,
  1068. wake_fd: i32 = -1,
  1069. eof: bool = false,
  1070. eof_reported: bool = false,
  1071. fn post(self: *StdinSrc, line: ?[]u8) void {
  1072. mutexLock(&self.mutex);
  1073. if (line) |l| {
  1074. self.queue.append(allocator, l) catch {};
  1075. } else {
  1076. self.eof = true;
  1077. }
  1078. mutexUnlock(&self.mutex);
  1079. const one: u64 = 1;
  1080. _ = stdin_c.write(self.wake_fd, @ptrCast(&one), 8);
  1081. }
  1082. };
  1083. const stdin_c = struct {
  1084. extern "c" fn read(fd: c_int, buf: [*]u8, n: usize) isize;
  1085. extern "c" fn write(fd: c_int, buf: [*]const u8, n: usize) isize;
  1086. extern "c" fn eventfd(initval: c_uint, flags: c_int) c_int;
  1087. };
  1088. var stdin_src: ?*StdinSrc = null;
  1089. fn stdinReaderMain(s: *StdinSrc) void {
  1090. var buf = std.ArrayListUnmanaged(u8).empty;
  1091. defer buf.deinit(allocator);
  1092. var rd: [4096]u8 = undefined;
  1093. while (true) {
  1094. const got = stdin_c.read(0, &rd, rd.len);
  1095. if (got <= 0) break;
  1096. const chunk = rd[0..@intCast(got)];
  1097. var start: usize = 0;
  1098. for (chunk, 0..) |ch, k| {
  1099. if (ch != '\n') continue;
  1100. buf.appendSlice(allocator, chunk[start..k]) catch {};
  1101. const line = textLine(buf.items);
  1102. if (line) |l| s.post(l);
  1103. buf.clearRetainingCapacity();
  1104. start = k + 1;
  1105. }
  1106. buf.appendSlice(allocator, chunk[start..]) catch {};
  1107. }
  1108. if (buf.items.len > 0) {
  1109. const line = textLine(buf.items);
  1110. if (line) |l| s.post(l);
  1111. }
  1112. s.post(null);
  1113. }
  1114. fn stdinTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  1115. const s: *StdinSrc = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  1116. var eat: [8]u8 = undefined;
  1117. _ = stdin_c.read(s.wake_fd, &eat, 8);
  1118. mutexLock(&s.mutex);
  1119. var line: ?[]u8 = null;
  1120. var eof_now = false;
  1121. if (s.queue.items.len > 0) {
  1122. line = s.queue.orderedRemove(0);
  1123. } else if (s.eof and !s.eof_reported) {
  1124. s.eof_reported = true;
  1125. eof_now = true;
  1126. }
  1127. mutexUnlock(&s.mutex);
  1128. if (line == null and !eof_now) return api.makeNull();
  1129. const fields = allocator.alloc(HlField, 2) catch return api.makeNull();
  1130. fields[0] = .{ .key = .{ .ptr = "line".ptr, .len = 4 }, .value = if (line) |l| api.makeString(l) else api.makeNull() };
  1131. fields[1] = .{ .key = .{ .ptr = "eof".ptr, .len = 3 }, .value = api.makeBool(eof_now) };
  1132. const obj = allocator.create(HlObject) catch return api.makeNull();
  1133. obj.* = .{ .fields = fields.ptr, .field_count = 2, .deinit_fn = null };
  1134. return api.makeObject(obj);
  1135. }
  1136. fn stdinDeinit(ctx: ?*anyopaque) callconv(.c) void {
  1137. _ = ctx;
  1138. }
  1139. /// hl_proc_stdin() → loop source
  1140. export fn hl_proc_stdin(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1141. _ = argc;
  1142. _ = argv;
  1143. if (stdin_src != null) return api.makeError("hl:proc stdin: this process already reads its terminal");
  1144. const s = allocator.create(StdinSrc) catch return api.makeError("hl:proc: out of memory");
  1145. s.* = .{ .wake_fd = stdin_c.eventfd(0, 0o4000) };
  1146. const t = std.Thread.spawn(.{}, stdinReaderMain, .{s}) catch {
  1147. allocator.destroy(s);
  1148. return api.makeError("hl:proc stdin: cannot start the reader thread");
  1149. };
  1150. t.detach();
  1151. stdin_src = s;
  1152. const iter = allocator.create(HlIterator) catch return api.makeError("hl:proc: out of memory");
  1153. iter.* = .{
  1154. .context = @ptrCast(s),
  1155. .next_fn = &stdinTryNext,
  1156. .deinit_fn = &stdinDeinit,
  1157. .try_next_fn = &stdinTryNext,
  1158. .wake_fd = s.wake_fd,
  1159. };
  1160. return api.makeIterator(iter);
  1161. }

Branches

Latest commits

  • 76e0587aWIP gs 2mre
  • a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
  • 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
  • a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre