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 writable yet.
143///
144/// Git’s `start_command` wants a blocking notify-pipe `read` after `fork`.
145/// That is emulated in the `read` syscall: while unreaped children exist, an
146/// `EAGAIN` on a pipe waits for readability (see `io::handle_read`).
147#[must_use]
148pub fn pipe_fds() -> Option<(RawFd, RawFd)> {
149    let mut fds = [0_i32; 2];
150    // Prefer pipe2 when available (Linux).
151    #[cfg(target_os = "linux")]
152    {
153        // SAFETY: stack buffer of two ints for the kernel to fill.
154        let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) };
155        if rc != 0 {
156            return None;
157        }
158    }
159    #[cfg(not(target_os = "linux"))]
160    {
161        // SAFETY: stack buffer of two ints for the kernel to fill.
162        let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
163        if rc != 0 {
164            return None;
165        }
166        for fd in fds {
167            // SAFETY: freshly created pipe ends.
168            unsafe {
169                let fl = libc::fcntl(fd, libc::F_GETFL);
170                if fl >= 0 {
171                    let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
172                }
173                let _ = libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
174            }
175        }
176    }
177    match (fds.first().copied(), fds.get(1).copied()) {
178        (Some(r), Some(w)) => Some((r, w)),
179        _ => None,
180    }
181}
182
183/// Block until `fd` is readable, hung-up, or errored. `timeout_ms` as in
184/// `poll(2)` (`-1` = forever). Returns `true` if any interesting revent.
185#[must_use]
186pub fn poll_fd_readable(fd: RawFd, timeout_ms: i32) -> bool {
187    let mut pfd = libc::pollfd {
188        fd,
189        events: libc::POLLIN,
190        revents: 0,
191    };
192    loop {
193        // SAFETY: single pollfd on the stack; fd is a live host descriptor.
194        let rc = unsafe { libc::poll(&raw mut pfd, 1, timeout_ms) };
195        if rc < 0 {
196            let err = io::Error::last_os_error()
197                .raw_os_error()
198                .unwrap_or(0);
199            if err == libc::EINTR {
200                continue;
201            }
202            return false;
203        }
204        if rc == 0 {
205            return false;
206        }
207        let interest = libc::POLLIN | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL;
208        return pfd.revents & interest != 0;
209    }
210}
211
212/// Mark a host fd non-blocking (best-effort).
213fn set_nonblock(fd: RawFd) {
214    // SAFETY: live fd from socket/accept/pipe.
215    unsafe {
216        let fl = libc::fcntl(fd, libc::F_GETFL);
217        if fl >= 0 {
218            let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
219        }
220    }
221}
222
223/// `socket(domain, type, protocol)` — host libc. Returns host fd or `None`.
224///
225/// Sockets are forced `O_NONBLOCK`. Curl/c-ares (and the multi interface)
226/// expect non-blocking I/O; a blocking `recv` on a keep-alive TCP socket after
227/// the response body is complete hangs the guest forever (clean-exit G3).
228#[must_use]
229pub fn socket(domain: libc::c_int, ty: libc::c_int, protocol: libc::c_int) -> Option<RawFd> {
230    // SAFETY: standard socket(2). Strip Darwin-only type flags if any sneak in;
231    // Linux SOCK_NONBLOCK/CLOEXEC bits differ and are applied via fcntl below.
232    let ty_plain = ty & 0xf;
233    let rc = unsafe { libc::socket(domain, ty_plain, protocol) };
234    if rc < 0 {
235        return None;
236    }
237    set_nonblock(rc);
238    // SAFETY: freshly created socket.
239    unsafe {
240        let _ = libc::fcntl(rc, libc::F_SETFD, libc::FD_CLOEXEC);
241    }
242    Some(rc)
243}
244
245/// `socketpair(domain, type, protocol, sv[2])`.
246pub fn socketpair(
247    domain: libc::c_int,
248    ty: libc::c_int,
249    protocol: libc::c_int,
250) -> Option<(RawFd, RawFd)> {
251    let mut sv = [0_i32; 2];
252    let ty_plain = ty & 0xf;
253    // SAFETY: stack pair for the kernel to fill.
254    let rc = unsafe { libc::socketpair(domain, ty_plain, protocol, sv.as_mut_ptr()) };
255    if rc != 0 {
256        return None;
257    }
258    set_nonblock(sv[0]);
259    set_nonblock(sv[1]);
260    // SAFETY: freshly created sockets.
261    unsafe {
262        let _ = libc::fcntl(sv[0], libc::F_SETFD, libc::FD_CLOEXEC);
263        let _ = libc::fcntl(sv[1], libc::F_SETFD, libc::FD_CLOEXEC);
264    }
265    Some((sv[0], sv[1]))
266}
267
268/// `connect(fd, sockaddr_bytes)`.
269pub fn connect(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
270    let Some(len) = socklen_of(addr.len()) else {
271        return Err(libc::EINVAL);
272    };
273    // SAFETY: `addr` is a valid host buffer for `len` bytes.
274    let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), len) };
275    if rc == 0 { Ok(()) } else { Err(last_errno()) }
276}
277
278/// `bind(fd, sockaddr_bytes)`.
279pub fn bind(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
280    let Some(len) = socklen_of(addr.len()) else {
281        return Err(libc::EINVAL);
282    };
283    // SAFETY: `addr` is a valid host buffer for `len` bytes.
284    let rc = unsafe { libc::bind(fd, addr.as_ptr().cast(), len) };
285    if rc == 0 { Ok(()) } else { Err(last_errno()) }
286}
287
288/// `listen(fd, backlog)`.
289pub fn listen(fd: RawFd, backlog: libc::c_int) -> Result<(), i32> {
290    // SAFETY: live socket fd.
291    let rc = unsafe { libc::listen(fd, backlog) };
292    if rc == 0 { Ok(()) } else { Err(last_errno()) }
293}
294
295/// `accept(fd)` — peer address discarded (curl client path rarely needs it).
296pub fn accept(fd: RawFd) -> Result<RawFd, i32> {
297    // SAFETY: live listening socket; null addr is allowed by accept(2).
298    let rc = unsafe { libc::accept(fd, ptr::null_mut(), ptr::null_mut()) };
299    if rc < 0 {
300        Err(last_errno())
301    } else {
302        set_nonblock(rc);
303        Ok(rc)
304    }
305}
306
307/// `accept` with peer sockaddr written into `addr_out` (truncated to buffer len).
308///
309/// Returns `(new_fd, bytes_written_into_addr_out)`.
310pub fn accept_addr(fd: RawFd, addr_out: &mut [u8]) -> Result<(RawFd, usize), i32> {
311    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
312    // SAFETY: live socket; `addr_out` is writable for `alen` bytes.
313    let rc = unsafe {
314        libc::accept(
315            fd,
316            addr_out.as_mut_ptr().cast(),
317            ptr::addr_of_mut!(alen),
318        )
319    };
320    if rc < 0 {
321        return Err(last_errno());
322    }
323    set_nonblock(rc);
324    let n = usize::try_from(alen).unwrap_or(0).min(addr_out.len());
325    Ok((rc, n))
326}
327
328/// `setsockopt(fd, level, optname, value_bytes)`.
329pub fn setsockopt(
330    fd: RawFd,
331    level: libc::c_int,
332    optname: libc::c_int,
333    value: &[u8],
334) -> Result<(), i32> {
335    let Some(len) = socklen_of(value.len()) else {
336        return Err(libc::EINVAL);
337    };
338    // SAFETY: live socket; value buffer valid for `len` bytes.
339    let rc = unsafe {
340        libc::setsockopt(
341            fd,
342            level,
343            optname,
344            value.as_ptr().cast(),
345            len,
346        )
347    };
348    if rc == 0 { Ok(()) } else { Err(last_errno()) }
349}
350
351/// `getsockopt` — writes into `value`, returns updated length.
352pub fn getsockopt(
353    fd: RawFd,
354    level: libc::c_int,
355    optname: libc::c_int,
356    value: &mut [u8],
357) -> Result<usize, i32> {
358    let mut len = socklen_of(value.len()).unwrap_or(0);
359    // SAFETY: live socket; value buffer writable.
360    let rc = unsafe {
361        libc::getsockopt(
362            fd,
363            level,
364            optname,
365            value.as_mut_ptr().cast(),
366            ptr::addr_of_mut!(len),
367        )
368    };
369    if rc == 0 {
370        Ok(usize::try_from(len).unwrap_or(0).min(value.len()))
371    } else {
372        Err(last_errno())
373    }
374}
375
376/// `shutdown(fd, how)`.
377pub fn shutdown(fd: RawFd, how: libc::c_int) -> Result<(), i32> {
378    // SAFETY: live socket fd.
379    let rc = unsafe { libc::shutdown(fd, how) };
380    if rc == 0 { Ok(()) } else { Err(last_errno()) }
381}
382
383/// `sendto` / `send` — optional peer address bytes.
384pub fn sendto(
385    fd: RawFd,
386    buf: &[u8],
387    flags: libc::c_int,
388    addr: Option<&[u8]>,
389) -> Result<usize, i32> {
390    let (ap, alen) = if let Some(a) = addr {
391        let Some(len) = socklen_of(a.len()) else {
392            return Err(libc::EINVAL);
393        };
394        (a.as_ptr().cast(), len)
395    } else {
396        (ptr::null(), 0)
397    };
398    // SAFETY: live fd; buffer valid; optional sockaddr.
399    let n = unsafe { libc::sendto(fd, buf.as_ptr().cast(), buf.len(), flags, ap, alen) };
400    if n < 0 {
401        Err(last_errno())
402    } else {
403        usize::try_from(n).map_err(|_| libc::EIO)
404    }
405}
406
407/// `recvfrom` / `recv` — optional peer address out-buffer.
408///
409/// Returns `(bytes_read, peer_addr_len)` when `addr_out` is `Some`.
410pub fn recvfrom(
411    fd: RawFd,
412    buf: &mut [u8],
413    flags: libc::c_int,
414    addr_out: Option<&mut [u8]>,
415) -> Result<(usize, usize), i32> {
416    let (n, peer_len) = if let Some(a) = addr_out {
417        let mut alen = socklen_of(a.len()).unwrap_or(0);
418        // SAFETY: live fd; buffers valid.
419        let n = unsafe {
420            libc::recvfrom(
421                fd,
422                buf.as_mut_ptr().cast(),
423                buf.len(),
424                flags,
425                a.as_mut_ptr().cast(),
426                ptr::addr_of_mut!(alen),
427            )
428        };
429        (n, usize::try_from(alen).unwrap_or(0).min(a.len()))
430    } else {
431        // SAFETY: live fd; buffer valid; null peer.
432        let n = unsafe {
433            libc::recvfrom(
434                fd,
435                buf.as_mut_ptr().cast(),
436                buf.len(),
437                flags,
438                ptr::null_mut(),
439                ptr::null_mut(),
440            )
441        };
442        (n, 0)
443    };
444    if n < 0 {
445        Err(last_errno())
446    } else {
447        let nr = usize::try_from(n).map_err(|_| libc::EIO)?;
448        Ok((nr, peer_len))
449    }
450}
451
452/// `getsockname(fd, addr_out)`.
453pub fn getsockname(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
454    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
455    // SAFETY: live socket; buffer writable for `alen` bytes.
456    let rc = unsafe {
457        libc::getsockname(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
458    };
459    if rc == 0 {
460        Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
461    } else {
462        Err(last_errno())
463    }
464}
465
466/// `getpeername(fd, addr_out)`.
467pub fn getpeername(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
468    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
469    // SAFETY: live socket; buffer writable for `alen` bytes.
470    let rc = unsafe {
471        libc::getpeername(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
472    };
473    if rc == 0 {
474        Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
475    } else {
476        Err(last_errno())
477    }
478}
479
480/// `poll(fds, timeout_ms)` — empty slice sleeps / checks timeout only.
481pub fn poll(fds: &mut [libc::pollfd], timeout: libc::c_int) -> Result<i32, i32> {
482    let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
483    // SAFETY: `fds` is a valid pollfd array of `nfds` entries (or empty).
484    let rc = unsafe {
485        libc::poll(
486            if fds.is_empty() {
487                ptr::null_mut()
488            } else {
489                fds.as_mut_ptr()
490            },
491            nfds,
492            timeout,
493        )
494    };
495    if rc < 0 { Err(last_errno()) } else { Ok(rc) }
496}
497
498/// `lseek` on a host fd.
499pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
500    // SAFETY: live fd; whence is a SEEK_* constant.
501    let rc = unsafe { libc::lseek(fd, offset, whence) };
502    if rc < 0 { None } else { Some(rc) }
503}
504
505/// `fcntl` with no extra arg (`F_GETFD` / `F_GETFL`).
506pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
507    // SAFETY: live fd; cmd is a valid fcntl command.
508    let rc = unsafe { libc::fcntl(fd, cmd) };
509    if rc < 0 { None } else { Some(rc) }
510}
511
512/// `fcntl` with one integer arg (`F_SETFD` / `F_SETFL` / `F_DUPFD`).
513pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
514    // SAFETY: live fd; cmd/arg match the fcntl ABI.
515    let rc = unsafe { libc::fcntl(fd, cmd, arg) };
516    if rc < 0 { None } else { Some(rc) }
517}
518
519/// `open(path, flags, mode)` — prefers libc over `std::fs::OpenOptions` so
520/// directories open with `O_RDONLY` (archive walks) and we avoid extra syscalls.
521pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
522    // SAFETY: path is a valid C string for the duration of the call.
523    let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
524    if rc < 0 { None } else { Some(rc) }
525}
526
527/// Open a directory as `O_RDONLY|O_DIRECTORY|O_CLOEXEC` (bottle root dirfd, B1).
528pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
529    open_path(
530        path,
531        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
532        0,
533    )
534}
535
536/// `openat(dirfd, path, flags, mode)`.
537pub fn openat(
538    dirfd: RawFd,
539    path: &std::ffi::CStr,
540    flags: libc::c_int,
541    mode: libc::c_uint,
542) -> Option<RawFd> {
543    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
544    let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
545    if rc < 0 { None } else { Some(rc) }
546}
547
548/// `mkdirat(dirfd, path, mode)` — returns `Ok(())` on success or `EEXIST`.
549pub fn mkdirat(dirfd: RawFd, path: &std::ffi::CStr, mode: libc::mode_t) -> io::Result<()> {
550    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
551    let rc = unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) };
552    if rc == 0 {
553        return Ok(());
554    }
555    let err = io::Error::last_os_error();
556    if err.raw_os_error() == Some(libc::EEXIST) {
557        Ok(())
558    } else {
559        Err(err)
560    }
561}
562
563/// `fstatat(dirfd, path, …)` — used by B1 bottle-relative `stat`/`lstat`.
564pub fn fstatat(dirfd: RawFd, path: &std::ffi::CStr, no_follow: bool) -> Option<libc::stat> {
565    let mut st: libc::stat = unsafe { std::mem::zeroed() };
566    let flags = if no_follow {
567        libc::AT_SYMLINK_NOFOLLOW
568    } else {
569        0
570    };
571    // SAFETY: dirfd live; path valid C string; stack `stat` buffer.
572    let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
573    if rc == 0 { Some(st) } else { None }
574}
575
576/// `faccessat(dirfd, path, F_OK, 0)` — existence check without full path build.
577pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
578    // SAFETY: dirfd live; path valid C string.
579    let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
580    rc == 0
581}
582
583/// Write bytes to a host fd (`write(2)`).
584pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
585    if data.is_empty() {
586        return Ok(0);
587    }
588    // SAFETY: fd live; buffer valid for `data.len()` bytes.
589    let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
590    if n < 0 {
591        return Err(io::Error::last_os_error());
592    }
593    usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
594}
595
596/// Read bytes from a host fd (`read(2)`).
597pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
598    if buf.is_empty() {
599        return Ok(0);
600    }
601    // SAFETY: fd live; buffer valid for `buf.len()` bytes.
602    let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
603    if n < 0 {
604        return Err(io::Error::last_os_error());
605    }
606    usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
607}
608
609/// `fstat` into a host `stat` buffer.
610pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
611    // SAFETY: live fd; stack buffer is valid for the duration of the call.
612    let mut st: libc::stat = unsafe { std::mem::zeroed() };
613    let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
614    if rc == 0 { Some(st) } else { None }
615}
616
617/// `ftruncate(fd, length)`.
618pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
619    // SAFETY: live fd.
620    let rc = unsafe { libc::ftruncate(fd, length) };
621    if rc == 0 { Some(()) } else { None }
622}
623
624/// `fsync(fd)`.
625pub fn fsync_fd(fd: RawFd) -> Option<()> {
626    // SAFETY: live fd.
627    let rc = unsafe { libc::fsync(fd) };
628    if rc == 0 { Some(()) } else { None }
629}
630
631/// `readlink(path)` into `buf` (no trailing NUL). Returns bytes written or host errno.
632pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
633    if buf.is_empty() {
634        return Ok(0);
635    }
636    // SAFETY: path is a valid C string; buffer is writable for `buf.len()`.
637    let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
638    if n < 0 {
639        return Err(io::Error::last_os_error()
640            .raw_os_error()
641            .unwrap_or(libc::EIO));
642    }
643    usize::try_from(n).map_err(|_| libc::EIO)
644}
645
646/// `symlink(target, linkpath)`.
647pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
648    // SAFETY: both are valid C strings for the duration of the call.
649    let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
650    if rc == 0 {
651        Ok(())
652    } else {
653        Err(io::Error::last_os_error()
654            .raw_os_error()
655            .unwrap_or(libc::EIO))
656    }
657}
658
659/// `link(existing, newpath)` hard link.
660pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
661    // SAFETY: both are valid C strings for the duration of the call.
662    let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
663    if rc == 0 {
664        Ok(())
665    } else {
666        Err(io::Error::last_os_error()
667            .raw_os_error()
668            .unwrap_or(libc::EIO))
669    }
670}
671
672/// Host `gettimeofday` (timezone ignored).
673pub fn gettimeofday() -> Option<libc::timeval> {
674    // SAFETY: stack timeval; null tz pointer is allowed.
675    let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
676    let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
677    if rc == 0 { Some(tv) } else { None }
678}
679
680/// Host `clock_gettime`.
681pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
682    // SAFETY: stack timespec; clock_id is a host constant.
683    let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
684    let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
685    if rc == 0 { Some(ts) } else { None }
686}
687
688/// Anonymous or file-backed `mmap`. Returns host base or `None` on failure.
689///
690/// When `fixed_addr` is `Some(va)`, the call uses that as the address hint
691/// (combine with [`fixed_map_flag`] / `MAP_FIXED` as appropriate).
692#[must_use]
693pub fn mmap(
694    fixed_addr: Option<u64>,
695    len: usize,
696    prot: libc::c_int,
697    flags: libc::c_int,
698    fd: RawFd,
699    offset: i64,
700) -> Option<*mut u8> {
701    if len == 0 {
702        return None;
703    }
704    let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
705    // SAFETY: length non-zero; flags/prot valid combinations; fd matches flags;
706    // `addr` is either null or a page-aligned VA for fixed placement.
707    let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
708    if raw == libc::MAP_FAILED {
709        None
710    } else {
711        Some(raw.cast())
712    }
713}
714
715/// `munmap` a mapping previously returned by [`mmap`].
716pub fn munmap(ptr: *mut u8, len: usize) -> bool {
717    if ptr.is_null() || len == 0 {
718        return true;
719    }
720    // SAFETY: ptr/len came from a successful mmap owned by the caller.
721    let rc = unsafe { libc::munmap(ptr.cast(), len) };
722    rc == 0
723}
724
725/// `mprotect` on a host mapping range.
726pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
727    if ptr.is_null() || len == 0 {
728        return true;
729    }
730    // SAFETY: range is a live mapping owned by the caller.
731    let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
732    rc == 0
733}
734
735/// `msync` on a host mapping range.
736pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
737    if ptr.is_null() || len == 0 {
738        return true;
739    }
740    // SAFETY: range is a live mapping; flags are MS_* bits.
741    let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
742    rc == 0
743}
744
745/// Pointer address as `u64` (identity guest/host model helpers).
746#[must_use]
747pub fn ptr_addr_u64(p: *mut u8) -> u64 {
748    u64::try_from(p.addr()).unwrap_or(0)
749}
750
751/// `u64` address → void pointer (fixed mmap hints).
752#[must_use]
753pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
754    let u = usize::try_from(addr).unwrap_or(0);
755    ptr::with_exposed_provenance_mut::<u8>(u).cast()
756}
757
758// ── directory streams (for guest readdir) ───────────────────────────────────
759
760/// Opaque host directory stream (`DIR*`).
761#[derive(Debug)]
762pub struct HostDir {
763    ptr: *mut libc::DIR,
764}
765
766// SAFETY: process-wide guest model serializes dir mutation under ProcessState
767// write lock; readers never touch `HostDir`.
768unsafe impl Send for HostDir {}
769// SAFETY: same as `Send` — exclusive dir use under write lock only.
770unsafe impl Sync for HostDir {}
771
772impl HostDir {
773    /// Open a directory stream on a **duplicate** of `host_fd` (does not own `host_fd`).
774    pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
775        // SAFETY: dup of a live host FD.
776        let dup = unsafe { libc::dup(host_fd) };
777        if dup < 0 {
778            return Err(last_errno_i32());
779        }
780        // SAFETY: fdopendir takes ownership of `dup`.
781        let dir = unsafe { libc::fdopendir(dup) };
782        if dir.is_null() {
783            let err = last_errno_i32();
784            // SAFETY: close the unused dup on failure.
785            unsafe {
786                libc::close(dup);
787            }
788            return Err(err);
789        }
790        Ok(Self { ptr: dir })
791    }
792
793    /// Next entry: `(name_bytes, d_type)`. `None` at end of stream.
794    pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
795        use std::ffi::CStr;
796        loop {
797            // SAFETY: `ptr` from fdopendir; readdir is the iterator.
798            let ent = unsafe { libc::readdir(self.ptr) };
799            if ent.is_null() {
800                return None;
801            }
802            // SAFETY: ent valid until next readdir/closedir.
803            let d_type = unsafe { (*ent).d_type };
804            let name_ptr = unsafe { (*ent).d_name.as_ptr() };
805            let name = unsafe { CStr::from_ptr(name_ptr) };
806            let bytes = name.to_bytes().to_vec();
807            if bytes.is_empty() {
808                continue;
809            }
810            return Some((bytes, d_type));
811        }
812    }
813}
814
815impl Drop for HostDir {
816    fn drop(&mut self) {
817        if !self.ptr.is_null() {
818            // SAFETY: owns DIR* from fdopendir.
819            unsafe {
820                let _ = libc::closedir(self.ptr);
821            }
822            self.ptr = ptr::null_mut();
823        }
824    }
825}
826
827fn last_errno_i32() -> i32 {
828    let raw = io::Error::last_os_error()
829        .raw_os_error()
830        .unwrap_or(1)
831        .unsigned_abs();
832    i32::try_from(raw).unwrap_or(1)
833}