@native-sdk/cli 0.5.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/app.zig +50 -1
- package/build.zig +534 -3
- package/build.zig.zon +7 -0
- package/native-sdk.d.ts +3 -1
- package/package.json +9 -9
- package/packages/core/package-lock.json +2 -2
- package/packages/core/package.json +1 -1
- package/packages/core/rt/rt.zig +280 -8
- package/packages/core/sdk/core.ts +481 -2
- package/packages/core/sdk/events.ts +17 -8
- package/packages/core/src/checker.ts +305 -2
- package/packages/core/src/diagnostics.ts +12 -0
- package/packages/core/src/emitter.ts +599 -3
- package/packages/core/src/typed_ast.ts +51 -4
- package/packages/core/src/types.ts +34 -1
- package/skill-data/native-ui/SKILL.md +39 -2
- package/skill-data/ts-core/SKILL.md +4 -2
- package/src/app_runner/root.zig +32 -10
- package/src/automation/layout_fingerprint.zig +160 -0
- package/src/automation/protocol.zig +82 -33
- package/src/automation/root.zig +1 -0
- package/src/automation/server.zig +1 -1
- package/src/automation/snapshot.zig +68 -9
- package/src/automation/watcher.zig +1 -1
- package/src/embed/host.zig +5 -0
- package/src/embed/ui_host.zig +13 -0
- package/src/platform/linux/gtk_host.c +527 -13
- package/src/platform/linux/gtk_host.h +25 -0
- package/src/platform/linux/root.zig +280 -7
- package/src/platform/macos/appkit_host.h +104 -6
- package/src/platform/macos/appkit_host.m +1283 -66
- package/src/platform/macos/cef_host.mm +110 -1
- package/src/platform/macos/root.zig +287 -7
- package/src/platform/null_platform.zig +398 -4
- package/src/platform/null_platform_tests.zig +35 -0
- package/src/platform/root.zig +9 -0
- package/src/platform/types.zig +386 -14
- package/src/platform/windows/root.zig +298 -9
- package/src/platform/windows/webview2_host.cpp +330 -5
- package/src/primitives/app_manifest/validation.zig +18 -0
- package/src/primitives/canvas/a11y_audit.zig +33 -11
- package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
- package/src/primitives/canvas/drawing.zig +25 -0
- package/src/primitives/canvas/equality.zig +8 -0
- package/src/primitives/canvas/events.zig +103 -16
- package/src/primitives/canvas/frame.zig +125 -1
- package/src/primitives/canvas/layout_audit.zig +22 -5
- package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
- package/src/primitives/canvas/render_tests.zig +13 -10
- package/src/primitives/canvas/root.zig +48 -0
- package/src/primitives/canvas/terminal_box.zig +471 -0
- package/src/primitives/canvas/terminal_grid.zig +978 -0
- package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
- package/src/primitives/canvas/test_support.zig +1 -0
- package/src/primitives/canvas/tests.zig +1 -0
- package/src/primitives/canvas/text_tests.zig +39 -4
- package/src/primitives/canvas/tokens.zig +115 -12
- package/src/primitives/canvas/ui.zig +524 -5
- package/src/primitives/canvas/ui_markup.zig +195 -2
- package/src/primitives/canvas/ui_markup_compiled.zig +172 -1
- package/src/primitives/canvas/ui_markup_compiled_tests.zig +133 -8
- package/src/primitives/canvas/ui_markup_contract.zig +88 -5
- package/src/primitives/canvas/ui_markup_contract_tests.zig +39 -1
- package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
- package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
- package/src/primitives/canvas/ui_markup_tests.zig +149 -0
- package/src/primitives/canvas/ui_markup_view.zig +191 -0
- package/src/primitives/canvas/ui_markup_view_tests.zig +403 -19
- package/src/primitives/canvas/ui_schema.zig +97 -17
- package/src/primitives/canvas/ui_schema_tests.zig +18 -11
- package/src/primitives/canvas/ui_tests.zig +141 -9
- package/src/primitives/canvas/widget_access.zig +28 -2
- package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
- package/src/primitives/canvas/widget_invalidation.zig +81 -1
- package/src/primitives/canvas/widget_layout.zig +59 -11
- package/src/primitives/canvas/widget_layout_tests.zig +125 -4
- package/src/primitives/canvas/widget_render.zig +272 -18
- package/src/primitives/canvas/widget_render_scroll.zig +108 -27
- package/src/primitives/canvas/widget_routing.zig +59 -7
- package/src/primitives/canvas/widget_runtime.zig +23 -0
- package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
- package/src/primitives/canvas/widget_semantics.zig +119 -11
- package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
- package/src/primitives/canvas/widget_tree.zig +17 -0
- package/src/primitives/canvas/widgets.zig +132 -0
- package/src/root.zig +16 -0
- package/src/runtime/api.zig +70 -1
- package/src/runtime/automation_commands.zig +20 -1
- package/src/runtime/automation_snapshot.zig +25 -1
- package/src/runtime/automation_widget_dispatch.zig +73 -8
- package/src/runtime/bridge_payload.zig +1 -0
- package/src/runtime/canvas_frame.zig +62 -7
- package/src/runtime/canvas_frame_animation_tests.zig +5 -4
- package/src/runtime/canvas_frame_helpers.zig +190 -1
- package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
- package/src/runtime/canvas_frame_patch_tests.zig +161 -10
- package/src/runtime/canvas_frame_retained_tests.zig +5 -2
- package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
- package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
- package/src/runtime/canvas_widget_context_menu.zig +269 -32
- package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
- package/src/runtime/canvas_widget_display.zig +1 -1
- package/src/runtime/canvas_widget_event_tests.zig +1823 -0
- package/src/runtime/canvas_widget_events.zig +240 -24
- package/src/runtime/canvas_widget_runtime.zig +213 -29
- package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
- package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
- package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
- package/src/runtime/canvas_widget_state.zig +6 -0
- package/src/runtime/canvas_widget_text_tests.zig +1 -1
- package/src/runtime/core.zig +73 -2
- package/src/runtime/effects.zig +6389 -54
- package/src/runtime/effects_channel_tests.zig +3519 -0
- package/src/runtime/effects_pty_tests.zig +1362 -0
- package/src/runtime/effects_tests.zig +14 -9
- package/src/runtime/effects_video_tests.zig +3609 -0
- package/src/runtime/flow.zig +25 -4
- package/src/runtime/gpu_surface_events.zig +473 -13
- package/src/runtime/media_surface.zig +116 -11
- package/src/runtime/media_surface_tests.zig +61 -0
- package/src/runtime/pty.zig +1252 -0
- package/src/runtime/pty_windows.zig +1780 -0
- package/src/runtime/root.zig +25 -0
- package/src/runtime/runtime_event_tests.zig +20 -1
- package/src/runtime/session_journal.zig +367 -61
- package/src/runtime/session_record.zig +16 -0
- package/src/runtime/session_replay.zig +395 -11
- package/src/runtime/session_tests.zig +109 -15
- package/src/runtime/terminal_session.zig +1569 -0
- package/src/runtime/terminal_session_tests.zig +450 -0
- package/src/runtime/terminal_vt_ghostty.zig +15 -0
- package/src/runtime/terminal_vt_stub.zig +13 -0
- package/src/runtime/tests.zig +6 -0
- package/src/runtime/ts_core_host.zig +980 -140
- package/src/runtime/ts_core_host_tests.zig +1059 -1
- package/src/runtime/ts_ui_app.zig +16 -5
- package/src/runtime/ui_app.zig +2333 -63
- package/src/runtime/ui_app_tests.zig +3171 -744
- package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
- package/src/runtime/ui_app_window_tests.zig +268 -0
- package/src/runtime/view.zig +190 -2
- package/src/runtime/view_widget_scroll.zig +218 -68
- package/src/runtime/view_widget_text.zig +11 -2
- package/src/runtime/view_widget_tree.zig +111 -3
- package/src/runtime/window_storage.zig +45 -2
- package/src/runtime/window_view_runtime.zig +34 -2
- package/src/runtime/window_views.zig +1 -0
- package/src/terminal_session_tests_root.zig +15 -0
- package/src/tooling/templates.zig +25 -7
|
@@ -0,0 +1,1252 @@
|
|
|
1
|
+
//! Pseudo-terminal transport seam. The POSIX half lives in this file:
|
|
2
|
+
//! open a pty pair, fork a child with the child end as its controlling
|
|
3
|
+
//! terminal, and hand the caller the parent fd to read output from and
|
|
4
|
+
//! write input to (macOS, and Linux with libc). Windows dispatches to
|
|
5
|
+
//! the ConPTY backend in `pty_windows.zig` through the same public
|
|
6
|
+
//! surface — one `Pty` shape, one `wait`/nudge vocabulary, one spawn
|
|
7
|
+
//! policy — so the effects io loop never branches per platform. Every
|
|
8
|
+
//! remaining target compiles to the `error.PtyUnsupported` stubs so the
|
|
9
|
+
//! effects layer reports the same loud rejection the null platform's
|
|
10
|
+
//! fake pty stands in for under test.
|
|
11
|
+
//!
|
|
12
|
+
//! (The two ends of a pty pair: the PARENT end is the controlling side the
|
|
13
|
+
//! toolkit keeps, and the CHILD end is the process side that becomes the
|
|
14
|
+
//! spawned program's controlling terminal — POSIX's own APIs spell these
|
|
15
|
+
//! `posix_openpt`/`ptsname`, whose C names we keep at the call site.)
|
|
16
|
+
//!
|
|
17
|
+
//! This is the one place the toolkit forks a child onto a terminal. It
|
|
18
|
+
//! deliberately does NOT use `std.process.spawn`: a pty child needs a
|
|
19
|
+
//! controlling terminal (`login_tty` = setsid + TIOCSCTTY + dup of the
|
|
20
|
+
//! child end onto fds 0/1/2), which the generic spawn path does not set up.
|
|
21
|
+
//! Everything the child touches between fork and exec is async-signal-safe:
|
|
22
|
+
//! argv/envp are built in the PARENT (including the `TERM` override and the
|
|
23
|
+
//! PATH resolution of argv[0]), so the child calls only `login_tty`,
|
|
24
|
+
//! `execve`, and `_exit` — no allocator, no `setenv`, none of the
|
|
25
|
+
//! fork-in-a-threaded-process hazards a mid-child `malloc` would invite.
|
|
26
|
+
|
|
27
|
+
const std = @import("std");
|
|
28
|
+
const builtin = @import("builtin");
|
|
29
|
+
const clock = @import("clock.zig");
|
|
30
|
+
const windows_impl = @import("pty_windows.zig");
|
|
31
|
+
|
|
32
|
+
const is_windows = builtin.os.tag == .windows;
|
|
33
|
+
|
|
34
|
+
/// Serializes the descriptor-opening half of every pty spawn in the
|
|
35
|
+
/// process (spawns can originate from independent runtime instances on
|
|
36
|
+
/// different threads): the section from `posix_openpt` through `fork`,
|
|
37
|
+
/// and the wake pipe's creation. Darwin ignores O_CLOEXEC on
|
|
38
|
+
/// `posix_openpt` (and its pipes need a second syscall for the flag),
|
|
39
|
+
/// so a CONCURRENT PTY FORK landing between an open and its fcntl would
|
|
40
|
+
/// gift its exec'd child a copy of another spawn's parent-end or pipe
|
|
41
|
+
/// descriptor for that child's whole life. Forks the lock cannot cover
|
|
42
|
+
/// — job spawns (their process start blocks on its own exec pipe, so
|
|
43
|
+
/// holding a UI-shared lock across it would freeze the loop on a
|
|
44
|
+
/// wedged mount) and embedder forks on foreign threads — keep the
|
|
45
|
+
/// documented residual sub-syscall window: inherited copies die at
|
|
46
|
+
/// those children's execs, and a delayed exec-pipe EOF is resolved by
|
|
47
|
+
/// the carried reap-time verdict rather than guessed. `ptsname`'s
|
|
48
|
+
/// libc-shared static buffer rides the same lock. A tiny spinlock —
|
|
49
|
+
/// the guarded section is a handful of bounded syscalls, never the
|
|
50
|
+
/// exec-status poll.
|
|
51
|
+
const SpinLock = struct {
|
|
52
|
+
locked: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
|
|
53
|
+
fn lock(self: *SpinLock) void {
|
|
54
|
+
while (self.locked.swap(true, .acquire)) std.atomic.spinLoopHint();
|
|
55
|
+
}
|
|
56
|
+
fn unlock(self: *SpinLock) void {
|
|
57
|
+
self.locked.store(false, .release);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
var pty_spawn_mutex: SpinLock = .{};
|
|
61
|
+
|
|
62
|
+
/// Pids whose reap was SURRENDERED (a SIGKILL'd child the kernel held in
|
|
63
|
+
/// uninterruptible I/O past the bounded window). They are polled again —
|
|
64
|
+
/// WNOHANG, never blocking — at every later spawn and at teardown, so a
|
|
65
|
+
/// child that dies after its device or mount recovers is reaped then
|
|
66
|
+
/// instead of lingering as a zombie for the process's life. A full table
|
|
67
|
+
/// drops the oldest entry (that one keeps the documented zombie); more
|
|
68
|
+
/// than a handful of simultaneously wedged children means the machine
|
|
69
|
+
/// has bigger problems than process-table slots.
|
|
70
|
+
const max_surrendered_pids = 16;
|
|
71
|
+
var surrendered_pids: [max_surrendered_pids]c_int = @splat(-1);
|
|
72
|
+
var surrendered_lock: SpinLock = .{};
|
|
73
|
+
/// Ring cursor for full-table overwrites: each overflow evicts the
|
|
74
|
+
/// OLDEST standing entry in turn (its zombie stands), never the same
|
|
75
|
+
/// slot repeatedly — a fixed victim would forget every surrender after
|
|
76
|
+
/// the first overflow while slot 0's zombie kept its retry seat.
|
|
77
|
+
var surrendered_evict: usize = 0;
|
|
78
|
+
|
|
79
|
+
fn recordSurrenderedPid(pid: c_int) void {
|
|
80
|
+
surrendered_lock.lock();
|
|
81
|
+
defer surrendered_lock.unlock();
|
|
82
|
+
for (&surrendered_pids) |*slot| {
|
|
83
|
+
if (slot.* < 0) {
|
|
84
|
+
slot.* = pid;
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Full: evict round-robin — the newer surrender gets the retry
|
|
89
|
+
// chance, and successive overflows spread the forgotten zombies
|
|
90
|
+
// across the table instead of pinning them all behind one slot.
|
|
91
|
+
surrendered_pids[surrendered_evict] = pid;
|
|
92
|
+
surrendered_evict = (surrendered_evict + 1) % max_surrendered_pids;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Opportunistically reap previously surrendered children (WNOHANG,
|
|
96
|
+
/// bounded). Called at spawn entry and teardown; safe from any thread.
|
|
97
|
+
/// A no-op on Windows: process objects self-release when their last
|
|
98
|
+
/// handle closes, so there is no zombie to re-poll for.
|
|
99
|
+
pub fn reapSurrendered() void {
|
|
100
|
+
if (comptime is_windows) return windows_impl.reapSurrendered();
|
|
101
|
+
if (comptime !posix_supported) return;
|
|
102
|
+
surrendered_lock.lock();
|
|
103
|
+
defer surrendered_lock.unlock();
|
|
104
|
+
for (&surrendered_pids) |*slot| {
|
|
105
|
+
if (slot.* < 0) continue;
|
|
106
|
+
var status: c_int = 0;
|
|
107
|
+
const r = c.waitpid(slot.*, &status, wnohang);
|
|
108
|
+
// Reaped (r == pid), or already gone (ECHILD from an embedder
|
|
109
|
+
// reaper): the entry is settled. 0 = still wedged, and EINTR —
|
|
110
|
+
// however unlikely against a non-blocking wait — keeps the pid
|
|
111
|
+
// for the next poll rather than abandoning a live child to
|
|
112
|
+
// zombie unreaped.
|
|
113
|
+
if (r == 0) continue;
|
|
114
|
+
if (r < 0 and errnoValue() == eintr) continue;
|
|
115
|
+
slot.* = -1;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/// Where a real pty transport exists: openpty + a controlling terminal
|
|
120
|
+
/// on the POSIX targets, ConPTY (`pty_windows.zig`) on Windows; every
|
|
121
|
+
/// other target reports the effect as unsupported rather than
|
|
122
|
+
/// pretending. macOS always links libSystem, so the libc externs below
|
|
123
|
+
/// always resolve there; Linux builds get the real transport exactly
|
|
124
|
+
/// when they link libc (every platform app build does — the GTK host is
|
|
125
|
+
/// C — while a libc-free headless build reports unsupported and tests
|
|
126
|
+
/// through the fake pty). `openpty`/`login_tty` live in libc proper on
|
|
127
|
+
/// the supported Linux floor (glibc 2.34+ merged libutil; musl always
|
|
128
|
+
/// shipped them). ConPTY needs no libc at all — the backend speaks
|
|
129
|
+
/// kernel32 directly.
|
|
130
|
+
pub const supported = switch (builtin.os.tag) {
|
|
131
|
+
.macos => true,
|
|
132
|
+
.linux => builtin.link_libc,
|
|
133
|
+
.windows => true,
|
|
134
|
+
else => false,
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
/// The POSIX half really compiled into this build — the gate the libc
|
|
138
|
+
/// externs and the in-file POSIX tests sit behind (`supported` also
|
|
139
|
+
/// covers Windows, whose code lives in `pty_windows.zig`).
|
|
140
|
+
const posix_supported = switch (builtin.os.tag) {
|
|
141
|
+
.macos => true,
|
|
142
|
+
.linux => builtin.link_libc,
|
|
143
|
+
else => false,
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/// The value written into the child's `TERM` when the caller does not
|
|
147
|
+
/// override it: a widely understood 256-color terminfo name matching the
|
|
148
|
+
/// palette the emulator and the example renderer speak.
|
|
149
|
+
pub const default_term = "xterm-256color";
|
|
150
|
+
|
|
151
|
+
/// Longest single command path (argv[0] resolved) plus each argv entry the
|
|
152
|
+
/// pty spawn accepts, mirroring the spawn effect's argv budget so the two
|
|
153
|
+
/// transports teach one limit.
|
|
154
|
+
pub const max_argv = 16;
|
|
155
|
+
pub const max_argv_bytes = 4096;
|
|
156
|
+
pub const max_env_entries = 256;
|
|
157
|
+
pub const max_env_bytes = 64 * 1024;
|
|
158
|
+
|
|
159
|
+
pub const Error = error{
|
|
160
|
+
PtyUnsupported,
|
|
161
|
+
PtyOpenFailed,
|
|
162
|
+
PtyForkFailed,
|
|
163
|
+
PtyArgvInvalid,
|
|
164
|
+
PtyEnvironTooLarge,
|
|
165
|
+
PtyCommandNotFound,
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/// A live pty. On Windows this is the ConPTY transport
|
|
169
|
+
/// (`pty_windows.zig`), same method surface; on POSIX it is the
|
|
170
|
+
/// parent-end fd plus the child pid — reads and writes go to `parent`,
|
|
171
|
+
/// `pid` is signalled for kill and reaped on exit.
|
|
172
|
+
pub const Pty = if (is_windows) windows_impl.Pty else struct {
|
|
173
|
+
parent: c_int,
|
|
174
|
+
pid: c_int,
|
|
175
|
+
/// The exec self-pipe's read end, kept ONLY when the spawn-time
|
|
176
|
+
/// probe timed out unresolved (an executable on a stalled mount can
|
|
177
|
+
/// block inside `execve` past any reasonable bound). The verdict
|
|
178
|
+
/// still arrives with the child's death — a failing exec writes its
|
|
179
|
+
/// byte before `_exit` — so `lateExecFailure` reads it at reap time
|
|
180
|
+
/// and the exit reports `spawn_failed` instead of masquerading as a
|
|
181
|
+
/// normal end. -1 when the probe resolved at spawn.
|
|
182
|
+
exec_status: c_int = -1,
|
|
183
|
+
|
|
184
|
+
/// Read available output bytes into `buf`. Returns 0 at EOF — which the
|
|
185
|
+
/// parent end reports as EIO on Linux once the child exits, normalized
|
|
186
|
+
/// here — and `error.ReadFailed` for anything else.
|
|
187
|
+
pub fn read(self: Pty, buf: []u8) error{ ReadFailed, WouldBlock }!usize {
|
|
188
|
+
while (true) {
|
|
189
|
+
const r = c.read(self.parent, buf.ptr, buf.len);
|
|
190
|
+
if (r >= 0) return @intCast(r);
|
|
191
|
+
switch (errnoValue()) {
|
|
192
|
+
eintr => continue,
|
|
193
|
+
// Non-blocking parent end with nothing ready: not EOF.
|
|
194
|
+
eagain => return error.WouldBlock,
|
|
195
|
+
// EIO from the parent end is the hangup after child exit:
|
|
196
|
+
// the stream is over, not broken.
|
|
197
|
+
eio => return 0,
|
|
198
|
+
else => return error.ReadFailed,
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/// Write input bytes toward the child. Partial writes are possible;
|
|
204
|
+
/// the caller loops. `error.WouldBlock` means the non-blocking parent
|
|
205
|
+
/// end's input buffer is full (the child is not reading) — the caller
|
|
206
|
+
/// leaves the bytes staged and retries on the next writable poll,
|
|
207
|
+
/// never blocking the io thread.
|
|
208
|
+
pub fn write(self: Pty, bytes: []const u8) error{ WriteFailed, WouldBlock }!usize {
|
|
209
|
+
while (true) {
|
|
210
|
+
const r = c.write(self.parent, bytes.ptr, bytes.len);
|
|
211
|
+
if (r >= 0) return @intCast(r);
|
|
212
|
+
switch (errnoValue()) {
|
|
213
|
+
eintr => continue,
|
|
214
|
+
eagain => return error.WouldBlock,
|
|
215
|
+
else => return error.WriteFailed,
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/// Push a new window size to the kernel line discipline so the child
|
|
221
|
+
/// receives SIGWINCH and re-queries via TIOCGWINSZ.
|
|
222
|
+
pub fn resize(self: Pty, cols: u16, rows: u16) void {
|
|
223
|
+
if (!posix_supported) return;
|
|
224
|
+
var ws: Winsize = .{
|
|
225
|
+
.row = if (rows == 0) 1 else rows,
|
|
226
|
+
.col = if (cols == 0) 1 else cols,
|
|
227
|
+
.xpixel = 0,
|
|
228
|
+
.ypixel = 0,
|
|
229
|
+
};
|
|
230
|
+
_ = c.ioctl(self.parent, tiocswinsz, &ws);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// Signal the child's process group. `graceful` sends SIGTERM (let the
|
|
234
|
+
/// shell clean up); otherwise SIGKILL. The child was placed in its own
|
|
235
|
+
/// session by `login_tty`, so signalling the negated pid reaches its
|
|
236
|
+
/// FOREGROUND process group — the direct child and everything it kept
|
|
237
|
+
/// in its group. A descendant that moved itself into another process
|
|
238
|
+
/// group (a shell's background job, a daemonizing setsid) is outside
|
|
239
|
+
/// the signal's reach: POSIX has no kill-whole-session primitive, so
|
|
240
|
+
/// such an escapee runs on detached — the spawn family's documented
|
|
241
|
+
/// limit, shared with `reapEnding`'s escalation and the io loop's
|
|
242
|
+
/// kill-then-reap path (which is why a kill never waits for the pty
|
|
243
|
+
/// to reach EOF: an escapee holding the child end open would strand
|
|
244
|
+
/// it forever).
|
|
245
|
+
pub fn kill(self: Pty, graceful: bool) void {
|
|
246
|
+
if (!posix_supported) return;
|
|
247
|
+
const sig: c_int = if (graceful) sigterm else sigkill;
|
|
248
|
+
_ = c.kill(-self.pid, sig);
|
|
249
|
+
_ = c.kill(self.pid, sig);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/// Reap the child if it has exited. Returns null while it is still
|
|
253
|
+
/// running, or the decoded exit on reap. Non-blocking (WNOHANG).
|
|
254
|
+
/// `ECHILD` — the child was already reaped elsewhere (an embedder
|
|
255
|
+
/// with `SA_NOCLDWAIT`, `SIG_IGN` on SIGCHLD, or its own reaper) —
|
|
256
|
+
/// is reported as a gone child (sentinel exit), NEVER as "still
|
|
257
|
+
/// running": a reaped pid may be reused, so treating it as alive
|
|
258
|
+
/// would let `reapEnding` signal an unrelated process.
|
|
259
|
+
pub fn reap(self: Pty) ?Exit {
|
|
260
|
+
if (!posix_supported) return null;
|
|
261
|
+
var status: c_int = 0;
|
|
262
|
+
const r = c.waitpid(self.pid, &status, wnohang);
|
|
263
|
+
if (r == self.pid) return decodeStatus(status);
|
|
264
|
+
if (r < 0 and errnoValue() == echild) return .{ .code = -1, .signal = 0 };
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/// Reap the child, blocking until it exits. Used at teardown after a
|
|
269
|
+
/// kill so no zombie is left behind. EINTR retries — a signal must
|
|
270
|
+
/// not fabricate an exit and leave the real child a zombie.
|
|
271
|
+
pub fn reapBlocking(self: Pty) Exit {
|
|
272
|
+
if (!posix_supported) return .{ .code = -1, .signal = 0 };
|
|
273
|
+
var status: c_int = 0;
|
|
274
|
+
while (true) {
|
|
275
|
+
const r = c.waitpid(self.pid, &status, 0);
|
|
276
|
+
if (r == self.pid) return decodeStatus(status);
|
|
277
|
+
if (r < 0 and errnoValue() == eintr) continue;
|
|
278
|
+
if (r < 0) return .{ .code = -1, .signal = 0 };
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/// Reap after the output stream ended, NEVER blocking indefinitely.
|
|
283
|
+
/// The fast path is the normal case: the child already exited, so a
|
|
284
|
+
/// non-blocking reap returns at once and no signal is sent. If the
|
|
285
|
+
/// child is still alive (it closed its terminal descriptors but kept
|
|
286
|
+
/// running), it is hung up like a real terminal (SIGHUP to the job),
|
|
287
|
+
/// then escalated to SIGKILL within a bounded window, so the exit
|
|
288
|
+
/// always arrives — the fix for a `reapBlocking` that would otherwise
|
|
289
|
+
/// wait forever on such a child while a kill is skipped. The caller
|
|
290
|
+
/// publishes `reaping` before this so no concurrent kill signals the
|
|
291
|
+
/// (soon-freed) pid.
|
|
292
|
+
pub fn reapEnding(self: Pty) Exit {
|
|
293
|
+
if (!posix_supported) return .{ .code = -1, .signal = 0 };
|
|
294
|
+
if (self.reap()) |exit| return exit;
|
|
295
|
+
// Still running: hang it up, then escalate. The grace windows
|
|
296
|
+
// are MONOTONIC DEADLINES, not sleep counts: `usleep` returns
|
|
297
|
+
// early on EINTR, so counting iterations would let an
|
|
298
|
+
// embedder's frequent non-restarting signals collapse the
|
|
299
|
+
// windows and SIGKILL a child that would have exited cleanly
|
|
300
|
+
// within the documented grace. (A missing clock — not expected
|
|
301
|
+
// on macOS/Linux — degrades to iteration counting rather than
|
|
302
|
+
// spinning forever.)
|
|
303
|
+
_ = c.kill(-self.pid, sighup);
|
|
304
|
+
_ = c.kill(self.pid, sighup);
|
|
305
|
+
const start_ns = clock.monotonicNanoseconds();
|
|
306
|
+
const clock_ok = start_ns != 0;
|
|
307
|
+
var iterations: usize = 0;
|
|
308
|
+
var killed = false;
|
|
309
|
+
while (true) : (iterations += 1) {
|
|
310
|
+
const elapsed_ns = if (clock_ok) clock.monotonicNanoseconds() -% start_ns else iterations * 10 * std.time.ns_per_ms;
|
|
311
|
+
if (elapsed_ns >= 500 * std.time.ns_per_ms) break;
|
|
312
|
+
_ = c.usleep(10_000);
|
|
313
|
+
if (self.reap()) |exit| return exit;
|
|
314
|
+
if (!killed and elapsed_ns >= 200 * std.time.ns_per_ms) {
|
|
315
|
+
killed = true;
|
|
316
|
+
_ = c.kill(-self.pid, sigkill);
|
|
317
|
+
_ = c.kill(self.pid, sigkill);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (!killed) {
|
|
321
|
+
_ = c.kill(-self.pid, sigkill);
|
|
322
|
+
_ = c.kill(self.pid, sigkill);
|
|
323
|
+
}
|
|
324
|
+
// SIGKILL cannot be caught — but a child stuck in UNINTERRUPTIBLE
|
|
325
|
+
// kernel I/O (a stalled mount, a wedged device) does not die
|
|
326
|
+
// until the kernel releases it, a wait no signal can shorten.
|
|
327
|
+
// Poll a further bounded window, then surrender the reap: the
|
|
328
|
+
// exit event must reach the app (an io thread wedged here would
|
|
329
|
+
// strand the session with no exit forever), so past the deadline
|
|
330
|
+
// the kill is reported as the ending and the pid parks on the
|
|
331
|
+
// surrendered list — later spawns and teardown re-poll it
|
|
332
|
+
// (WNOHANG), so a child that dies when its mount recovers is
|
|
333
|
+
// reaped then rather than zombieing for the process's life.
|
|
334
|
+
// Nothing signals the pid after this (`reaping` stays
|
|
335
|
+
// published). SIGKILL is irrevocable, so the reported signaled
|
|
336
|
+
// end is EVENTUALLY TRUE — the child dies the moment its
|
|
337
|
+
// syscall returns — and the surrendered list keeps re-polling
|
|
338
|
+
// for the reap. The same monotonic-deadline rule as above.
|
|
339
|
+
const surrender_start_ns = clock.monotonicNanoseconds();
|
|
340
|
+
var surrender_iterations: usize = 0;
|
|
341
|
+
while (true) : (surrender_iterations += 1) {
|
|
342
|
+
const elapsed_ns = if (clock_ok) clock.monotonicNanoseconds() -% surrender_start_ns else surrender_iterations * 20 * std.time.ns_per_ms;
|
|
343
|
+
if (elapsed_ns >= 5 * std.time.ns_per_s) break;
|
|
344
|
+
if (self.reap()) |exit| return exit;
|
|
345
|
+
_ = c.usleep(20_000);
|
|
346
|
+
}
|
|
347
|
+
recordSurrenderedPid(self.pid);
|
|
348
|
+
return .{ .code = -1, .signal = sigkill };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/// Close the parent-end fd (and a still-held exec-status pipe). The
|
|
352
|
+
/// child is expected to be reaped separately.
|
|
353
|
+
pub fn close(self: Pty) void {
|
|
354
|
+
if (!posix_supported) return;
|
|
355
|
+
_ = c.close(self.parent);
|
|
356
|
+
if (self.exec_status >= 0) _ = c.close(self.exec_status);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/// Whether a LATE exec failure landed on the carried status pipe —
|
|
360
|
+
/// checked at reap time, when the child is dead: a failing exec
|
|
361
|
+
/// wrote its byte before `_exit`, so the byte is either in the pipe
|
|
362
|
+
/// buffer now or the exec succeeded. The read is non-blocking (a
|
|
363
|
+
/// leaked writer in an embedder-forked child can therefore never
|
|
364
|
+
/// wedge the reap), and an empty pipe reads as success.
|
|
365
|
+
pub fn lateExecFailure(self: Pty) bool {
|
|
366
|
+
if (!posix_supported) return false;
|
|
367
|
+
if (self.exec_status < 0) return false;
|
|
368
|
+
var probe: [1]u8 = undefined;
|
|
369
|
+
while (true) {
|
|
370
|
+
const n = c.read(self.exec_status, &probe, 1);
|
|
371
|
+
if (n > 0) return true;
|
|
372
|
+
// A signal interrupting the read must not read as success —
|
|
373
|
+
// the failure byte may be sitting right there. EAGAIN
|
|
374
|
+
// (empty, non-blocking) and EOF are the genuine successes.
|
|
375
|
+
if (n < 0 and errnoValue() == eintr) continue;
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
/// How a pty child ended, decoded from `waitpid`'s status word.
|
|
382
|
+
pub const Exit = struct {
|
|
383
|
+
/// Exit code for a normal exit; -1 when the child died to a signal.
|
|
384
|
+
code: i32,
|
|
385
|
+
/// Signal number when the child was terminated by a signal; 0 for a
|
|
386
|
+
/// normal exit.
|
|
387
|
+
signal: i32,
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
/// Everything one spawn needs. argv and env come pre-flattened so the
|
|
391
|
+
/// child does nothing but exec.
|
|
392
|
+
pub const SpawnOptions = struct {
|
|
393
|
+
argv: []const []const u8,
|
|
394
|
+
/// The child's environment. When null the child inherits nothing but
|
|
395
|
+
/// `TERM` (a clean environment, like the fallback spawn environ).
|
|
396
|
+
env: ?[]const EnvVar = null,
|
|
397
|
+
/// Overrides the injected `TERM` value.
|
|
398
|
+
term: []const u8 = default_term,
|
|
399
|
+
cols: u16 = 80,
|
|
400
|
+
rows: u16 = 24,
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
pub const EnvVar = struct {
|
|
404
|
+
name: []const u8,
|
|
405
|
+
value: []const u8,
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
/// Windows only: snapshot the LIVE process environment into `buffer`
|
|
409
|
+
/// (names/values decoded into `bytes`) — the effects layer's
|
|
410
|
+
/// inherit-the-host env policy where the OS hands out a WTF-16 block
|
|
411
|
+
/// instead of a posix envp. Returns null on an over-bound environment,
|
|
412
|
+
/// the flatten seam's loud whole-or-nothing refusal. On every other
|
|
413
|
+
/// target the live environ flattens straight from the posix block and
|
|
414
|
+
/// this reports empty.
|
|
415
|
+
pub fn captureGlobalEnviron(buffer: []EnvVar, bytes: []u8) ?[]const EnvVar {
|
|
416
|
+
if (comptime !is_windows) return buffer[0..0];
|
|
417
|
+
return windows_impl.captureGlobalEnviron(buffer, bytes);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/// Open a pty and fork `argv` onto it. On success the returned `Pty` owns
|
|
421
|
+
/// the parent-end fd and the child pid. The child's environment is exactly
|
|
422
|
+
/// the caller's `env` (or empty) plus a `TERM` entry — no host variables leak
|
|
423
|
+
/// in unless the caller put them in `env`, the same explicit-policy shape
|
|
424
|
+
/// the spawn effect's `bindEnviron` draws.
|
|
425
|
+
pub fn spawn(gpa: std.mem.Allocator, options: SpawnOptions) Error!Pty {
|
|
426
|
+
if (comptime is_windows) return windows_impl.spawn(gpa, options);
|
|
427
|
+
if (!posix_supported) return error.PtyUnsupported;
|
|
428
|
+
// A cheap moment to settle any surrendered reap whose child has
|
|
429
|
+
// since died (its stalled device recovered).
|
|
430
|
+
reapSurrendered();
|
|
431
|
+
if (options.argv.len == 0 or options.argv.len > max_argv) return error.PtyArgvInvalid;
|
|
432
|
+
// An argv entry with an embedded NUL would be silently truncated at
|
|
433
|
+
// the C boundary (execve reads to the first NUL) — reject it rather
|
|
434
|
+
// than hand the child a cut argument.
|
|
435
|
+
for (options.argv) |arg| {
|
|
436
|
+
if (std.mem.indexOfScalar(u8, arg, 0) != null) return error.PtyArgvInvalid;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// Resolve argv[0] to an absolute path in the PARENT so the child's
|
|
440
|
+
// only post-fork calls are login_tty/execve/_exit — execve needs a
|
|
441
|
+
// resolved path (it does no PATH search).
|
|
442
|
+
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
|
|
443
|
+
const resolved = resolveExecutable(options.argv[0], options.env, &path_buf) orelse
|
|
444
|
+
return error.PtyCommandNotFound;
|
|
445
|
+
|
|
446
|
+
// Build the NUL-terminated argv/envp arrays the child hands execve.
|
|
447
|
+
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
|
448
|
+
defer arena_state.deinit();
|
|
449
|
+
const arena = arena_state.allocator();
|
|
450
|
+
|
|
451
|
+
const resolved_z = arena.dupeZ(u8, resolved) catch return error.PtyEnvironTooLarge;
|
|
452
|
+
const argv_z = buildArgvZ(arena, options.argv) catch return error.PtyEnvironTooLarge;
|
|
453
|
+
const envp_z = buildEnvpZ(arena, options.env, options.term) catch return error.PtyEnvironTooLarge;
|
|
454
|
+
|
|
455
|
+
const ws: Winsize = .{
|
|
456
|
+
.row = if (options.rows == 0) 24 else options.rows,
|
|
457
|
+
.col = if (options.cols == 0) 80 else options.cols,
|
|
458
|
+
.xpixel = 0,
|
|
459
|
+
.ypixel = 0,
|
|
460
|
+
};
|
|
461
|
+
const pair = try spawnPair(resolved_z, argv_z, envp_z, ws);
|
|
462
|
+
// A failure byte, EOF, or the timeout resolves the probe. A real
|
|
463
|
+
// exec failure writes its byte into the pipe buffer INSTANTLY (the
|
|
464
|
+
// child's write lands before its _exit), so a byte always means
|
|
465
|
+
// failure regardless of who else holds a writer. EOF (every writer
|
|
466
|
+
// closed) is the fast success signal. The timeout resolves NOTHING:
|
|
467
|
+
// an exec can genuinely block past any bound (an executable or
|
|
468
|
+
// shebang interpreter on a stalled mount) and an embedder-forked
|
|
469
|
+
// child holding a leaked writer delays EOF — so an unresolved probe
|
|
470
|
+
// CARRIES the pipe on the transport, where `lateExecFailure` reads
|
|
471
|
+
// the verdict at reap time and a late failure still delivers
|
|
472
|
+
// `spawn_failed`, never a masqueraded normal exit. Polled OUTSIDE
|
|
473
|
+
// the spawn lock, which covers only bounded syscalls.
|
|
474
|
+
switch (execStatus(pair.exec_read)) {
|
|
475
|
+
.failed => {
|
|
476
|
+
_ = c.close(pair.exec_read);
|
|
477
|
+
var status: c_int = 0;
|
|
478
|
+
while (c.waitpid(pair.pid, &status, 0) < 0 and errnoValue() == eintr) {}
|
|
479
|
+
_ = c.close(pair.parent);
|
|
480
|
+
return error.PtyCommandNotFound;
|
|
481
|
+
},
|
|
482
|
+
.succeeded => {
|
|
483
|
+
_ = c.close(pair.exec_read);
|
|
484
|
+
return .{ .parent = pair.parent, .pid = pair.pid };
|
|
485
|
+
},
|
|
486
|
+
.unresolved => {
|
|
487
|
+
// Non-blocking so the reap-time check can never wait on a
|
|
488
|
+
// leaked writer. If the flag cannot be set, the carried
|
|
489
|
+
// check is unsafe — fall back to the probe's old
|
|
490
|
+
// timed-out-means-started answer rather than risk a wedged
|
|
491
|
+
// reap.
|
|
492
|
+
if (!setNonblock(pair.exec_read)) {
|
|
493
|
+
_ = c.close(pair.exec_read);
|
|
494
|
+
return .{ .parent = pair.parent, .pid = pair.pid };
|
|
495
|
+
}
|
|
496
|
+
return .{ .parent = pair.parent, .pid = pair.pid, .exec_status = pair.exec_read };
|
|
497
|
+
},
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const SpawnedPair = struct {
|
|
502
|
+
parent: c_int,
|
|
503
|
+
pid: c_int,
|
|
504
|
+
exec_read: c_int,
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
/// Open the pty pair, arm the exec self-pipe, and fork — the whole
|
|
508
|
+
/// descriptor-opening window — under the process-wide spawn lock (see
|
|
509
|
+
/// `pty_spawn_mutex`): with every toolkit fork serialized against every
|
|
510
|
+
/// toolkit open-to-CLOEXEC gap, no toolkit child can inherit another
|
|
511
|
+
/// spawn's parent end or pipe ends across its exec.
|
|
512
|
+
fn spawnPair(
|
|
513
|
+
resolved_z: [:0]const u8,
|
|
514
|
+
argv_z: [:null]const ?[*:0]const u8,
|
|
515
|
+
envp_z: [:null]const ?[*:0]const u8,
|
|
516
|
+
ws: Winsize,
|
|
517
|
+
) Error!SpawnedPair {
|
|
518
|
+
pty_spawn_mutex.lock();
|
|
519
|
+
defer pty_spawn_mutex.unlock();
|
|
520
|
+
|
|
521
|
+
// Open the pty pair by hand rather than `openpty`, so the CHILD end is
|
|
522
|
+
// opened close-on-exec ATOMICALLY (`open` with O_CLOEXEC). The child
|
|
523
|
+
// end is the descriptor that matters most for the inheritance race:
|
|
524
|
+
// if a concurrent fork on another thread inherited a non-CLOEXEC
|
|
525
|
+
// child end across its exec, it would hold THIS pty open after our
|
|
526
|
+
// child exits, so no EOF and no `.exit` event ever arrives.
|
|
527
|
+
// `posix_openpt` + `grantpt` + `unlockpt` is the portable primitive
|
|
528
|
+
// underneath `openpty`; the parent end's CLOEXEC is applied — and
|
|
529
|
+
// VERIFIED — immediately after (Linux honors O_CLOEXEC on
|
|
530
|
+
// `posix_openpt` directly; Darwin ignores it, which is one of the
|
|
531
|
+
// windows the spawn lock closes against our own forks).
|
|
532
|
+
const parent = c.posix_openpt(o_rdwr | o_noctty | o_cloexec_open);
|
|
533
|
+
if (parent < 0) return error.PtyOpenFailed;
|
|
534
|
+
if (!setCloexec(parent)) {
|
|
535
|
+
_ = c.close(parent);
|
|
536
|
+
return error.PtyOpenFailed;
|
|
537
|
+
}
|
|
538
|
+
if (c.grantpt(parent) != 0 or c.unlockpt(parent) != 0) {
|
|
539
|
+
_ = c.close(parent);
|
|
540
|
+
return error.PtyOpenFailed;
|
|
541
|
+
}
|
|
542
|
+
// `ptsname` returns libc-managed SHARED storage (not thread-safe):
|
|
543
|
+
// two runtimes spawning ptys on different threads could otherwise
|
|
544
|
+
// race, the second call overwriting the first's child-end name before
|
|
545
|
+
// it opens. The spawn lock serializes the resolve-and-copy so each
|
|
546
|
+
// spawn opens its own child end. (`ptsname_r` is not portably
|
|
547
|
+
// available — macOS lacks it on older SDKs — so a copy under the
|
|
548
|
+
// lock is the portable answer.)
|
|
549
|
+
var name_buf: [128]u8 = undefined;
|
|
550
|
+
const child_name = blk: {
|
|
551
|
+
const shared_name = c.ptsname(parent) orelse {
|
|
552
|
+
_ = c.close(parent);
|
|
553
|
+
return error.PtyOpenFailed;
|
|
554
|
+
};
|
|
555
|
+
const span = std.mem.span(shared_name);
|
|
556
|
+
if (span.len + 1 > name_buf.len) {
|
|
557
|
+
_ = c.close(parent);
|
|
558
|
+
return error.PtyOpenFailed;
|
|
559
|
+
}
|
|
560
|
+
@memcpy(name_buf[0..span.len], span);
|
|
561
|
+
name_buf[span.len] = 0;
|
|
562
|
+
break :blk name_buf[0..span.len :0];
|
|
563
|
+
};
|
|
564
|
+
var child_fd = c.open(child_name.ptr, o_rdwr | o_noctty | o_cloexec_open, @as(c_uint, 0));
|
|
565
|
+
if (child_fd < 0) {
|
|
566
|
+
_ = c.close(parent);
|
|
567
|
+
return error.PtyOpenFailed;
|
|
568
|
+
}
|
|
569
|
+
// Keep the child end off the standard descriptors: `login_tty` dup2's
|
|
570
|
+
// it onto 0/1/2, and dup2 CLEARS close-on-exec on its copies — but a
|
|
571
|
+
// SAME-fd dup2 (the child end already IS fd 0/1/2, which happens when
|
|
572
|
+
// the host started with standard descriptors closed) is a no-op that
|
|
573
|
+
// leaves the CLOEXEC flag set, so the child's stdio would vanish at
|
|
574
|
+
// execve. Relocating to a high fd guarantees the dup2 targets are
|
|
575
|
+
// distinct and their CLOEXEC gets cleared.
|
|
576
|
+
child_fd = relocateAboveStdio(child_fd) orelse {
|
|
577
|
+
_ = c.close(parent);
|
|
578
|
+
return error.PtyOpenFailed;
|
|
579
|
+
};
|
|
580
|
+
// Non-blocking parent end: the sole io thread must never block inside a
|
|
581
|
+
// write when the child stops reading its stdin (a full pty input
|
|
582
|
+
// buffer), which would stall stdout draining and deadlock both
|
|
583
|
+
// sides. Reads and writes handle EAGAIN; the poll loop paces both.
|
|
584
|
+
// Set AFTER the child end opened, deliberately: some Darwin kernels
|
|
585
|
+
// answer ENOTTY to any nonblocking request (fcntl F_SETFL and the
|
|
586
|
+
// FIONBIO ioctl alike) on a pty parent whose replica has never been
|
|
587
|
+
// opened, and accept the same call once it has.
|
|
588
|
+
if (!setNonblock(parent)) {
|
|
589
|
+
_ = c.close(parent);
|
|
590
|
+
_ = c.close(child_fd);
|
|
591
|
+
return error.PtyOpenFailed;
|
|
592
|
+
}
|
|
593
|
+
// Push the initial window size onto the child end (the child's
|
|
594
|
+
// terminal) before the fork so the child's very first TIOCGWINSZ sees
|
|
595
|
+
// the requested grid. `openpty` applied its `winp` to the child end;
|
|
596
|
+
// match that — setting it on the parent end does not reliably
|
|
597
|
+
// propagate before the child end becomes a controlling terminal.
|
|
598
|
+
_ = c.ioctl(child_fd, tiocswinsz, &ws);
|
|
599
|
+
|
|
600
|
+
// The exec self-pipe: close-on-exec on the write end, so a
|
|
601
|
+
// successful `execve` closes it and the parent reads EOF (exec
|
|
602
|
+
// worked). A failed exec writes its errno and the parent reads it,
|
|
603
|
+
// distinguishing "the pty forked but the program could not start"
|
|
604
|
+
// (`error.PtyCommandNotFound`) from a program that ran and exited
|
|
605
|
+
// 127 on its own — a shebang naming a missing interpreter passes
|
|
606
|
+
// the X_OK check yet fails at exec, and must not masquerade as a
|
|
607
|
+
// normal exit.
|
|
608
|
+
// Both ends close-on-exec (atomically on Linux via pipe2): the
|
|
609
|
+
// write end must close on the child's successful exec to signal EOF
|
|
610
|
+
// (and must not leak to a concurrent fork's child, which would
|
|
611
|
+
// delay that EOF), and the read end must not leak either. The
|
|
612
|
+
// exec-status poll's timeout is the net for Darwin's residual
|
|
613
|
+
// sub-syscall window.
|
|
614
|
+
const raw_pipe = makePipe(false) catch {
|
|
615
|
+
_ = c.close(parent);
|
|
616
|
+
_ = c.close(child_fd);
|
|
617
|
+
return error.PtyOpenFailed;
|
|
618
|
+
};
|
|
619
|
+
// The write end must also clear the standard descriptors: `login_tty`
|
|
620
|
+
// dup2's the child end onto 0/1/2 in the child, and if the write end
|
|
621
|
+
// sat on fd 1 or 2 that dup2 would clobber it — the child could then
|
|
622
|
+
// never report an exec failure, so a missing-interpreter exec would
|
|
623
|
+
// masquerade as a normal exit. (This only bites when the host began
|
|
624
|
+
// with standard descriptors closed; the relocation is a no-op
|
|
625
|
+
// otherwise. `relocateAboveStdio` closes the original on both
|
|
626
|
+
// success and failure.)
|
|
627
|
+
const exec_read = relocateAboveStdio(raw_pipe[0]) orelse {
|
|
628
|
+
_ = c.close(parent);
|
|
629
|
+
_ = c.close(child_fd);
|
|
630
|
+
_ = c.close(raw_pipe[1]);
|
|
631
|
+
return error.PtyOpenFailed;
|
|
632
|
+
};
|
|
633
|
+
const exec_write = relocateAboveStdio(raw_pipe[1]) orelse {
|
|
634
|
+
_ = c.close(parent);
|
|
635
|
+
_ = c.close(child_fd);
|
|
636
|
+
_ = c.close(exec_read);
|
|
637
|
+
return error.PtyOpenFailed;
|
|
638
|
+
};
|
|
639
|
+
const exec_pipe = [2]c_int{ exec_read, exec_write };
|
|
640
|
+
|
|
641
|
+
const pid = c.fork();
|
|
642
|
+
if (pid < 0) {
|
|
643
|
+
_ = c.close(parent);
|
|
644
|
+
_ = c.close(child_fd);
|
|
645
|
+
_ = c.close(exec_pipe[0]);
|
|
646
|
+
_ = c.close(exec_pipe[1]);
|
|
647
|
+
return error.PtyForkFailed;
|
|
648
|
+
}
|
|
649
|
+
if (pid == 0) {
|
|
650
|
+
// CHILD. Async-signal-safe only from here.
|
|
651
|
+
_ = c.close(parent);
|
|
652
|
+
_ = c.close(exec_pipe[0]);
|
|
653
|
+
if (c.login_tty(child_fd) != 0) reportExecFailure(exec_pipe[1]);
|
|
654
|
+
_ = c.execve(resolved_z.ptr, argv_z.ptr, envp_z.ptr);
|
|
655
|
+
reportExecFailure(exec_pipe[1]);
|
|
656
|
+
}
|
|
657
|
+
// PARENT.
|
|
658
|
+
_ = c.close(child_fd);
|
|
659
|
+
_ = c.close(exec_pipe[1]);
|
|
660
|
+
return .{ .parent = parent, .pid = pid, .exec_read = exec_pipe[0] };
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/// CHILD-side exec-failure report: write the errno byte into the self-
|
|
664
|
+
/// pipe and exit. Async-signal-safe (`write`/`_exit`). EINTR retries —
|
|
665
|
+
/// a signal interrupting the one-byte report must not drop it, or the
|
|
666
|
+
/// parent reads a clean EOF and mistakes the failed exec for success.
|
|
667
|
+
fn reportExecFailure(write_fd: c_int) noreturn {
|
|
668
|
+
const byte = [_]u8{1};
|
|
669
|
+
while (true) {
|
|
670
|
+
if (c.write(write_fd, &byte, 1) >= 0) break;
|
|
671
|
+
if (errnoValue() == eintr) continue;
|
|
672
|
+
break;
|
|
673
|
+
}
|
|
674
|
+
c._exit(127);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
fn setCloexec(fd: c_int) bool {
|
|
678
|
+
const flags = c.fcntl(fd, f_getfd, @as(c_int, 0));
|
|
679
|
+
if (flags < 0) return false;
|
|
680
|
+
return c.fcntl(fd, f_setfd, flags | fd_cloexec) >= 0;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/// Ensure `fd` is above the standard descriptors (>= 3), close-on-exec.
|
|
684
|
+
/// A descriptor already at 3+ is returned unchanged; a low one is
|
|
685
|
+
/// duplicated to a high, close-on-exec fd and the original is closed.
|
|
686
|
+
/// Returns null on failure, having closed the original either way, so
|
|
687
|
+
/// the caller never double-closes it. This keeps `login_tty`'s dup2
|
|
688
|
+
/// onto 0/1/2 from being a same-fd no-op that would strand the
|
|
689
|
+
/// close-on-exec flag on a descriptor the child must keep.
|
|
690
|
+
fn relocateAboveStdio(fd: c_int) ?c_int {
|
|
691
|
+
if (fd >= 3) return fd;
|
|
692
|
+
const high = c.fcntl(fd, f_dupfd_cloexec, @as(c_int, 3));
|
|
693
|
+
_ = c.close(fd);
|
|
694
|
+
if (high < 0) return null;
|
|
695
|
+
return high;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const ExecProbe = enum { succeeded, failed, unresolved };
|
|
699
|
+
|
|
700
|
+
/// Resolve exec status from the self-pipe read end. A failure byte (the
|
|
701
|
+
/// child's errno report) means exec FAILED; a clean EOF (every writer
|
|
702
|
+
/// closed) means it SUCCEEDED.
|
|
703
|
+
///
|
|
704
|
+
/// The read BLOCKS — up to a generous bound — so a slow `execve` (an
|
|
705
|
+
/// interpreter on a sluggish filesystem or automount) is awaited and its
|
|
706
|
+
/// eventual failure byte correctly reported, rather than assumed
|
|
707
|
+
/// successful. The bound exists because CLOEXEC does NOT keep an
|
|
708
|
+
/// EMBEDDER `fork` on a thread the toolkit does not own from TRANSIENTLY
|
|
709
|
+
/// inheriting the write end (`O_CLOEXEC` closes the inherited copy on
|
|
710
|
+
/// that child's `exec`, not its `fork`; the toolkit's OWN forks are
|
|
711
|
+
/// serialized out by the spawn lock), so EOF can be delayed until such a
|
|
712
|
+
/// forker execs. A timeout therefore resolves NOTHING — the exec may
|
|
713
|
+
/// still be pending — and reports `unresolved`: the caller carries the
|
|
714
|
+
/// pipe on the transport, where the reap-time check converts a late
|
|
715
|
+
/// failure byte into the exit's `spawn_failed` instead of guessing.
|
|
716
|
+
fn execStatus(fd: c_int) ExecProbe {
|
|
717
|
+
// Half a second, not seconds: the probe runs on the caller's (loop)
|
|
718
|
+
// thread, and since an unresolved verdict is CARRIED to the reap —
|
|
719
|
+
// where a late failure still reports `spawn_failed` exactly — the
|
|
720
|
+
// deadline buys only the nicety of a synchronous rejection for the
|
|
721
|
+
// common instant failure (a missing shebang interpreter reports
|
|
722
|
+
// within milliseconds). Anything slower resolves through the exit
|
|
723
|
+
// event instead of holding the loop.
|
|
724
|
+
const timeout_ns: u64 = 500 * std.time.ns_per_ms;
|
|
725
|
+
// The bound is a DEADLINE, not a per-poll timeout: `poll` restarts
|
|
726
|
+
// with a fresh timeout on every EINTR, so a fixed per-call timeout
|
|
727
|
+
// would let signals arriving less than the bound apart defer the
|
|
728
|
+
// timeout forever, blocking the spawn thread indefinitely. Recompute
|
|
729
|
+
// the remaining time against a monotonic start so the total wait
|
|
730
|
+
// stays capped no matter how many signals interrupt it. A missing
|
|
731
|
+
// monotonic clock (not expected on macOS/Linux) reports unresolved
|
|
732
|
+
// rather than risk an unbounded wait.
|
|
733
|
+
const start = clock.monotonicNanoseconds();
|
|
734
|
+
var fds = [1]Pollfd{.{ .fd = fd, .events = pollin, .revents = 0 }};
|
|
735
|
+
while (true) {
|
|
736
|
+
const now = clock.monotonicNanoseconds();
|
|
737
|
+
// A zero read is the clock's unavailable sentinel (not expected
|
|
738
|
+
// on macOS/Linux); report unresolved rather than risk an
|
|
739
|
+
// unbounded EINTR-retry loop. `-%` keeps a clock that appears
|
|
740
|
+
// to move backwards bounded too (it maps to a huge elapsed).
|
|
741
|
+
const elapsed = now -% start;
|
|
742
|
+
if (now == 0 or elapsed >= timeout_ns) return .unresolved;
|
|
743
|
+
const remaining_ms: c_int = @intCast(@min(
|
|
744
|
+
@as(u64, @intCast(std.math.maxInt(c_int))),
|
|
745
|
+
(timeout_ns - elapsed) / std.time.ns_per_ms,
|
|
746
|
+
));
|
|
747
|
+
const r = c.poll(&fds, 1, remaining_ms);
|
|
748
|
+
if (r < 0) {
|
|
749
|
+
if (errnoValue() == eintr) continue;
|
|
750
|
+
return .unresolved;
|
|
751
|
+
}
|
|
752
|
+
if (r == 0) return .unresolved; // deadline: verdict still pending
|
|
753
|
+
// Readable or hung up: a byte present is failure; a clean EOF
|
|
754
|
+
// (readable, zero bytes) is success.
|
|
755
|
+
if (fds[0].revents & pollin != 0) {
|
|
756
|
+
var probe: [1]u8 = undefined;
|
|
757
|
+
const n = c.read(fd, &probe, 1);
|
|
758
|
+
if (n > 0) return .failed;
|
|
759
|
+
if (n < 0 and errnoValue() == eintr) continue;
|
|
760
|
+
return .succeeded;
|
|
761
|
+
}
|
|
762
|
+
// POLLHUP/POLLERR with no data: the writer closed on exec.
|
|
763
|
+
return .succeeded;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
fn decodeStatus(status: c_int) Exit {
|
|
768
|
+
const s: u32 = @bitCast(status);
|
|
769
|
+
// WIFEXITED: low 7 bits (signal) are 0.
|
|
770
|
+
if (s & 0x7f == 0) {
|
|
771
|
+
return .{ .code = @intCast((s >> 8) & 0xff), .signal = 0 };
|
|
772
|
+
}
|
|
773
|
+
// WIFSIGNALED: low 7 bits carry the terminating signal.
|
|
774
|
+
const sig: i32 = @intCast(s & 0x7f);
|
|
775
|
+
return .{ .code = -1, .signal = sig };
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
fn resolveExecutable(arg0: []const u8, env: ?[]const EnvVar, buf: []u8) ?[]const u8 {
|
|
779
|
+
if (std.mem.indexOfScalar(u8, arg0, '/') != null) {
|
|
780
|
+
if (!executableAt(buf, arg0)) return null;
|
|
781
|
+
if (arg0.len >= buf.len) return null;
|
|
782
|
+
@memcpy(buf[0..arg0.len], arg0);
|
|
783
|
+
return buf[0..arg0.len];
|
|
784
|
+
}
|
|
785
|
+
const path = lookupEnv(env, "PATH") orelse "/usr/bin:/bin:/usr/sbin:/sbin";
|
|
786
|
+
var scratch: [std.fs.max_path_bytes]u8 = undefined;
|
|
787
|
+
var it = std.mem.splitScalar(u8, path, ':');
|
|
788
|
+
while (it.next()) |component| {
|
|
789
|
+
// A POSIX empty PATH component names the current directory.
|
|
790
|
+
const dir = if (component.len == 0) "." else component;
|
|
791
|
+
const joined = std.fmt.bufPrint(buf, "{s}/{s}", .{ dir, arg0 }) catch continue;
|
|
792
|
+
if (!executableAt(&scratch, joined)) continue;
|
|
793
|
+
return joined;
|
|
794
|
+
}
|
|
795
|
+
return null;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/// X_OK access check through libc; `scratch` holds the NUL-terminated copy.
|
|
799
|
+
fn executableAt(scratch: []u8, path: []const u8) bool {
|
|
800
|
+
if (path.len + 1 > scratch.len) return false;
|
|
801
|
+
@memcpy(scratch[0..path.len], path);
|
|
802
|
+
scratch[path.len] = 0;
|
|
803
|
+
return c.access(scratch[0..path.len :0].ptr, 1) == 0;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
fn lookupEnv(env: ?[]const EnvVar, name: []const u8) ?[]const u8 {
|
|
807
|
+
const list = env orelse return null;
|
|
808
|
+
for (list) |entry| {
|
|
809
|
+
if (std.mem.eql(u8, entry.name, name)) return entry.value;
|
|
810
|
+
}
|
|
811
|
+
return null;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
fn buildArgvZ(arena: std.mem.Allocator, argv: []const []const u8) ![:null]const ?[*:0]const u8 {
|
|
815
|
+
var out = try arena.allocSentinel(?[*:0]const u8, argv.len, null);
|
|
816
|
+
// argv[0] the program sees is the caller's original arg0 (the name it
|
|
817
|
+
// expects); execve's separate path argument carries the resolved one.
|
|
818
|
+
for (argv, 0..) |arg, i| out[i] = try arena.dupeZ(u8, arg);
|
|
819
|
+
return out;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
fn buildEnvpZ(arena: std.mem.Allocator, env: ?[]const EnvVar, term: []const u8) ![:null]const ?[*:0]const u8 {
|
|
823
|
+
const list = env orelse &[_]EnvVar{};
|
|
824
|
+
var has_term = false;
|
|
825
|
+
for (list) |entry| {
|
|
826
|
+
if (std.mem.eql(u8, entry.name, "TERM")) has_term = true;
|
|
827
|
+
}
|
|
828
|
+
const extra: usize = if (has_term) 0 else 1;
|
|
829
|
+
var out = try arena.allocSentinel(?[*:0]const u8, list.len + extra, null);
|
|
830
|
+
for (list, 0..) |entry, i| {
|
|
831
|
+
// The requested TERM REPLACES an inherited one: the spawn
|
|
832
|
+
// declared what terminal the child is attached to (this pty's
|
|
833
|
+
// emulator), and a stale `TERM=dumb` riding in from the host
|
|
834
|
+
// environment would misdeclare its capabilities.
|
|
835
|
+
if (std.mem.eql(u8, entry.name, "TERM")) {
|
|
836
|
+
out[i] = try std.fmt.allocPrintSentinel(arena, "TERM={s}", .{term}, 0);
|
|
837
|
+
continue;
|
|
838
|
+
}
|
|
839
|
+
out[i] = try std.fmt.allocPrintSentinel(arena, "{s}={s}", .{ entry.name, entry.value }, 0);
|
|
840
|
+
}
|
|
841
|
+
if (!has_term) {
|
|
842
|
+
out[list.len] = try std.fmt.allocPrintSentinel(arena, "TERM={s}", .{term}, 0);
|
|
843
|
+
}
|
|
844
|
+
return out;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/// The kernel's window-size word (struct winsize): identical layout on
|
|
848
|
+
/// Linux and Darwin.
|
|
849
|
+
const Winsize = extern struct {
|
|
850
|
+
row: u16,
|
|
851
|
+
col: u16,
|
|
852
|
+
xpixel: u16,
|
|
853
|
+
ypixel: u16,
|
|
854
|
+
};
|
|
855
|
+
|
|
856
|
+
// TIOCSWINSZ differs by platform (the BSD `_IOW('t',103,winsize)` encoding
|
|
857
|
+
// on Darwin, a fixed constant on Linux). Stated per-os because std.c
|
|
858
|
+
// exposes only the GET variant on Darwin.
|
|
859
|
+
const tiocswinsz: c_ulong = switch (builtin.os.tag) {
|
|
860
|
+
.linux => 0x5414,
|
|
861
|
+
.macos => 0x80087467,
|
|
862
|
+
else => 0,
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
// WNOHANG is 1 on both Linux and Darwin.
|
|
866
|
+
const wnohang: c_int = 1;
|
|
867
|
+
// F_GETFL/F_SETFL and O_NONBLOCK per platform (fcntl.h).
|
|
868
|
+
const f_getfl: c_int = 3;
|
|
869
|
+
const f_setfl: c_int = 4;
|
|
870
|
+
const f_getfd: c_int = 1;
|
|
871
|
+
const f_setfd: c_int = 2;
|
|
872
|
+
const fd_cloexec: c_int = 1;
|
|
873
|
+
const o_nonblock: c_int = switch (builtin.os.tag) {
|
|
874
|
+
.linux => 0x800,
|
|
875
|
+
.macos => 0x4,
|
|
876
|
+
else => 0,
|
|
877
|
+
};
|
|
878
|
+
// pipe2 flag values (Linux): O_CLOEXEC and O_NONBLOCK as c_uint.
|
|
879
|
+
const o_cloexec: c_uint = 0x80000;
|
|
880
|
+
const o_nonblock_flag: c_uint = 0x800;
|
|
881
|
+
|
|
882
|
+
// open(2) flags for the pty pair, per platform.
|
|
883
|
+
const o_rdwr: c_int = 0x2;
|
|
884
|
+
const o_noctty: c_int = switch (builtin.os.tag) {
|
|
885
|
+
.linux => 0x100,
|
|
886
|
+
.macos => 0x20000,
|
|
887
|
+
else => 0,
|
|
888
|
+
};
|
|
889
|
+
// O_CLOEXEC on the parent end (posix_openpt, honored on Linux, ignored on
|
|
890
|
+
// Darwin) and on the child end (open, honored on both — the atomic close
|
|
891
|
+
// of the inheritance race).
|
|
892
|
+
const o_cloexec_open: c_int = switch (builtin.os.tag) {
|
|
893
|
+
.linux => 0x80000,
|
|
894
|
+
.macos => 0x1000000,
|
|
895
|
+
else => 0,
|
|
896
|
+
};
|
|
897
|
+
// FIONBIO ("set non-blocking io") per platform, the fcntl fallback in
|
|
898
|
+
// `setNonblock`.
|
|
899
|
+
const fionbio: c_ulong = switch (builtin.os.tag) {
|
|
900
|
+
.linux => 0x5421,
|
|
901
|
+
.macos => 0x8004667e,
|
|
902
|
+
else => 0,
|
|
903
|
+
};
|
|
904
|
+
const sigterm: c_int = 15;
|
|
905
|
+
const sigkill: c_int = 9;
|
|
906
|
+
const sighup: c_int = 1;
|
|
907
|
+
const eintr: c_int = 4;
|
|
908
|
+
const eio: c_int = 5;
|
|
909
|
+
const echild: c_int = 10;
|
|
910
|
+
// EAGAIN (== EWOULDBLOCK on both platforms): no progress on a
|
|
911
|
+
// non-blocking fd right now.
|
|
912
|
+
const eagain: c_int = switch (builtin.os.tag) {
|
|
913
|
+
.linux => 11,
|
|
914
|
+
.macos => 35,
|
|
915
|
+
else => 11,
|
|
916
|
+
};
|
|
917
|
+
// F_DUPFD_CLOEXEC differs by platform.
|
|
918
|
+
const f_dupfd_cloexec: c_int = switch (builtin.os.tag) {
|
|
919
|
+
.linux => 1030,
|
|
920
|
+
.macos => 67,
|
|
921
|
+
else => 0,
|
|
922
|
+
};
|
|
923
|
+
|
|
924
|
+
fn errnoValue() c_int {
|
|
925
|
+
return switch (builtin.os.tag) {
|
|
926
|
+
.macos => c.__error().*,
|
|
927
|
+
.linux => c.__errno_location().*,
|
|
928
|
+
else => 0,
|
|
929
|
+
};
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/// libc externs for the fork/exec/pty path. Resolved through the C library
|
|
933
|
+
/// the platform layer already links; `openpty`/`login_tty` live in libutil
|
|
934
|
+
/// on Linux (linked by the platform build) and in libSystem on macOS.
|
|
935
|
+
const c = struct {
|
|
936
|
+
extern "c" fn posix_openpt(flags: c_int) c_int;
|
|
937
|
+
extern "c" fn grantpt(fd: c_int) c_int;
|
|
938
|
+
extern "c" fn unlockpt(fd: c_int) c_int;
|
|
939
|
+
extern "c" fn ptsname(fd: c_int) ?[*:0]const u8;
|
|
940
|
+
extern "c" fn open(path: [*:0]const u8, flags: c_int, ...) c_int;
|
|
941
|
+
extern "c" fn login_tty(fd: c_int) c_int;
|
|
942
|
+
extern "c" fn fork() c_int;
|
|
943
|
+
extern "c" fn execve(
|
|
944
|
+
path: [*:0]const u8,
|
|
945
|
+
argv: [*:null]const ?[*:0]const u8,
|
|
946
|
+
envp: [*:null]const ?[*:0]const u8,
|
|
947
|
+
) c_int;
|
|
948
|
+
extern "c" fn read(fd: c_int, buf: [*]u8, len: usize) isize;
|
|
949
|
+
extern "c" fn write(fd: c_int, buf: [*]const u8, len: usize) isize;
|
|
950
|
+
extern "c" fn close(fd: c_int) c_int;
|
|
951
|
+
extern "c" fn access(path: [*:0]const u8, mode: c_int) c_int;
|
|
952
|
+
extern "c" fn _exit(code: c_int) noreturn;
|
|
953
|
+
extern "c" fn kill(pid: c_int, sig: c_int) c_int;
|
|
954
|
+
extern "c" fn waitpid(pid: c_int, status: *c_int, options: c_int) c_int;
|
|
955
|
+
extern "c" fn usleep(usec: c_uint) c_int;
|
|
956
|
+
// ioctl is variadic in C; declaring it variadic here matches the
|
|
957
|
+
// platform ABI for the winsize pointer argument (a fixed-arg
|
|
958
|
+
// declaration mis-passes it on arm64, silently dropping the size).
|
|
959
|
+
extern "c" fn ioctl(fd: c_int, request: c_ulong, ...) c_int;
|
|
960
|
+
extern "c" fn pipe(fds: *[2]c_int) c_int;
|
|
961
|
+
extern "c" fn pipe2(fds: *[2]c_int, flags: c_uint) c_int;
|
|
962
|
+
extern "c" fn fcntl(fd: c_int, cmd: c_int, ...) c_int;
|
|
963
|
+
extern "c" fn poll(fds: [*]Pollfd, nfds: c_uint, timeout: c_int) c_int;
|
|
964
|
+
extern "c" fn __error() *c_int; // Darwin errno
|
|
965
|
+
extern "c" fn __errno_location() *c_int; // Linux errno
|
|
966
|
+
};
|
|
967
|
+
|
|
968
|
+
/// A nudge pipe for the io thread: [read end, write end]. BOTH ends are
|
|
969
|
+
/// non-blocking (the write side so a burst of loop-thread nudges against
|
|
970
|
+
/// a full pipe can never block the UI loop — a full pipe already means a
|
|
971
|
+
/// wake is pending; the read side so the eager drain never parks the io
|
|
972
|
+
/// thread) and BOTH ends are close-on-exec: a pty child inherits every
|
|
973
|
+
/// parent fd across fork, and without CLOEXEC a daemonized descendant
|
|
974
|
+
/// would keep these descriptors — and the pipe itself — alive past the
|
|
975
|
+
/// runtime closing its copies. The child needs neither end.
|
|
976
|
+
pub fn pipePair() Error![2]c_int {
|
|
977
|
+
if (comptime is_windows) return windows_impl.pipePair();
|
|
978
|
+
if (comptime !posix_supported) return error.PtyUnsupported;
|
|
979
|
+
// Under the spawn lock: Darwin's pipe-then-fcntl flag gap is a
|
|
980
|
+
// descriptor-inheritance window exactly like the spawn's own, so no
|
|
981
|
+
// PTY fork can inherit a not-yet-CLOEXEC wake pipe across its exec.
|
|
982
|
+
// Forks the lock does not cover (job spawns, whose process start
|
|
983
|
+
// blocks on its own exec pipe and must never hold a lock the UI
|
|
984
|
+
// loop takes; embedder forks on foreign threads) are the bounded
|
|
985
|
+
// residual: inherited copies die at those children's execs, and the
|
|
986
|
+
// one lasting effect — a delayed exec-pipe EOF — is resolved by the
|
|
987
|
+
// carried reap-time verdict.
|
|
988
|
+
pty_spawn_mutex.lock();
|
|
989
|
+
defer pty_spawn_mutex.unlock();
|
|
990
|
+
return makePipe(true);
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
/// Create a pipe with both ends close-on-exec (and, when `nonblock`,
|
|
994
|
+
/// non-blocking). On Linux the flags are set ATOMICALLY at creation via
|
|
995
|
+
/// `pipe2`, closing the concurrent-fork inheritance window entirely; on
|
|
996
|
+
/// Darwin there is no `pipe2`, so the flags are applied with `fcntl`
|
|
997
|
+
/// immediately after — an irreducible sub-syscall window on that OS.
|
|
998
|
+
/// Every caller here runs under the pty spawn lock, which closes the
|
|
999
|
+
/// window against pty forks; the residual is a fork the lock cannot
|
|
1000
|
+
/// cover (a job spawn's process start, an embedder fork on a foreign
|
|
1001
|
+
/// thread) landing inside it. That residual is bounded on every axis:
|
|
1002
|
+
/// the inherited copy dies at that child's exec; a job child whose exec
|
|
1003
|
+
/// itself wedges holds an exec-pipe writer only until it resolves,
|
|
1004
|
+
/// costing at most the half-second probe (whose unresolved verdict
|
|
1005
|
+
/// carries to the reap and stays CORRECT); and a held wake pipe merely
|
|
1006
|
+
/// outlives its session's close until that exec. A failed setup closes
|
|
1007
|
+
/// both ends and aborts. CLOEXEC is load-bearing (an inherited
|
|
1008
|
+
/// exec-pipe writer would delay EOF; an inherited wake pipe would
|
|
1009
|
+
/// leak); non-blocking is load-bearing on the wake pipe (a full pipe
|
|
1010
|
+
/// must never block the UI thread inside `nudge`).
|
|
1011
|
+
fn makePipe(nonblock: bool) Error![2]c_int {
|
|
1012
|
+
var fds: [2]c_int = undefined;
|
|
1013
|
+
if (comptime builtin.os.tag == .linux) {
|
|
1014
|
+
var flags: c_uint = o_cloexec;
|
|
1015
|
+
if (nonblock) flags |= o_nonblock_flag;
|
|
1016
|
+
if (c.pipe2(&fds, flags) != 0) return error.PtyOpenFailed;
|
|
1017
|
+
return fds;
|
|
1018
|
+
}
|
|
1019
|
+
if (c.pipe(&fds) != 0) return error.PtyOpenFailed;
|
|
1020
|
+
for (fds) |fd| {
|
|
1021
|
+
if (nonblock) {
|
|
1022
|
+
const flags = c.fcntl(fd, f_getfl, @as(c_int, 0));
|
|
1023
|
+
if (flags < 0 or c.fcntl(fd, f_setfl, flags | o_nonblock) < 0) {
|
|
1024
|
+
_ = c.close(fds[0]);
|
|
1025
|
+
_ = c.close(fds[1]);
|
|
1026
|
+
return error.PtyOpenFailed;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
if (!setCloexec(fd)) {
|
|
1030
|
+
_ = c.close(fds[0]);
|
|
1031
|
+
_ = c.close(fds[1]);
|
|
1032
|
+
return error.PtyOpenFailed;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
return fds;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
pub fn closeFd(fd: c_int) void {
|
|
1039
|
+
if (comptime is_windows) return windows_impl.closeFd(fd);
|
|
1040
|
+
if (comptime !posix_supported) return;
|
|
1041
|
+
if (fd >= 0) _ = c.close(fd);
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/// Set O_NONBLOCK on `fd`, preferring `fcntl(F_SETFL)` and falling back
|
|
1045
|
+
/// to the `FIONBIO` ioctl: Darwin's pty parent-end driver rejects
|
|
1046
|
+
/// F_SETFL with ENOTTY on some macOS releases (observed on 14.x; newer
|
|
1047
|
+
/// kernels accept it), while FIONBIO succeeds on every release — the
|
|
1048
|
+
/// same fallback the mainstream event loops carry for exactly this fd.
|
|
1049
|
+
fn setNonblock(fd: c_int) bool {
|
|
1050
|
+
if (comptime !posix_supported) return false;
|
|
1051
|
+
const flags = c.fcntl(fd, f_getfl, @as(c_int, 0));
|
|
1052
|
+
if (flags >= 0 and c.fcntl(fd, f_setfl, flags | o_nonblock) >= 0) return true;
|
|
1053
|
+
var one: c_int = 1;
|
|
1054
|
+
return c.ioctl(fd, fionbio, &one) == 0;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/// Write one byte into the nudge pipe. EINTR retries — losing the only
|
|
1058
|
+
/// wake would strand staged outbound bytes; a full pipe (EAGAIN) is a
|
|
1059
|
+
/// nudge already coalesced and returns.
|
|
1060
|
+
pub fn nudge(fd: c_int) void {
|
|
1061
|
+
if (comptime is_windows) return windows_impl.nudge(fd);
|
|
1062
|
+
if (comptime !posix_supported) return;
|
|
1063
|
+
const byte = [_]u8{1};
|
|
1064
|
+
while (true) {
|
|
1065
|
+
if (c.write(fd, &byte, 1) >= 0) return;
|
|
1066
|
+
if (errnoValue() == eintr) continue;
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/// Drain whatever accumulated in the nudge pipe.
|
|
1072
|
+
pub fn drainNudges(fd: c_int) void {
|
|
1073
|
+
if (comptime is_windows) return windows_impl.drainNudges(fd);
|
|
1074
|
+
if (comptime !posix_supported) return;
|
|
1075
|
+
var buf: [64]u8 = undefined;
|
|
1076
|
+
_ = c.read(fd, &buf, buf.len);
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
/// What one poll round observed.
|
|
1080
|
+
pub const Ready = struct {
|
|
1081
|
+
readable: bool = false,
|
|
1082
|
+
writable: bool = false,
|
|
1083
|
+
hangup: bool = false,
|
|
1084
|
+
nudged: bool = false,
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
/// Block until the transport is readable (`want_read`), writable
|
|
1088
|
+
/// (`want_write`), hung up, or the nudge pipe fires. A caller wanting
|
|
1089
|
+
/// NEITHER direction (a parked reader with nothing to write) waits on
|
|
1090
|
+
/// the nudge pipe alone — POLLHUP is unmaskable, so keeping the parent
|
|
1091
|
+
/// end in the set would turn a hangup racing a full staging ring into
|
|
1092
|
+
/// a busy loop. (Takes the whole transport, not a bare fd: the Windows
|
|
1093
|
+
/// backend waits on events and the process handle, not one
|
|
1094
|
+
/// descriptor.)
|
|
1095
|
+
pub fn wait(transport: Pty, nudge_fd: c_int, want_read: bool, want_write: bool) Ready {
|
|
1096
|
+
if (comptime is_windows) return windows_impl.wait(transport, nudge_fd, want_read, want_write);
|
|
1097
|
+
if (comptime !posix_supported) return .{};
|
|
1098
|
+
const parent = transport.parent;
|
|
1099
|
+
const parent_events: c_short = (if (want_read) pollin else 0) | (if (want_write) pollout else 0);
|
|
1100
|
+
var fds = [2]Pollfd{
|
|
1101
|
+
.{ .fd = nudge_fd, .events = pollin, .revents = 0 },
|
|
1102
|
+
.{ .fd = parent, .events = parent_events, .revents = 0 },
|
|
1103
|
+
};
|
|
1104
|
+
const nfds: c_uint = if (parent_events == 0) 1 else 2;
|
|
1105
|
+
const r = c.poll(&fds, nfds, -1);
|
|
1106
|
+
if (r < 0) return .{};
|
|
1107
|
+
return .{
|
|
1108
|
+
.readable = nfds == 2 and fds[1].revents & pollin != 0,
|
|
1109
|
+
.writable = nfds == 2 and fds[1].revents & pollout != 0,
|
|
1110
|
+
.hangup = nfds == 2 and fds[1].revents & (pollhup | pollerr) != 0,
|
|
1111
|
+
.nudged = fds[0].revents & pollin != 0,
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
const Pollfd = extern struct {
|
|
1116
|
+
fd: c_int,
|
|
1117
|
+
events: c_short,
|
|
1118
|
+
revents: c_short,
|
|
1119
|
+
};
|
|
1120
|
+
|
|
1121
|
+
// POLLIN/POLLOUT/POLLERR/POLLHUP share values on Linux and Darwin.
|
|
1122
|
+
const pollin: c_short = 0x1;
|
|
1123
|
+
const pollout: c_short = 0x4;
|
|
1124
|
+
const pollerr: c_short = 0x8;
|
|
1125
|
+
const pollhup: c_short = 0x10;
|
|
1126
|
+
|
|
1127
|
+
// ------------------------------------------------------------------ tests
|
|
1128
|
+
|
|
1129
|
+
/// Read the child's whole output, polling the non-blocking parent end to
|
|
1130
|
+
/// EOF — the effects io loop's poll discipline, condensed for the
|
|
1131
|
+
/// in-file tests (which have no effects channel).
|
|
1132
|
+
fn testReadAll(p: Pty, buf: []u8) usize {
|
|
1133
|
+
var total: usize = 0;
|
|
1134
|
+
while (total < buf.len) {
|
|
1135
|
+
const ready = wait(p, p.parent, true, false);
|
|
1136
|
+
if (p.read(buf[total..])) |n| {
|
|
1137
|
+
if (n == 0) return total; // EOF
|
|
1138
|
+
total += n;
|
|
1139
|
+
} else |err| switch (err) {
|
|
1140
|
+
error.WouldBlock => {
|
|
1141
|
+
if (ready.hangup) return total;
|
|
1142
|
+
},
|
|
1143
|
+
error.ReadFailed => return total,
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
return total;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
test "spawn rejects an empty argv and a missing command" {
|
|
1150
|
+
if (comptime !posix_supported) return;
|
|
1151
|
+
try std.testing.expectError(error.PtyArgvInvalid, spawn(std.testing.allocator, .{ .argv = &.{} }));
|
|
1152
|
+
try std.testing.expectError(error.PtyCommandNotFound, spawn(std.testing.allocator, .{
|
|
1153
|
+
.argv = &.{"/nonexistent/never-a-command"},
|
|
1154
|
+
}));
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
test "live pty round trip: output, exit code, controlling terminal" {
|
|
1158
|
+
if (comptime !posix_supported) return;
|
|
1159
|
+
const p = try spawn(std.testing.allocator, .{
|
|
1160
|
+
// `test -t 0` proves fd 0 is a real terminal — the controlling-tty
|
|
1161
|
+
// wiring, not just a pipe with a fancy name.
|
|
1162
|
+
.argv = &.{ "/bin/sh", "-c", "test -t 0 && printf hello; exit 7" },
|
|
1163
|
+
.cols = 40,
|
|
1164
|
+
.rows = 10,
|
|
1165
|
+
});
|
|
1166
|
+
defer p.close();
|
|
1167
|
+
var buf: [256]u8 = undefined;
|
|
1168
|
+
const total = testReadAll(p, &buf);
|
|
1169
|
+
try std.testing.expect(std.mem.indexOf(u8, buf[0..total], "hello") != null);
|
|
1170
|
+
const exit = p.reapBlocking();
|
|
1171
|
+
try std.testing.expectEqual(@as(i32, 7), exit.code);
|
|
1172
|
+
try std.testing.expectEqual(@as(i32, 0), exit.signal);
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
test "kill reports the terminating signal" {
|
|
1176
|
+
if (comptime !posix_supported) return;
|
|
1177
|
+
const p = try spawn(std.testing.allocator, .{ .argv = &.{ "/bin/sh", "-c", "sleep 30" } });
|
|
1178
|
+
defer p.close();
|
|
1179
|
+
p.resize(100, 30);
|
|
1180
|
+
p.kill(false);
|
|
1181
|
+
const exit = p.reapBlocking();
|
|
1182
|
+
try std.testing.expectEqual(@as(i32, -1), exit.code);
|
|
1183
|
+
try std.testing.expectEqual(@as(i32, 9), exit.signal);
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
test "the child environment is exactly env plus TERM" {
|
|
1187
|
+
if (comptime !posix_supported) return;
|
|
1188
|
+
const p = try spawn(std.testing.allocator, .{
|
|
1189
|
+
.argv = &.{ "/bin/sh", "-c", "printf '%s|%s|%s' \"$TERM\" \"$MARKER\" \"$HOME\"" },
|
|
1190
|
+
.env = &.{.{ .name = "MARKER", .value = "pty-proof" }},
|
|
1191
|
+
});
|
|
1192
|
+
defer p.close();
|
|
1193
|
+
var buf: [256]u8 = undefined;
|
|
1194
|
+
const total = testReadAll(p, &buf);
|
|
1195
|
+
_ = p.reapBlocking();
|
|
1196
|
+
const out = buf[0..total];
|
|
1197
|
+
// TERM injected, MARKER passed through, HOME absent (clean env).
|
|
1198
|
+
try std.testing.expect(std.mem.indexOf(u8, out, default_term ++ "|pty-proof|") != null);
|
|
1199
|
+
|
|
1200
|
+
// An INHERITED TERM is replaced, never preserved: the spawn
|
|
1201
|
+
// declared what terminal the child is attached to, and a stale
|
|
1202
|
+
// `TERM=dumb` from the host environment would misdeclare it.
|
|
1203
|
+
const q = try spawn(std.testing.allocator, .{
|
|
1204
|
+
.argv = &.{ "/bin/sh", "-c", "printf '%s' \"$TERM\"" },
|
|
1205
|
+
.env = &.{.{ .name = "TERM", .value = "dumb" }},
|
|
1206
|
+
.term = "xterm-256color",
|
|
1207
|
+
});
|
|
1208
|
+
defer q.close();
|
|
1209
|
+
var term_buf: [128]u8 = undefined;
|
|
1210
|
+
const term_total = testReadAll(q, &term_buf);
|
|
1211
|
+
_ = q.reapBlocking();
|
|
1212
|
+
try std.testing.expect(std.mem.indexOf(u8, term_buf[0..term_total], "xterm-256color") != null);
|
|
1213
|
+
try std.testing.expect(std.mem.indexOf(u8, term_buf[0..term_total], "dumb") == null);
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
test "a late exec-failure byte on the carried status pipe converts at reap time" {
|
|
1217
|
+
if (comptime !posix_supported) return;
|
|
1218
|
+
// The unresolved-probe carry: a failure byte written after the
|
|
1219
|
+
// probe's deadline is read — non-blocking — at reap time.
|
|
1220
|
+
const with_byte = try makePipe(true);
|
|
1221
|
+
const byte = [_]u8{1};
|
|
1222
|
+
_ = c.write(with_byte[1], &byte, 1);
|
|
1223
|
+
const failed_pty: Pty = .{ .parent = -1, .pid = -1, .exec_status = with_byte[0] };
|
|
1224
|
+
try std.testing.expect(failed_pty.lateExecFailure());
|
|
1225
|
+
_ = c.close(with_byte[0]);
|
|
1226
|
+
_ = c.close(with_byte[1]);
|
|
1227
|
+
|
|
1228
|
+
// No byte before the child died means the exec succeeded: an empty
|
|
1229
|
+
// (or closed) pipe reads as success and never blocks.
|
|
1230
|
+
const without_byte = try makePipe(true);
|
|
1231
|
+
_ = c.close(without_byte[1]);
|
|
1232
|
+
const started_pty: Pty = .{ .parent = -1, .pid = -1, .exec_status = without_byte[0] };
|
|
1233
|
+
try std.testing.expect(!started_pty.lateExecFailure());
|
|
1234
|
+
_ = c.close(without_byte[0]);
|
|
1235
|
+
|
|
1236
|
+
// A spawn whose probe resolved carries no pipe: never a late report.
|
|
1237
|
+
const resolved_pty: Pty = .{ .parent = -1, .pid = -1 };
|
|
1238
|
+
try std.testing.expect(!resolved_pty.lateExecFailure());
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
test "an exec failure is reported, not masqueraded as a normal exit" {
|
|
1242
|
+
if (comptime !posix_supported) return;
|
|
1243
|
+
// A directory passes the X_OK (searchable) check but execve refuses
|
|
1244
|
+
// it — the exec self-pipe turns that into PtyCommandNotFound rather
|
|
1245
|
+
// than a forked child that exits 127 on its own.
|
|
1246
|
+
try std.testing.expectError(error.PtyCommandNotFound, spawn(std.testing.allocator, .{ .argv = &.{"/"} }));
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
test "embedded NUL in argv is rejected, never truncated" {
|
|
1250
|
+
if (comptime !posix_supported) return;
|
|
1251
|
+
try std.testing.expectError(error.PtyArgvInvalid, spawn(std.testing.allocator, .{ .argv = &.{ "/bin/echo", "abc\x00def" } }));
|
|
1252
|
+
}
|