Skip to main content

kh_runtime/
host.rs

1//! Host OS primitives: the **only** crate-level home for most libc I/O and
2//! memory syscalls used by the translator.
3//!
4//! Call sites should prefer these wrappers so `unsafe` does not scatter across
5//! BSD handlers. Each function documents the ownership / validity contract.
6#![allow(unsafe_code)]
7
8use std::io;
9use std::os::fd::RawFd;
10use std::ptr;
11
12/// Linux `MAP_FIXED_NOREPLACE` (do not clobber existing maps).
13#[cfg(target_os = "linux")]
14pub const MAP_FIXED_NOREPLACE: libc::c_int = 0x100_000;
15
16/// Preferred fixed-map flag for this host.
17#[must_use]
18pub fn fixed_map_flag() -> libc::c_int {
19    #[cfg(target_os = "linux")]
20    {
21        MAP_FIXED_NOREPLACE
22    }
23    #[cfg(not(target_os = "linux"))]
24    {
25        libc::MAP_FIXED
26    }
27}
28
29/// Host page size in bytes, or `None` if `sysconf` fails.
30#[must_use]
31pub fn page_size() -> Option<usize> {
32    // SAFETY: `sysconf(_SC_PAGESIZE)` returns a scalar; no memory is touched.
33    let raw = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
34    if raw <= 0 {
35        return None;
36    }
37    usize::try_from(raw).ok()
38}
39
40/// Physical page count from `sysconf(_SC_PHYS_PAGES)`, when available.
41#[must_use]
42pub fn phys_pages() -> Option<u64> {
43    // SAFETY: scalar sysconf; no memory is touched.
44    let raw = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
45    if raw <= 0 {
46        return None;
47    }
48    u64::try_from(raw).ok()
49}
50
51/// Best-effort host RAM size in bytes.
52#[must_use]
53pub fn phys_mem_bytes() -> u64 {
54    match (phys_pages(), page_size()) {
55        (Some(pages), Some(page)) => {
56            let s = u64::try_from(page).unwrap_or(0);
57            pages.saturating_mul(s).max(64 * 1024 * 1024)
58        }
59        _ => 8 * 1024 * 1024 * 1024, // 8 GiB fallback
60    }
61}
62
63/// Close a host file descriptor. Errors are ignored (best-effort cleanup).
64pub fn close_fd(fd: RawFd) {
65    // SAFETY: caller owned `fd` and will not use it after this call.
66    unsafe {
67        let _ = libc::close(fd);
68    }
69}
70
71/// Duplicate a host fd. Returns the new fd or `None` on failure.
72#[must_use]
73pub fn dup_fd(fd: RawFd) -> Option<RawFd> {
74    // SAFETY: `fd` is a live host descriptor.
75    let rc = unsafe { libc::dup(fd) };
76    if rc < 0 { None } else { Some(rc) }
77}
78
79/// `dup2(old, new)` on the host. Returns `new` or `None` on failure.
80#[must_use]
81pub fn dup2_fd(old: RawFd, new: RawFd) -> Option<RawFd> {
82    // SAFETY: both fds are valid host descriptors for the duration of the call.
83    let rc = unsafe { libc::dup2(old, new) };
84    if rc < 0 { None } else { Some(rc) }
85}
86
87/// Host `fork`. Returns `Ok(pid)` where pid is 0 in the child, or `Err(errno)`.
88pub fn fork_process() -> Result<i32, i32> {
89    // SAFETY: Linux fork; only the calling thread is duplicated.
90    let rc = unsafe { libc::fork() };
91    if rc < 0 {
92        Err(last_errno())
93    } else {
94        Ok(rc)
95    }
96}
97
98/// Host `waitpid`. Returns `(pid, status)` or `Err(errno)`. `pid == 0` with
99/// `WNOHANG` means no child ready.
100pub fn wait_pid(pid: i32, options: i32) -> Result<(i32, i32), i32> {
101    let mut status: libc::c_int = 0;
102    // SAFETY: status is stack-local; waitpid is well-defined.
103    let rc = unsafe { libc::waitpid(pid, &raw mut status, options) };
104    if rc < 0 {
105        Err(last_errno())
106    } else {
107        Ok((rc, status))
108    }
109}
110
111/// Host `execve` with owned C strings (never returns on success).
112///
113/// # Safety
114///
115/// `argv` and `envp` must be NULL-terminated arrays of valid C strings; this
116/// process image is replaced on success.
117pub unsafe fn execve_host(
118    path: &std::ffi::CStr,
119    argv: &[*const libc::c_char],
120    envp: &[*const libc::c_char],
121) -> i32 {
122    // SAFETY: caller guarantees NUL-terminated argv/envp; path is a CStr.
123    let rc = unsafe { libc::execve(path.as_ptr(), argv.as_ptr().cast(), envp.as_ptr().cast()) };
124    let _ = rc;
125    last_errno()
126}
127
128fn last_errno() -> i32 {
129    io::Error::last_os_error()
130        .raw_os_error()
131        .unwrap_or(libc::EIO)
132}
133
134fn socklen_of(len: usize) -> Option<libc::socklen_t> {
135    libc::socklen_t::try_from(len).ok()
136}
137
138/// `pipe(2)` — returns `(read_fd, write_fd)` or `None` on failure.
139///
140/// Both ends are set `O_NONBLOCK|O_CLOEXEC`. Freestanding curl/c-ares often
141/// `poll` then `read` the wakeup pipe; a **blocking** host pipe deadlocks the
142/// single-threaded guest when nothing is readable yet (tier1 hang).
143///
144/// Darwin default is blocking; guest-visible semantics are tracked in
145/// [`crate::process::fd_guest_nonblock`]. I/O waits on `EAGAIN` until the guest
146/// sets `O_NONBLOCK` via `fcntl`. Nested helpers also call
147/// [`crate::process::normalize_stdio_pipes_blocking`] so inherited command
148/// pipes behave as Darwin blocking stdin/stdout.
149#[must_use]
150pub fn pipe_fds() -> Option<(RawFd, RawFd)> {
151    let mut fds = [0_i32; 2];
152    // Prefer pipe2 when available (Linux).
153    #[cfg(target_os = "linux")]
154    {
155        // SAFETY: stack buffer of two ints for the kernel to fill.
156        let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) };
157        if rc != 0 {
158            return None;
159        }
160    }
161    #[cfg(not(target_os = "linux"))]
162    {
163        // SAFETY: stack buffer of two ints for the kernel to fill.
164        let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
165        if rc != 0 {
166            return None;
167        }
168        for fd in fds {
169            set_nonblock(fd);
170            // SAFETY: freshly created pipe ends.
171            unsafe {
172                let _ = libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
173            }
174        }
175    }
176    match (fds.first().copied(), fds.get(1).copied()) {
177        (Some(r), Some(w)) => Some((r, w)),
178        _ => None,
179    }
180}
181
182/// Block until `fd` is readable, hung-up, or errored. `timeout_ms` as in
183/// `poll(2)` (`-1` = forever). Returns `true` if any interesting revent.
184#[must_use]
185pub fn poll_fd_readable(fd: RawFd, timeout_ms: i32) -> bool {
186    poll_fd(fd, libc::POLLIN, timeout_ms)
187}
188
189/// Block until `fd` is writable, hung-up, or errored.
190#[must_use]
191pub fn poll_fd_writable(fd: RawFd, timeout_ms: i32) -> bool {
192    poll_fd(fd, libc::POLLOUT, timeout_ms)
193}
194
195/// Block until `fd` is readable **or** writable (TLS may need both).
196#[must_use]
197pub fn poll_fd_io(fd: RawFd, timeout_ms: i32) -> bool {
198    poll_fd(fd, libc::POLLIN | libc::POLLOUT, timeout_ms)
199}
200
201fn poll_fd(fd: RawFd, events: libc::c_short, timeout_ms: i32) -> bool {
202    let mut pfd = libc::pollfd {
203        fd,
204        events,
205        revents: 0,
206    };
207    loop {
208        // SAFETY: single pollfd on the stack; fd is a live host descriptor.
209        let rc = unsafe { libc::poll(&raw mut pfd, 1, timeout_ms) };
210        if rc < 0 {
211            let err = io::Error::last_os_error()
212                .raw_os_error()
213                .unwrap_or(0);
214            if err == libc::EINTR {
215                continue;
216            }
217            return false;
218        }
219        if rc == 0 {
220            return false;
221        }
222        let interest = events | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL;
223        return pfd.revents & interest != 0;
224    }
225}
226
227/// Mark a host fd non-blocking (best-effort).
228fn set_nonblock(fd: RawFd) {
229    // SAFETY: live fd from socket/accept/pipe.
230    unsafe {
231        let fl = libc::fcntl(fd, libc::F_GETFL);
232        if fl >= 0 {
233            let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
234        }
235    }
236}
237
238/// Clear host `O_NONBLOCK` (best-effort). Used for nested-helper stdio pipes.
239pub fn clear_nonblock(fd: RawFd) {
240    // SAFETY: live fd.
241    unsafe {
242        let fl = libc::fcntl(fd, libc::F_GETFL);
243        if fl >= 0 {
244            let _ = libc::fcntl(fd, libc::F_SETFL, fl & !libc::O_NONBLOCK);
245        }
246    }
247}
248
249/// `true` when `fd` is a FIFO/pipe (`S_IFIFO`).
250#[must_use]
251pub fn fd_is_fifo(fd: RawFd) -> bool {
252    // SAFETY: fstat on a live fd.
253    unsafe {
254        let mut st: libc::stat = core::mem::zeroed();
255        if libc::fstat(fd, &raw mut st) != 0 {
256            return false;
257        }
258        (st.st_mode & libc::S_IFMT) == libc::S_IFIFO
259    }
260}
261
262/// `socket(domain, type, protocol)` — host libc. Returns host fd or `None`.
263///
264/// Sockets are forced `O_NONBLOCK`. Curl/c-ares (and the multi interface)
265/// expect non-blocking I/O; a blocking `recv` on a keep-alive TCP socket after
266/// the response body is complete hangs the guest forever (clean-exit G3).
267#[must_use]
268pub fn socket(domain: libc::c_int, ty: libc::c_int, protocol: libc::c_int) -> Option<RawFd> {
269    // SAFETY: standard socket(2). Strip Darwin-only type flags if any sneak in;
270    // Linux SOCK_NONBLOCK/CLOEXEC bits differ and are applied via fcntl below.
271    let ty_plain = ty & 0xf;
272    let rc = unsafe { libc::socket(domain, ty_plain, protocol) };
273    if rc < 0 {
274        return None;
275    }
276    set_nonblock(rc);
277    // SAFETY: freshly created socket.
278    unsafe {
279        let _ = libc::fcntl(rc, libc::F_SETFD, libc::FD_CLOEXEC);
280    }
281    Some(rc)
282}
283
284/// `socketpair(domain, type, protocol, sv[2])`.
285pub fn socketpair(
286    domain: libc::c_int,
287    ty: libc::c_int,
288    protocol: libc::c_int,
289) -> Option<(RawFd, RawFd)> {
290    let mut sv = [0_i32; 2];
291    let ty_plain = ty & 0xf;
292    // SAFETY: stack pair for the kernel to fill.
293    let rc = unsafe { libc::socketpair(domain, ty_plain, protocol, sv.as_mut_ptr()) };
294    if rc != 0 {
295        return None;
296    }
297    set_nonblock(sv[0]);
298    set_nonblock(sv[1]);
299    // SAFETY: freshly created sockets.
300    unsafe {
301        let _ = libc::fcntl(sv[0], libc::F_SETFD, libc::FD_CLOEXEC);
302        let _ = libc::fcntl(sv[1], libc::F_SETFD, libc::FD_CLOEXEC);
303    }
304    Some((sv[0], sv[1]))
305}
306
307/// `connect(fd, sockaddr_bytes)`.
308pub fn connect(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
309    let Some(len) = socklen_of(addr.len()) else {
310        return Err(libc::EINVAL);
311    };
312    // SAFETY: `addr` is a valid host buffer for `len` bytes.
313    let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), len) };
314    if rc == 0 { Ok(()) } else { Err(last_errno()) }
315}
316
317/// `bind(fd, sockaddr_bytes)`.
318pub fn bind(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
319    let Some(len) = socklen_of(addr.len()) else {
320        return Err(libc::EINVAL);
321    };
322    // SAFETY: `addr` is a valid host buffer for `len` bytes.
323    let rc = unsafe { libc::bind(fd, addr.as_ptr().cast(), len) };
324    if rc == 0 { Ok(()) } else { Err(last_errno()) }
325}
326
327/// `listen(fd, backlog)`.
328pub fn listen(fd: RawFd, backlog: libc::c_int) -> Result<(), i32> {
329    // SAFETY: live socket fd.
330    let rc = unsafe { libc::listen(fd, backlog) };
331    if rc == 0 { Ok(()) } else { Err(last_errno()) }
332}
333
334/// `accept(fd)` — peer address discarded (curl client path rarely needs it).
335pub fn accept(fd: RawFd) -> Result<RawFd, i32> {
336    // SAFETY: live listening socket; null addr is allowed by accept(2).
337    let rc = unsafe { libc::accept(fd, ptr::null_mut(), ptr::null_mut()) };
338    if rc < 0 {
339        Err(last_errno())
340    } else {
341        set_nonblock(rc);
342        Ok(rc)
343    }
344}
345
346/// `accept` with peer sockaddr written into `addr_out` (truncated to buffer len).
347///
348/// Returns `(new_fd, bytes_written_into_addr_out)`.
349pub fn accept_addr(fd: RawFd, addr_out: &mut [u8]) -> Result<(RawFd, usize), i32> {
350    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
351    // SAFETY: live socket; `addr_out` is writable for `alen` bytes.
352    let rc = unsafe {
353        libc::accept(
354            fd,
355            addr_out.as_mut_ptr().cast(),
356            ptr::addr_of_mut!(alen),
357        )
358    };
359    if rc < 0 {
360        return Err(last_errno());
361    }
362    set_nonblock(rc);
363    let n = usize::try_from(alen).unwrap_or(0).min(addr_out.len());
364    Ok((rc, n))
365}
366
367/// `setsockopt(fd, level, optname, value_bytes)`.
368pub fn setsockopt(
369    fd: RawFd,
370    level: libc::c_int,
371    optname: libc::c_int,
372    value: &[u8],
373) -> Result<(), i32> {
374    let Some(len) = socklen_of(value.len()) else {
375        return Err(libc::EINVAL);
376    };
377    // SAFETY: live socket; value buffer valid for `len` bytes.
378    let rc = unsafe {
379        libc::setsockopt(
380            fd,
381            level,
382            optname,
383            value.as_ptr().cast(),
384            len,
385        )
386    };
387    if rc == 0 { Ok(()) } else { Err(last_errno()) }
388}
389
390/// `getsockopt` — writes into `value`, returns updated length.
391pub fn getsockopt(
392    fd: RawFd,
393    level: libc::c_int,
394    optname: libc::c_int,
395    value: &mut [u8],
396) -> Result<usize, i32> {
397    let mut len = socklen_of(value.len()).unwrap_or(0);
398    // SAFETY: live socket; value buffer writable.
399    let rc = unsafe {
400        libc::getsockopt(
401            fd,
402            level,
403            optname,
404            value.as_mut_ptr().cast(),
405            ptr::addr_of_mut!(len),
406        )
407    };
408    if rc == 0 {
409        Ok(usize::try_from(len).unwrap_or(0).min(value.len()))
410    } else {
411        Err(last_errno())
412    }
413}
414
415/// `shutdown(fd, how)`.
416pub fn shutdown(fd: RawFd, how: libc::c_int) -> Result<(), i32> {
417    // SAFETY: live socket fd.
418    let rc = unsafe { libc::shutdown(fd, how) };
419    if rc == 0 { Ok(()) } else { Err(last_errno()) }
420}
421
422/// `sendto` / `send` — optional peer address bytes.
423pub fn sendto(
424    fd: RawFd,
425    buf: &[u8],
426    flags: libc::c_int,
427    addr: Option<&[u8]>,
428) -> Result<usize, i32> {
429    let (ap, alen) = if let Some(a) = addr {
430        let Some(len) = socklen_of(a.len()) else {
431            return Err(libc::EINVAL);
432        };
433        (a.as_ptr().cast(), len)
434    } else {
435        (ptr::null(), 0)
436    };
437    // SAFETY: live fd; buffer valid; optional sockaddr.
438    let n = unsafe { libc::sendto(fd, buf.as_ptr().cast(), buf.len(), flags, ap, alen) };
439    if n < 0 {
440        Err(last_errno())
441    } else {
442        usize::try_from(n).map_err(|_| libc::EIO)
443    }
444}
445
446/// `recvfrom` / `recv` — optional peer address out-buffer.
447///
448/// Returns `(bytes_read, peer_addr_len)` when `addr_out` is `Some`.
449pub fn recvfrom(
450    fd: RawFd,
451    buf: &mut [u8],
452    flags: libc::c_int,
453    addr_out: Option<&mut [u8]>,
454) -> Result<(usize, usize), i32> {
455    let (n, peer_len) = if let Some(a) = addr_out {
456        let mut alen = socklen_of(a.len()).unwrap_or(0);
457        // SAFETY: live fd; buffers valid.
458        let n = unsafe {
459            libc::recvfrom(
460                fd,
461                buf.as_mut_ptr().cast(),
462                buf.len(),
463                flags,
464                a.as_mut_ptr().cast(),
465                ptr::addr_of_mut!(alen),
466            )
467        };
468        (n, usize::try_from(alen).unwrap_or(0).min(a.len()))
469    } else {
470        // SAFETY: live fd; buffer valid; null peer.
471        let n = unsafe {
472            libc::recvfrom(
473                fd,
474                buf.as_mut_ptr().cast(),
475                buf.len(),
476                flags,
477                ptr::null_mut(),
478                ptr::null_mut(),
479            )
480        };
481        (n, 0)
482    };
483    if n < 0 {
484        Err(last_errno())
485    } else {
486        let nr = usize::try_from(n).map_err(|_| libc::EIO)?;
487        Ok((nr, peer_len))
488    }
489}
490
491/// `getsockname(fd, addr_out)`.
492pub fn getsockname(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
493    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
494    // SAFETY: live socket; buffer writable for `alen` bytes.
495    let rc = unsafe {
496        libc::getsockname(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
497    };
498    if rc == 0 {
499        Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
500    } else {
501        Err(last_errno())
502    }
503}
504
505/// `getpeername(fd, addr_out)`.
506pub fn getpeername(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
507    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
508    // SAFETY: live socket; buffer writable for `alen` bytes.
509    let rc = unsafe {
510        libc::getpeername(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
511    };
512    if rc == 0 {
513        Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
514    } else {
515        Err(last_errno())
516    }
517}
518
519/// `poll(fds, timeout_ms)` — empty slice sleeps / checks timeout only.
520pub fn poll(fds: &mut [libc::pollfd], timeout: libc::c_int) -> Result<i32, i32> {
521    let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
522    // SAFETY: `fds` is a valid pollfd array of `nfds` entries (or empty).
523    let rc = unsafe {
524        libc::poll(
525            if fds.is_empty() {
526                ptr::null_mut()
527            } else {
528                fds.as_mut_ptr()
529            },
530            nfds,
531            timeout,
532        )
533    };
534    if rc < 0 { Err(last_errno()) } else { Ok(rc) }
535}
536
537/// `lseek` on a host fd.
538pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
539    // SAFETY: live fd; whence is a SEEK_* constant.
540    let rc = unsafe { libc::lseek(fd, offset, whence) };
541    if rc < 0 { None } else { Some(rc) }
542}
543
544/// `fcntl` with no extra arg (`F_GETFD` / `F_GETFL`).
545pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
546    // SAFETY: live fd; cmd is a valid fcntl command.
547    let rc = unsafe { libc::fcntl(fd, cmd) };
548    if rc < 0 { None } else { Some(rc) }
549}
550
551/// `fcntl` with one integer arg (`F_SETFD` / `F_SETFL` / `F_DUPFD`).
552pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
553    // SAFETY: live fd; cmd/arg match the fcntl ABI.
554    let rc = unsafe { libc::fcntl(fd, cmd, arg) };
555    if rc < 0 { None } else { Some(rc) }
556}
557
558/// `open(path, flags, mode)` — prefers libc over `std::fs::OpenOptions` so
559/// directories open with `O_RDONLY` (archive walks) and we avoid extra syscalls.
560pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
561    // SAFETY: path is a valid C string for the duration of the call.
562    let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
563    if rc < 0 { None } else { Some(rc) }
564}
565
566/// Open a directory as `O_RDONLY|O_DIRECTORY|O_CLOEXEC` (bottle root dirfd, B1).
567pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
568    open_path(
569        path,
570        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
571        0,
572    )
573}
574
575/// `openat(dirfd, path, flags, mode)`.
576pub fn openat(
577    dirfd: RawFd,
578    path: &std::ffi::CStr,
579    flags: libc::c_int,
580    mode: libc::c_uint,
581) -> Option<RawFd> {
582    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
583    let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
584    if rc < 0 { None } else { Some(rc) }
585}
586
587/// `mkdirat(dirfd, path, mode)` — returns `Ok(())` on success or `EEXIST`.
588pub fn mkdirat(dirfd: RawFd, path: &std::ffi::CStr, mode: libc::mode_t) -> io::Result<()> {
589    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
590    let rc = unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) };
591    if rc == 0 {
592        return Ok(());
593    }
594    let err = io::Error::last_os_error();
595    if err.raw_os_error() == Some(libc::EEXIST) {
596        Ok(())
597    } else {
598        Err(err)
599    }
600}
601
602/// `fstatat(dirfd, path, …)` — used by B1 bottle-relative `stat`/`lstat`.
603pub fn fstatat(dirfd: RawFd, path: &std::ffi::CStr, no_follow: bool) -> Option<libc::stat> {
604    let mut st: libc::stat = unsafe { std::mem::zeroed() };
605    let flags = if no_follow {
606        libc::AT_SYMLINK_NOFOLLOW
607    } else {
608        0
609    };
610    // SAFETY: dirfd live; path valid C string; stack `stat` buffer.
611    let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
612    if rc == 0 { Some(st) } else { None }
613}
614
615/// `faccessat(dirfd, path, F_OK, 0)` — existence check without full path build.
616pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
617    // SAFETY: dirfd live; path valid C string.
618    let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
619    rc == 0
620}
621
622/// Write bytes to a host fd (`write(2)`).
623pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
624    if data.is_empty() {
625        return Ok(0);
626    }
627    // SAFETY: fd live; buffer valid for `data.len()` bytes.
628    let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
629    if n < 0 {
630        return Err(io::Error::last_os_error());
631    }
632    usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
633}
634
635/// Read bytes from a host fd (`read(2)`).
636pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
637    if buf.is_empty() {
638        return Ok(0);
639    }
640    // SAFETY: fd live; buffer valid for `buf.len()` bytes.
641    let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
642    if n < 0 {
643        return Err(io::Error::last_os_error());
644    }
645    usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
646}
647
648/// `fstat` into a host `stat` buffer.
649pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
650    // SAFETY: live fd; stack buffer is valid for the duration of the call.
651    let mut st: libc::stat = unsafe { std::mem::zeroed() };
652    let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
653    if rc == 0 { Some(st) } else { None }
654}
655
656/// `ftruncate(fd, length)`.
657pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
658    // SAFETY: live fd.
659    let rc = unsafe { libc::ftruncate(fd, length) };
660    if rc == 0 { Some(()) } else { None }
661}
662
663/// `fsync(fd)`.
664pub fn fsync_fd(fd: RawFd) -> Option<()> {
665    // SAFETY: live fd.
666    let rc = unsafe { libc::fsync(fd) };
667    if rc == 0 { Some(()) } else { None }
668}
669
670/// `readlink(path)` into `buf` (no trailing NUL). Returns bytes written or host errno.
671pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
672    if buf.is_empty() {
673        return Ok(0);
674    }
675    // SAFETY: path is a valid C string; buffer is writable for `buf.len()`.
676    let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
677    if n < 0 {
678        return Err(io::Error::last_os_error()
679            .raw_os_error()
680            .unwrap_or(libc::EIO));
681    }
682    usize::try_from(n).map_err(|_| libc::EIO)
683}
684
685/// `symlink(target, linkpath)`.
686pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
687    // SAFETY: both are valid C strings for the duration of the call.
688    let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
689    if rc == 0 {
690        Ok(())
691    } else {
692        Err(io::Error::last_os_error()
693            .raw_os_error()
694            .unwrap_or(libc::EIO))
695    }
696}
697
698/// `link(existing, newpath)` hard link.
699pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
700    // SAFETY: both are valid C strings for the duration of the call.
701    let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
702    if rc == 0 {
703        Ok(())
704    } else {
705        Err(io::Error::last_os_error()
706            .raw_os_error()
707            .unwrap_or(libc::EIO))
708    }
709}
710
711/// Host `gettimeofday` (timezone ignored).
712pub fn gettimeofday() -> Option<libc::timeval> {
713    // SAFETY: stack timeval; null tz pointer is allowed.
714    let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
715    let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
716    if rc == 0 { Some(tv) } else { None }
717}
718
719/// Host `clock_gettime`.
720pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
721    // SAFETY: stack timespec; clock_id is a host constant.
722    let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
723    let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
724    if rc == 0 { Some(ts) } else { None }
725}
726
727/// Anonymous or file-backed `mmap`. Returns host base or `None` on failure.
728///
729/// When `fixed_addr` is `Some(va)`, the call uses that as the address hint
730/// (combine with [`fixed_map_flag`] / `MAP_FIXED` as appropriate).
731#[must_use]
732pub fn mmap(
733    fixed_addr: Option<u64>,
734    len: usize,
735    prot: libc::c_int,
736    flags: libc::c_int,
737    fd: RawFd,
738    offset: i64,
739) -> Option<*mut u8> {
740    if len == 0 {
741        return None;
742    }
743    let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
744    // SAFETY: length non-zero; flags/prot valid combinations; fd matches flags;
745    // `addr` is either null or a page-aligned VA for fixed placement.
746    let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
747    if raw == libc::MAP_FAILED {
748        None
749    } else {
750        Some(raw.cast())
751    }
752}
753
754/// `munmap` a mapping previously returned by [`mmap`].
755pub fn munmap(ptr: *mut u8, len: usize) -> bool {
756    if ptr.is_null() || len == 0 {
757        return true;
758    }
759    // SAFETY: ptr/len came from a successful mmap owned by the caller.
760    let rc = unsafe { libc::munmap(ptr.cast(), len) };
761    rc == 0
762}
763
764/// `mprotect` on a host mapping range.
765pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
766    if ptr.is_null() || len == 0 {
767        return true;
768    }
769    // SAFETY: range is a live mapping owned by the caller.
770    let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
771    rc == 0
772}
773
774/// `msync` on a host mapping range.
775pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
776    if ptr.is_null() || len == 0 {
777        return true;
778    }
779    // SAFETY: range is a live mapping; flags are MS_* bits.
780    let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
781    rc == 0
782}
783
784/// Pointer address as `u64` (identity guest/host model helpers).
785#[must_use]
786pub fn ptr_addr_u64(p: *mut u8) -> u64 {
787    u64::try_from(p.addr()).unwrap_or(0)
788}
789
790/// `u64` address → void pointer (fixed mmap hints).
791#[must_use]
792pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
793    let u = usize::try_from(addr).unwrap_or(0);
794    ptr::with_exposed_provenance_mut::<u8>(u).cast()
795}
796
797// ── directory streams (for guest readdir) ───────────────────────────────────
798
799/// Opaque host directory stream (`DIR*`).
800#[derive(Debug)]
801pub struct HostDir {
802    ptr: *mut libc::DIR,
803}
804
805// SAFETY: process-wide guest model serializes dir mutation under ProcessState
806// write lock; readers never touch `HostDir`.
807unsafe impl Send for HostDir {}
808// SAFETY: same as `Send` — exclusive dir use under write lock only.
809unsafe impl Sync for HostDir {}
810
811impl HostDir {
812    /// Open a directory stream on a **duplicate** of `host_fd` (does not own `host_fd`).
813    pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
814        // SAFETY: dup of a live host FD.
815        let dup = unsafe { libc::dup(host_fd) };
816        if dup < 0 {
817            return Err(last_errno_i32());
818        }
819        // SAFETY: fdopendir takes ownership of `dup`.
820        let dir = unsafe { libc::fdopendir(dup) };
821        if dir.is_null() {
822            let err = last_errno_i32();
823            // SAFETY: close the unused dup on failure.
824            unsafe {
825                libc::close(dup);
826            }
827            return Err(err);
828        }
829        Ok(Self { ptr: dir })
830    }
831
832    /// Next entry: `(name_bytes, d_type)`. `None` at end of stream.
833    pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
834        use std::ffi::CStr;
835        loop {
836            // SAFETY: `ptr` from fdopendir; readdir is the iterator.
837            let ent = unsafe { libc::readdir(self.ptr) };
838            if ent.is_null() {
839                return None;
840            }
841            // SAFETY: ent valid until next readdir/closedir.
842            let d_type = unsafe { (*ent).d_type };
843            let name_ptr = unsafe { (*ent).d_name.as_ptr() };
844            let name = unsafe { CStr::from_ptr(name_ptr) };
845            let bytes = name.to_bytes().to_vec();
846            if bytes.is_empty() {
847                continue;
848            }
849            return Some((bytes, d_type));
850        }
851    }
852}
853
854impl Drop for HostDir {
855    fn drop(&mut self) {
856        if !self.ptr.is_null() {
857            // SAFETY: owns DIR* from fdopendir.
858            unsafe {
859                let _ = libc::closedir(self.ptr);
860            }
861            self.ptr = ptr::null_mut();
862        }
863    }
864}
865
866fn last_errno_i32() -> i32 {
867    let raw = io::Error::last_os_error()
868        .raw_os_error()
869        .unwrap_or(1)
870        .unsigned_abs();
871    i32::try_from(raw).unwrap_or(1)
872}