Skip to main content

kh_runtime/
process.rs

1//! Process-wide translator state for the single guest-process model.
2//!
3//! Hot paths avoid the process [`RwLock`]:
4//! - FD map: lock-free atomics ([`fd_get`] / [`fd_alloc`] / [`fd_take`])
5//! - bottle root: narrow [`Arc`] slot ([`with_bottle_root`])
6//! - `bsdthread_register`: atomic pointer snapshot ([`bsdthread_reg`])
7//!
8//! Soft signals and directory streams still use [`with_mut`] / [`with_ref`].
9
10use std::collections::HashMap;
11use std::os::fd::RawFd;
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicI32, AtomicU8, AtomicU64, Ordering};
14use std::sync::{Arc, OnceLock, RwLock};
15
16use crate::host;
17
18/// Process-wide syscall counter (hot path: no process-state lock).
19static SYSCALL_COUNT: AtomicU64 = AtomicU64::new(0);
20/// Cap for [`SYSCALL_COUNT`]; updated by [`reset_run`].
21static MAX_SYSCALLS: AtomicU64 = AtomicU64::new(256);
22
23/// Unreaped host children from guest `fork` (parent side only).
24///
25/// Secondary signal for blocking I/O waits; primary control is
26/// [`fd_guest_nonblock`] (guest `O_NONBLOCK` flag).
27static LIVE_CHILDREN: AtomicU64 = AtomicU64::new(0);
28
29/// Max guest FD slots (stdio 0–2 + table). Keeps FDs under typical OPEN_MAX.
30const FD_SLOTS: usize = 1024;
31/// Empty slot in the lock-free FD map.
32const FD_EMPTY: i32 = -1;
33
34/// Guest → host FD map for **lookup** without the process `RwLock`.
35///
36/// Slots 0–2 are unused (stdio identity). Other slots: host fd ≥ 0, or [`FD_EMPTY`].
37/// Alloc/take update these atomics; dir streams still use the process lock.
38static FD_HOST: [AtomicI32; FD_SLOTS] = [const { AtomicI32::new(FD_EMPTY) }; FD_SLOTS];
39/// Guest-visible `O_NONBLOCK` per FD slot (including stdio 0–2).
40///
41/// Host pipes/sockets are often forced non-blocking for curl multi; Darwin
42/// guests still expect **blocking** semantics until they `fcntl(F_SETFL)`.
43/// I/O emulates blocking waits when this bit is clear.
44static FD_GUEST_NB: [AtomicU8; FD_SLOTS] = [const { AtomicU8::new(0) }; FD_SLOTS];
45/// Guest FD has a host-side TLS session ([`crate::tls_fd`]).
46///
47/// Lock-free hot-path check so ordinary `read`/`write` skip the TLS HashMap.
48static FD_TLS: [AtomicU8; FD_SLOTS] = [const { AtomicU8::new(0) }; FD_SLOTS];
49/// Hint for next free FD scan.
50static FD_NEXT: AtomicI32 = AtomicI32::new(3);
51/// Guest path string for each allocated FD (for `fcntl(F_GETPATH)` after
52/// fat-thin replaces the host FD with a memfd / unlinked temp).
53static FD_GUEST_PATH: RwLock<Option<HashMap<i32, String>>> = RwLock::new(None);
54/// Guest has `close`'d stdio slots 0/1/2 (bit0=stdin, bit1=stdout, bit2=stderr).
55///
56/// Stdio is identity-mapped to host 0/1/2, so a soft no-op `close` left the host
57/// pipe open. Apple `git fetch-pack --stateless-rpc` closes stdout **before**
58/// printing the fetched-ref list; with a no-op close those lines reach the
59/// remote-curl helper and surface as hundreds of
60/// `https unexpectedly said: '<sha> refs/…'` warnings after a successful clone.
61static STDIO_CLOSED: AtomicU8 = AtomicU8::new(0);
62
63/// Soft Darwin `sigaction` slot (handler + mask + flags).
64#[derive(Clone, Copy, Debug)]
65pub(crate) struct SoftSigAct {
66    pub handler: u64,
67    pub mask: u32,
68    pub flags: i32,
69}
70
71/// Values from Darwin `bsdthread_register` (libpthread start trampoline, etc.).
72///
73/// Extra fields are retained for future workq/TLS wiring even when unused today.
74#[derive(Clone, Copy, Debug, Default)]
75#[allow(dead_code)]
76pub(crate) struct BsdThreadReg {
77    /// Userland start trampoline (`_pthread_start`).
78    pub threadstart: u64,
79    /// Workqueue thread entry (unused in micro; stored for completeness).
80    pub wqthread: u64,
81    /// Registration flags from libpthread.
82    pub flags: u32,
83    /// Stack address hint (unused in micro).
84    pub stack_addr_hint: u64,
85    /// TSD offset within the pthread structure.
86    pub tsd_offset: u32,
87    /// Dispatch queue offset within the pthread structure.
88    pub dispatchqueue_offset: u32,
89}
90
91impl SoftSigAct {
92    pub(crate) const fn zero() -> Self {
93        Self {
94            handler: 0,
95            mask: 0,
96            flags: 0,
97        }
98    }
99}
100
101/// Marker so `ProcessState::reset_run` can clear the lock-free FD map.
102#[derive(Debug, Default)]
103struct FdTable;
104
105impl FdTable {
106    const fn new() -> Self {
107        Self
108    }
109
110    fn reset(&mut self) {
111        let _ = self;
112        reset_fd_map();
113    }
114}
115
116/// Resolve guest FD → host FD without taking the process lock (I/O hot path).
117#[must_use]
118#[inline]
119pub fn fd_get(gfd: i32) -> Option<RawFd> {
120    if gfd == 0 || gfd == 1 || gfd == 2 {
121        if stdio_is_closed(gfd) {
122            return None;
123        }
124        return Some(gfd);
125    }
126    if gfd < 0 {
127        return None;
128    }
129    let Ok(idx) = usize::try_from(gfd) else {
130        return None;
131    };
132    let slot = FD_HOST.get(idx)?;
133    let v = slot.load(Ordering::Acquire);
134    if v < 0 { None } else { Some(v) }
135}
136
137/// Removes a guest FD mapping and returns the host fd (lock-free).
138///
139/// For stdio 0–2: marks the slot closed and returns the host fd (identity) so
140/// the caller can `close` it — matching Darwin when `fetch-pack` drops stdout.
141#[must_use]
142#[inline]
143pub fn fd_take(gfd: i32) -> Option<RawFd> {
144    if gfd == 0 || gfd == 1 || gfd == 2 {
145        if stdio_is_closed(gfd) {
146            return None;
147        }
148        stdio_mark_closed(gfd);
149        return Some(gfd);
150    }
151    if gfd < 0 {
152        return None;
153    }
154    let Ok(idx) = usize::try_from(gfd) else {
155        return None;
156    };
157    let slot = FD_HOST.get(idx)?;
158    let v = slot.swap(FD_EMPTY, Ordering::AcqRel);
159    if let Some(t) = FD_TLS.get(idx) {
160        t.store(0, Ordering::Release);
161    }
162    if let Some(nb) = FD_GUEST_NB.get(idx) {
163        nb.store(0, Ordering::Release);
164    }
165    fd_clear_guest_path(gfd);
166    if v < 0 { None } else { Some(v) }
167}
168
169/// Record the guest path used to open `gfd` (absolute Darwin path).
170pub fn fd_set_guest_path(gfd: i32, path: impl Into<String>) {
171    if gfd < 3 {
172        return;
173    }
174    if let Ok(mut g) = FD_GUEST_PATH.write() {
175        let map = g.get_or_insert_with(HashMap::new);
176        map.insert(gfd, path.into());
177    }
178}
179
180/// Guest path for `gfd`, if recorded at open.
181#[must_use]
182pub fn fd_guest_path(gfd: i32) -> Option<String> {
183    if gfd < 3 {
184        return None;
185    }
186    FD_GUEST_PATH
187        .read()
188        .ok()
189        .and_then(|g| g.as_ref().and_then(|m| m.get(&gfd).cloned()))
190}
191
192fn fd_clear_guest_path(gfd: i32) {
193    if gfd < 3 {
194        return;
195    }
196    if let Ok(mut g) = FD_GUEST_PATH.write()
197        && let Some(map) = g.as_mut()
198    {
199        map.remove(&gfd);
200    }
201}
202
203/// Bit for guest stdio FD in [`STDIO_CLOSED`] (`0→1`, `1→2`, `2→4`).
204#[inline]
205fn stdio_closed_bit(gfd: i32) -> Option<u8> {
206    match gfd {
207        0 => Some(1),
208        1 => Some(2),
209        2 => Some(4),
210        _ => None,
211    }
212}
213
214#[inline]
215fn stdio_is_closed(gfd: i32) -> bool {
216    let Some(bit) = stdio_closed_bit(gfd) else {
217        return false;
218    };
219    STDIO_CLOSED.load(Ordering::Acquire) & bit != 0
220}
221
222#[inline]
223fn stdio_mark_closed(gfd: i32) {
224    let Some(bit) = stdio_closed_bit(gfd) else {
225        return;
226    };
227    STDIO_CLOSED.fetch_or(bit, Ordering::AcqRel);
228}
229
230/// Clear the closed bit for a stdio slot (after successful `dup2` onto 0/1/2).
231#[inline]
232pub fn stdio_mark_open(gfd: i32) {
233    let Some(bit) = stdio_closed_bit(gfd) else {
234        return;
235    };
236    STDIO_CLOSED.fetch_and(!bit, Ordering::AcqRel);
237}
238
239/// Installs `host_fd` into a **specific** guest FD slot (for `dup2`).
240///
241/// Closes any previous host mapping at `gfd` (except stdio 0–2 identity).
242/// Guest nonblock flag is **not** updated — caller should copy from the source.
243/// Returns `false` if `gfd` is out of range.
244#[must_use]
245#[inline]
246pub fn fd_install(gfd: i32, host_fd: RawFd) -> bool {
247    if host_fd < 0 || gfd < 3 {
248        return false;
249    }
250    let Ok(idx) = usize::try_from(gfd) else {
251        return false;
252    };
253    let Some(slot) = FD_HOST.get(idx) else {
254        return false;
255    };
256    let prev = slot.swap(host_fd, Ordering::AcqRel);
257    if prev >= 0 && prev != host_fd {
258        host::close_fd(prev);
259    }
260    true
261}
262
263/// Allocates a guest FD slot for `host_fd` (lock-free CAS scan).
264///
265/// New slots start with guest-blocking semantics (`O_NONBLOCK` clear). Call
266/// [`fd_set_guest_nonblock`] for sockets / after `fcntl(F_SETFL)`.
267#[must_use]
268#[inline]
269pub fn fd_alloc(host_fd: RawFd) -> Option<i32> {
270    if host_fd < 0 {
271        return None;
272    }
273    let start = usize::try_from(FD_NEXT.load(Ordering::Relaxed).max(3)).unwrap_or(3);
274    for idx in start..FD_SLOTS {
275        if try_claim_slot(idx, host_fd) {
276            let gfd = i32::try_from(idx).ok()?;
277            fd_set_guest_nonblock(gfd, false);
278            FD_NEXT.store(gfd.saturating_add(1), Ordering::Relaxed);
279            return Some(gfd);
280        }
281    }
282    for idx in 3..start.min(FD_SLOTS) {
283        if try_claim_slot(idx, host_fd) {
284            let gfd = i32::try_from(idx).ok()?;
285            fd_set_guest_nonblock(gfd, false);
286            FD_NEXT.store(gfd.saturating_add(1), Ordering::Relaxed);
287            return Some(gfd);
288        }
289    }
290    None
291}
292
293/// Guest-visible `O_NONBLOCK` for `gfd` (stdio or allocated slot).
294#[must_use]
295#[inline]
296pub fn fd_guest_nonblock(gfd: i32) -> bool {
297    if gfd < 0 {
298        return false;
299    }
300    let Ok(idx) = usize::try_from(gfd) else {
301        return false;
302    };
303    FD_GUEST_NB
304        .get(idx)
305        .is_some_and(|s| s.load(Ordering::Acquire) != 0)
306}
307
308/// Sets guest-visible `O_NONBLOCK` for `gfd`.
309#[inline]
310pub fn fd_set_guest_nonblock(gfd: i32, nonblock: bool) {
311    if gfd < 0 {
312        return;
313    }
314    let Ok(idx) = usize::try_from(gfd) else {
315        return;
316    };
317    if let Some(slot) = FD_GUEST_NB.get(idx) {
318        slot.store(u8::from(nonblock), Ordering::Release);
319    }
320}
321
322/// True when `gfd` is a TLS-wrapped guest FD (hot path; no mutex).
323#[must_use]
324#[inline]
325pub fn fd_is_tls(gfd: i32) -> bool {
326    if gfd < 0 {
327        return false;
328    }
329    let Ok(idx) = usize::try_from(gfd) else {
330        return false;
331    };
332    FD_TLS
333        .get(idx)
334        .is_some_and(|s| s.load(Ordering::Acquire) != 0)
335}
336
337/// Mark / clear TLS session association for `gfd` (paired with [`crate::tls_fd`]).
338#[inline]
339pub fn fd_set_tls(gfd: i32, is_tls: bool) {
340    if gfd < 0 {
341        return;
342    }
343    let Ok(idx) = usize::try_from(gfd) else {
344        return;
345    };
346    if let Some(slot) = FD_TLS.get(idx) {
347        slot.store(u8::from(is_tls), Ordering::Release);
348    }
349}
350
351/// Clear host `O_NONBLOCK` on stdio when the fd is a pipe/FIFO.
352///
353/// Nested `kh run` (git helpers after `fork`+re-exec) inherits command pipes as
354/// host 0/1/2. Those pipes are created non-blocking for curl multi; helpers
355/// expect Darwin blocking stdin/stdout. Call once per guest run start.
356pub fn normalize_stdio_pipes_blocking() {
357    for fd in 0_i32..=2 {
358        if host::fd_is_fifo(fd) {
359            host::clear_nonblock(fd);
360            fd_set_guest_nonblock(fd, false);
361        }
362    }
363}
364
365/// Bottle root published for path translation (set once per run; rare updates).
366static BOTTLE_ROOT: RwLock<Option<Arc<PathBuf>>> = RwLock::new(None);
367
368/// Guest absolute path of the main executable (`_NSGetExecutablePath`).
369///
370/// Set at `kh run` / nested re-exec start. Soft-git fallback lived in freestanding
371/// libSystem; clang spawn needs the real binary (not a hard-coded git path).
372static GUEST_EXECUTABLE: RwLock<Option<Arc<str>>> = RwLock::new(None);
373
374/// Open `O_DIRECTORY` fd for the bottle root (`-1` = none).
375///
376/// Hot path: absolute guest paths use `openat`/`fstatat` against this fd
377/// instead of building `{root}/{rel}` PathBuf + `open` from `/` each call (B1).
378static BOTTLE_DIRFD: AtomicI32 = AtomicI32::new(-1);
379
380/// `bsdthread_register` snapshot (narrow lock; not the full process state).
381static BSDTHREAD_REG: RwLock<Option<BsdThreadReg>> = RwLock::new(None);
382
383fn try_claim_slot(idx: usize, host_fd: RawFd) -> bool {
384    let Some(slot) = FD_HOST.get(idx) else {
385        return false;
386    };
387    slot.compare_exchange(FD_EMPTY, host_fd, Ordering::AcqRel, Ordering::Relaxed)
388        .is_ok()
389}
390
391fn reset_fd_map() {
392    for (i, slot) in FD_HOST.iter().enumerate() {
393        let prev = slot.swap(FD_EMPTY, Ordering::AcqRel);
394        if i > 2 && prev >= 0 {
395            host::close_fd(prev);
396        }
397    }
398    for slot in &FD_GUEST_NB {
399        slot.store(0, Ordering::Relaxed);
400    }
401    for slot in &FD_TLS {
402        slot.store(0, Ordering::Relaxed);
403    }
404    if let Ok(mut g) = FD_GUEST_PATH.write() {
405        *g = None;
406    }
407    STDIO_CLOSED.store(0, Ordering::Relaxed);
408    FD_NEXT.store(3, Ordering::Relaxed);
409}
410
411/// Owned process state for one guest (or unit-test isolation via reset).
412///
413/// Bottle root and `bsdthread_register` live in separate process-wide slots so
414/// open/create hot paths do not take this lock.
415#[derive(Debug)]
416pub struct ProcessState {
417    fds: FdTable,
418    /// Guest FD → directory stream (for `readdir` host helper).
419    dir_streams: HashMap<i32, host::HostDir>,
420    sig_mask: u32,
421    sigactions: [SoftSigAct; 32],
422}
423
424impl ProcessState {
425    /// Fresh process state with default syscall limit.
426    #[must_use]
427    pub fn new() -> Self {
428        Self {
429            fds: FdTable::new(),
430            dir_streams: HashMap::new(),
431            sig_mask: 0,
432            sigactions: [SoftSigAct::zero(); 32],
433        }
434    }
435
436    /// Resets FD table, soft signals, thread reg, and counters. Preserves bottle root.
437    pub fn reset_run(&mut self, max_syscalls: usize) {
438        self.dir_streams.clear();
439        self.fds.reset();
440        self.sig_mask = 0;
441        self.sigactions = [SoftSigAct::zero(); 32];
442        clear_bsdthread_reg();
443        let max = u64::try_from(max_syscalls).unwrap_or(256);
444        MAX_SYSCALLS.store(max, Ordering::Relaxed);
445        SYSCALL_COUNT.store(0, Ordering::Relaxed);
446        LIVE_CHILDREN.store(0, Ordering::Relaxed);
447        crate::thread::reset_thread_runtime();
448    }
449
450    /// Closes any directory stream associated with `gfd` (call before FD free).
451    pub(crate) fn close_dir_stream(&mut self, gfd: i32) {
452        drop(self.dir_streams.remove(&gfd));
453    }
454
455    /// Returns the next directory entry for `gfd`, opening a stream on first use.
456    ///
457    /// `None` means end-of-directory (or empty). `Err(errno)` on failure.
458    pub(crate) fn readdir_next(&mut self, gfd: i32) -> Result<Option<(Vec<u8>, u8)>, i64> {
459        let Some(host_fd) = fd_get(gfd) else {
460            return Err(9); // EBADF
461        };
462
463        if let std::collections::hash_map::Entry::Vacant(e) = self.dir_streams.entry(gfd) {
464            match host::HostDir::open_dup(host_fd) {
465                Ok(dir) => {
466                    e.insert(dir);
467                }
468                Err(err) => return Err(i64::from(err)),
469            }
470        }
471
472        let Some(stream) = self.dir_streams.get_mut(&gfd) else {
473            return Err(9);
474        };
475        Ok(stream.read_next())
476    }
477
478    #[must_use]
479    pub(crate) fn sig_mask(&self) -> u32 {
480        self.sig_mask
481    }
482
483    pub(crate) fn set_sig_mask(&mut self, mask: u32) {
484        self.sig_mask = mask;
485    }
486
487    #[must_use]
488    pub(crate) fn sigaction(&self, sig: usize) -> Option<SoftSigAct> {
489        self.sigactions.get(sig).copied()
490    }
491
492    pub(crate) fn set_sigaction(&mut self, sig: usize, act: SoftSigAct) -> bool {
493        if let Some(slot) = self.sigactions.get_mut(sig) {
494            *slot = act;
495            true
496        } else {
497            false
498        }
499    }
500}
501
502impl Default for ProcessState {
503    fn default() -> Self {
504        Self::new()
505    }
506}
507
508/// Parent observed a successful `fork` (child pid > 0).
509#[inline]
510pub fn child_born() {
511    LIVE_CHILDREN.fetch_add(1, Ordering::Relaxed);
512}
513
514/// Parent reaped at least one child via `waitpid`/`wait4`.
515#[inline]
516pub fn child_reaped() {
517    let _ = LIVE_CHILDREN.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| {
518        Some(n.saturating_sub(1))
519    });
520}
521
522/// Number of unreaped host children (approximate; for pipe blocking heuristics).
523#[must_use]
524#[inline]
525pub fn live_children() -> u64 {
526    LIVE_CHILDREN.load(Ordering::Relaxed)
527}
528
529/// Bumps the process-wide syscall counter without taking the process lock.
530///
531/// Returns `true` when the configured max has been exceeded.
532#[must_use]
533pub fn tick_syscall() -> bool {
534    let n = SYSCALL_COUNT.fetch_add(1, Ordering::Relaxed);
535    n >= MAX_SYSCALLS.load(Ordering::Relaxed)
536}
537
538fn active_lock() -> &'static RwLock<ProcessState> {
539    static ACTIVE: OnceLock<RwLock<ProcessState>> = OnceLock::new();
540    ACTIVE.get_or_init(|| RwLock::new(ProcessState::new()))
541}
542
543/// Exclusive access to the active process state.
544pub fn with_mut<R>(f: impl FnOnce(&mut ProcessState) -> R) -> R {
545    match active_lock().write() {
546        Ok(mut guard) => f(&mut guard),
547        Err(poisoned) => f(&mut poisoned.into_inner()),
548    }
549}
550
551/// Shared access to the active process state (concurrent FD lookups, etc.).
552pub fn with_ref<R>(f: impl FnOnce(&ProcessState) -> R) -> R {
553    match active_lock().read() {
554        Ok(guard) => f(&guard),
555        Err(poisoned) => f(&poisoned.into_inner()),
556    }
557}
558
559/// Resets FD/signals/counters for a new guest run (keeps bottle root).
560pub fn reset_run(max_syscalls: usize) {
561    with_mut(|p| p.reset_run(max_syscalls));
562    // Fresh guest process: drop prior dlopen image table.
563    crate::dyld_table::clear();
564    // After re-exec of a Mach-O helper, host 0/1/2 may be O_NONBLOCK pipes
565    // created for curl multi in the parent — restore Darwin blocking stdio.
566    normalize_stdio_pipes_blocking();
567}
568
569/// Configures the bottle root used by path-taking syscalls.
570///
571/// Also opens/replaces the process-wide bottle directory fd for B1 `openat`.
572pub fn set_bottle_root(root: Option<PathBuf>) {
573    let new_fd = root
574        .as_ref()
575        .map_or(-1, |p| open_bottle_dirfd(p).unwrap_or(-1));
576    let old_fd = BOTTLE_DIRFD.swap(new_fd, Ordering::AcqRel);
577    if old_fd >= 0 {
578        host::close_fd(old_fd);
579    }
580
581    let next = root.map(Arc::new);
582    match BOTTLE_ROOT.write() {
583        Ok(mut guard) => {
584            *guard = next;
585        }
586        Err(poisoned) => {
587            *poisoned.into_inner() = next;
588        }
589    }
590}
591
592/// Clone of the configured bottle root, if any.
593#[must_use]
594pub fn bottle_root() -> Option<PathBuf> {
595    with_bottle_root(|p| p.map(Path::to_path_buf))
596}
597
598/// Borrow the bottle root without cloning (hot path for path translation).
599///
600/// Uses a **narrow** bottle-root lock (not the full process state).
601pub fn with_bottle_root<R>(f: impl FnOnce(Option<&Path>) -> R) -> R {
602    match BOTTLE_ROOT.read() {
603        Ok(guard) => f(guard.as_ref().map(|a| a.as_path())),
604        Err(poisoned) => f(poisoned.into_inner().as_ref().map(|a| a.as_path())),
605    }
606}
607
608/// Records the guest-visible main executable path for `_NSGetExecutablePath`.
609pub fn set_guest_executable_path(path: Option<String>) {
610    let next = path.filter(|s| !s.is_empty() && !s.contains('\0')).map(Arc::from);
611    match GUEST_EXECUTABLE.write() {
612        Ok(mut guard) => {
613            *guard = next;
614        }
615        Err(poisoned) => {
616            *poisoned.into_inner() = next;
617        }
618    }
619}
620
621/// Guest absolute executable path, if set for this run.
622#[must_use]
623pub fn guest_executable_path() -> Option<String> {
624    match GUEST_EXECUTABLE.read() {
625        Ok(guard) => guard.as_ref().map(|s| s.as_ref().to_owned()),
626        Err(poisoned) => poisoned
627            .into_inner()
628            .as_ref()
629            .map(|s| s.as_ref().to_owned()),
630    }
631}
632
633/// Process-wide bottle root directory fd for `openat`/`fstatat` (B1).
634///
635/// `None` when no bottle is configured or the directory could not be opened.
636#[must_use]
637pub fn bottle_dirfd() -> Option<RawFd> {
638    let fd = BOTTLE_DIRFD.load(Ordering::Acquire);
639    if fd >= 0 { Some(fd) } else { None }
640}
641
642/// Open `root` as `O_RDONLY|O_DIRECTORY|O_CLOEXEC` for hot-path `openat`.
643fn open_bottle_dirfd(root: &Path) -> Option<RawFd> {
644    let c = std::ffi::CString::new(root.as_os_str().as_encoded_bytes()).ok()?;
645    host::open_directory(&c)
646}
647
648/// Stores `bsdthread_register` metadata for subsequent `bsdthread_create`.
649pub(crate) fn set_bsdthread_reg(reg: BsdThreadReg) {
650    match BSDTHREAD_REG.write() {
651        Ok(mut guard) => {
652            *guard = Some(reg);
653        }
654        Err(poisoned) => {
655            *poisoned.into_inner() = Some(reg);
656        }
657    }
658}
659
660/// Snapshot of the last `bsdthread_register` (narrow lock, copy-out).
661#[must_use]
662pub(crate) fn bsdthread_reg() -> Option<BsdThreadReg> {
663    match BSDTHREAD_REG.read() {
664        Ok(guard) => *guard,
665        Err(poisoned) => *poisoned.into_inner(),
666    }
667}
668
669fn clear_bsdthread_reg() {
670    match BSDTHREAD_REG.write() {
671        Ok(mut guard) => {
672            *guard = None;
673        }
674        Err(poisoned) => {
675            *poisoned.into_inner() = None;
676        }
677    }
678}
679
680/// Serializes tests that mutate process-wide state (address space + process).
681#[cfg(test)]
682pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {
683    use std::sync::Mutex;
684    static LOCK: Mutex<()> = Mutex::new(());
685    LOCK.lock()
686        .unwrap_or_else(std::sync::PoisonError::into_inner)
687}