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/// `lseek` on a host fd.
80pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
81    // SAFETY: live fd; whence is a SEEK_* constant.
82    let rc = unsafe { libc::lseek(fd, offset, whence) };
83    if rc < 0 { None } else { Some(rc) }
84}
85
86/// `fcntl` with no extra arg (`F_GETFD` / `F_GETFL`).
87pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
88    // SAFETY: live fd; cmd is a valid fcntl command.
89    let rc = unsafe { libc::fcntl(fd, cmd) };
90    if rc < 0 { None } else { Some(rc) }
91}
92
93/// `fcntl` with one integer arg (`F_SETFD` / `F_SETFL` / `F_DUPFD`).
94pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
95    // SAFETY: live fd; cmd/arg match the fcntl ABI.
96    let rc = unsafe { libc::fcntl(fd, cmd, arg) };
97    if rc < 0 { None } else { Some(rc) }
98}
99
100/// `open(path, flags, mode)` — prefers libc over `std::fs::OpenOptions` so
101/// directories open with `O_RDONLY` (archive walks) and we avoid extra syscalls.
102pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
103    // SAFETY: path is a valid C string for the duration of the call.
104    let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
105    if rc < 0 { None } else { Some(rc) }
106}
107
108/// Open a directory as `O_RDONLY|O_DIRECTORY|O_CLOEXEC` (bottle root dirfd, B1).
109pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
110    open_path(
111        path,
112        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
113        0,
114    )
115}
116
117/// `openat(dirfd, path, flags, mode)`.
118pub fn openat(
119    dirfd: RawFd,
120    path: &std::ffi::CStr,
121    flags: libc::c_int,
122    mode: libc::c_uint,
123) -> Option<RawFd> {
124    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
125    let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
126    if rc < 0 { None } else { Some(rc) }
127}
128
129/// `fstatat(dirfd, path, …)` — used by B1 bottle-relative `stat`/`lstat`.
130pub fn fstatat(
131    dirfd: RawFd,
132    path: &std::ffi::CStr,
133    no_follow: bool,
134) -> Option<libc::stat> {
135    let mut st: libc::stat = unsafe { std::mem::zeroed() };
136    let flags = if no_follow {
137        libc::AT_SYMLINK_NOFOLLOW
138    } else {
139        0
140    };
141    // SAFETY: dirfd live; path valid C string; stack `stat` buffer.
142    let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
143    if rc == 0 { Some(st) } else { None }
144}
145
146/// `faccessat(dirfd, path, F_OK, 0)` — existence check without full path build.
147pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
148    // SAFETY: dirfd live; path valid C string.
149    let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
150    rc == 0
151}
152
153/// Write bytes to a host fd (`write(2)`).
154pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
155    if data.is_empty() {
156        return Ok(0);
157    }
158    // SAFETY: fd live; buffer valid for `data.len()` bytes.
159    let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
160    if n < 0 {
161        return Err(io::Error::last_os_error());
162    }
163    usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
164}
165
166/// Read bytes from a host fd (`read(2)`).
167pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
168    if buf.is_empty() {
169        return Ok(0);
170    }
171    // SAFETY: fd live; buffer valid for `buf.len()` bytes.
172    let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
173    if n < 0 {
174        return Err(io::Error::last_os_error());
175    }
176    usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
177}
178
179/// `fstat` into a host `stat` buffer.
180pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
181    // SAFETY: live fd; stack buffer is valid for the duration of the call.
182    let mut st: libc::stat = unsafe { std::mem::zeroed() };
183    let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
184    if rc == 0 { Some(st) } else { None }
185}
186
187/// `ftruncate(fd, length)`.
188pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
189    // SAFETY: live fd.
190    let rc = unsafe { libc::ftruncate(fd, length) };
191    if rc == 0 { Some(()) } else { None }
192}
193
194/// `fsync(fd)`.
195pub fn fsync_fd(fd: RawFd) -> Option<()> {
196    // SAFETY: live fd.
197    let rc = unsafe { libc::fsync(fd) };
198    if rc == 0 { Some(()) } else { None }
199}
200
201/// `readlink(path)` into `buf` (no trailing NUL). Returns bytes written or host errno.
202pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
203    if buf.is_empty() {
204        return Ok(0);
205    }
206    // SAFETY: path is a valid C string; buffer is writable for `buf.len()`.
207    let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
208    if n < 0 {
209        return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO));
210    }
211    usize::try_from(n).map_err(|_| libc::EIO)
212}
213
214/// `symlink(target, linkpath)`.
215pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
216    // SAFETY: both are valid C strings for the duration of the call.
217    let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
218    if rc == 0 {
219        Ok(())
220    } else {
221        Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO))
222    }
223}
224
225/// `link(existing, newpath)` hard link.
226pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
227    // SAFETY: both are valid C strings for the duration of the call.
228    let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
229    if rc == 0 {
230        Ok(())
231    } else {
232        Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO))
233    }
234}
235
236/// Host `gettimeofday` (timezone ignored).
237pub fn gettimeofday() -> Option<libc::timeval> {
238    // SAFETY: stack timeval; null tz pointer is allowed.
239    let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
240    let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
241    if rc == 0 { Some(tv) } else { None }
242}
243
244/// Host `clock_gettime`.
245pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
246    // SAFETY: stack timespec; clock_id is a host constant.
247    let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
248    let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
249    if rc == 0 { Some(ts) } else { None }
250}
251
252/// Anonymous or file-backed `mmap`. Returns host base or `None` on failure.
253///
254/// When `fixed_addr` is `Some(va)`, the call uses that as the address hint
255/// (combine with [`fixed_map_flag`] / `MAP_FIXED` as appropriate).
256#[must_use]
257pub fn mmap(
258    fixed_addr: Option<u64>,
259    len: usize,
260    prot: libc::c_int,
261    flags: libc::c_int,
262    fd: RawFd,
263    offset: i64,
264) -> Option<*mut u8> {
265    if len == 0 {
266        return None;
267    }
268    let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
269    // SAFETY: length non-zero; flags/prot valid combinations; fd matches flags;
270    // `addr` is either null or a page-aligned VA for fixed placement.
271    let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
272    if raw == libc::MAP_FAILED {
273        None
274    } else {
275        Some(raw.cast())
276    }
277}
278
279/// `munmap` a mapping previously returned by [`mmap`].
280pub fn munmap(ptr: *mut u8, len: usize) -> bool {
281    if ptr.is_null() || len == 0 {
282        return true;
283    }
284    // SAFETY: ptr/len came from a successful mmap owned by the caller.
285    let rc = unsafe { libc::munmap(ptr.cast(), len) };
286    rc == 0
287}
288
289/// `mprotect` on a host mapping range.
290pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
291    if ptr.is_null() || len == 0 {
292        return true;
293    }
294    // SAFETY: range is a live mapping owned by the caller.
295    let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
296    rc == 0
297}
298
299/// `msync` on a host mapping range.
300pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
301    if ptr.is_null() || len == 0 {
302        return true;
303    }
304    // SAFETY: range is a live mapping; flags are MS_* bits.
305    let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
306    rc == 0
307}
308
309/// Pointer address as `u64` (identity guest/host model helpers).
310#[must_use]
311pub fn ptr_addr_u64(p: *mut u8) -> u64 {
312    u64::try_from(p.addr()).unwrap_or(0)
313}
314
315/// `u64` address → void pointer (fixed mmap hints).
316#[must_use]
317pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
318    let u = usize::try_from(addr).unwrap_or(0);
319    ptr::with_exposed_provenance_mut::<u8>(u).cast()
320}
321
322// ── directory streams (for guest readdir) ───────────────────────────────────
323
324/// Opaque host directory stream (`DIR*`).
325#[derive(Debug)]
326pub struct HostDir {
327    ptr: *mut libc::DIR,
328}
329
330// SAFETY: process-wide guest model serializes dir mutation under ProcessState
331// write lock; readers never touch `HostDir`.
332unsafe impl Send for HostDir {}
333// SAFETY: same as `Send` — exclusive dir use under write lock only.
334unsafe impl Sync for HostDir {}
335
336impl HostDir {
337    /// Open a directory stream on a **duplicate** of `host_fd` (does not own `host_fd`).
338    pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
339        // SAFETY: dup of a live host FD.
340        let dup = unsafe { libc::dup(host_fd) };
341        if dup < 0 {
342            return Err(last_errno_i32());
343        }
344        // SAFETY: fdopendir takes ownership of `dup`.
345        let dir = unsafe { libc::fdopendir(dup) };
346        if dir.is_null() {
347            let err = last_errno_i32();
348            // SAFETY: close the unused dup on failure.
349            unsafe {
350                libc::close(dup);
351            }
352            return Err(err);
353        }
354        Ok(Self { ptr: dir })
355    }
356
357    /// Next entry: `(name_bytes, d_type)`. `None` at end of stream.
358    pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
359        use std::ffi::CStr;
360        loop {
361            // SAFETY: `ptr` from fdopendir; readdir is the iterator.
362            let ent = unsafe { libc::readdir(self.ptr) };
363            if ent.is_null() {
364                return None;
365            }
366            // SAFETY: ent valid until next readdir/closedir.
367            let d_type = unsafe { (*ent).d_type };
368            let name_ptr = unsafe { (*ent).d_name.as_ptr() };
369            let name = unsafe { CStr::from_ptr(name_ptr) };
370            let bytes = name.to_bytes().to_vec();
371            if bytes.is_empty() {
372                continue;
373            }
374            return Some((bytes, d_type));
375        }
376    }
377}
378
379impl Drop for HostDir {
380    fn drop(&mut self) {
381        if !self.ptr.is_null() {
382            // SAFETY: owns DIR* from fdopendir.
383            unsafe {
384                let _ = libc::closedir(self.ptr);
385            }
386            self.ptr = ptr::null_mut();
387        }
388    }
389}
390
391fn last_errno_i32() -> i32 {
392    let raw = io::Error::last_os_error()
393        .raw_os_error()
394        .unwrap_or(1)
395        .unsigned_abs();
396    i32::try_from(raw).unwrap_or(1)
397}