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