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