gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/proc/proc.zig

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

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre