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/// `openat(dirfd, path, flags, mode)`.
109pub fn openat(
110    dirfd: RawFd,
111    path: &std::ffi::CStr,
112    flags: libc::c_int,
113    mode: libc::c_uint,
114) -> Option<RawFd> {
115    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
116    let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
117    if rc < 0 { None } else { Some(rc) }
118}
119
120/// Write bytes to a host fd (`write(2)`).
121pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
122    if data.is_empty() {
123        return Ok(0);
124    }
125    // SAFETY: fd live; buffer valid for `data.len()` bytes.
126    let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
127    if n < 0 {
128        return Err(io::Error::last_os_error());
129    }
130    usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
131}
132
133/// Read bytes from a host fd (`read(2)`).
134pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
135    if buf.is_empty() {
136        return Ok(0);
137    }
138    // SAFETY: fd live; buffer valid for `buf.len()` bytes.
139    let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
140    if n < 0 {
141        return Err(io::Error::last_os_error());
142    }
143    usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
144}
145
146/// `fstat` into a host `stat` buffer.
147pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
148    // SAFETY: live fd; stack buffer is valid for the duration of the call.
149    let mut st: libc::stat = unsafe { std::mem::zeroed() };
150    let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
151    if rc == 0 { Some(st) } else { None }
152}
153
154/// `ftruncate(fd, length)`.
155pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
156    // SAFETY: live fd.
157    let rc = unsafe { libc::ftruncate(fd, length) };
158    if rc == 0 { Some(()) } else { None }
159}
160
161/// `fsync(fd)`.
162pub fn fsync_fd(fd: RawFd) -> Option<()> {
163    // SAFETY: live fd.
164    let rc = unsafe { libc::fsync(fd) };
165    if rc == 0 { Some(()) } else { None }
166}
167
168/// Host `gettimeofday` (timezone ignored).
169pub fn gettimeofday() -> Option<libc::timeval> {
170    // SAFETY: stack timeval; null tz pointer is allowed.
171    let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
172    let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
173    if rc == 0 { Some(tv) } else { None }
174}
175
176/// Host `clock_gettime`.
177pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
178    // SAFETY: stack timespec; clock_id is a host constant.
179    let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
180    let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
181    if rc == 0 { Some(ts) } else { None }
182}
183
184/// Anonymous or file-backed `mmap`. Returns host base or `None` on failure.
185///
186/// When `fixed_addr` is `Some(va)`, the call uses that as the address hint
187/// (combine with [`fixed_map_flag`] / `MAP_FIXED` as appropriate).
188#[must_use]
189pub fn mmap(
190    fixed_addr: Option<u64>,
191    len: usize,
192    prot: libc::c_int,
193    flags: libc::c_int,
194    fd: RawFd,
195    offset: i64,
196) -> Option<*mut u8> {
197    if len == 0 {
198        return None;
199    }
200    let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
201    // SAFETY: length non-zero; flags/prot valid combinations; fd matches flags;
202    // `addr` is either null or a page-aligned VA for fixed placement.
203    let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
204    if raw == libc::MAP_FAILED {
205        None
206    } else {
207        Some(raw.cast())
208    }
209}
210
211/// `munmap` a mapping previously returned by [`mmap`].
212pub fn munmap(ptr: *mut u8, len: usize) -> bool {
213    if ptr.is_null() || len == 0 {
214        return true;
215    }
216    // SAFETY: ptr/len came from a successful mmap owned by the caller.
217    let rc = unsafe { libc::munmap(ptr.cast(), len) };
218    rc == 0
219}
220
221/// `mprotect` on a host mapping range.
222pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
223    if ptr.is_null() || len == 0 {
224        return true;
225    }
226    // SAFETY: range is a live mapping owned by the caller.
227    let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
228    rc == 0
229}
230
231/// `msync` on a host mapping range.
232pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
233    if ptr.is_null() || len == 0 {
234        return true;
235    }
236    // SAFETY: range is a live mapping; flags are MS_* bits.
237    let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
238    rc == 0
239}
240
241/// Pointer address as `u64` (identity guest/host model helpers).
242#[must_use]
243pub fn ptr_addr_u64(p: *mut u8) -> u64 {
244    u64::try_from(p.addr()).unwrap_or(0)
245}
246
247/// `u64` address → void pointer (fixed mmap hints).
248#[must_use]
249pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
250    let u = usize::try_from(addr).unwrap_or(0);
251    ptr::with_exposed_provenance_mut::<u8>(u).cast()
252}
253
254// ── directory streams (for guest readdir) ───────────────────────────────────
255
256/// Opaque host directory stream (`DIR*`).
257#[derive(Debug)]
258pub struct HostDir {
259    ptr: *mut libc::DIR,
260}
261
262// SAFETY: process-wide guest model serializes dir mutation under ProcessState
263// write lock; readers never touch `HostDir`.
264unsafe impl Send for HostDir {}
265// SAFETY: same as `Send` — exclusive dir use under write lock only.
266unsafe impl Sync for HostDir {}
267
268impl HostDir {
269    /// Open a directory stream on a **duplicate** of `host_fd` (does not own `host_fd`).
270    pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
271        // SAFETY: dup of a live host FD.
272        let dup = unsafe { libc::dup(host_fd) };
273        if dup < 0 {
274            return Err(last_errno_i32());
275        }
276        // SAFETY: fdopendir takes ownership of `dup`.
277        let dir = unsafe { libc::fdopendir(dup) };
278        if dir.is_null() {
279            let err = last_errno_i32();
280            // SAFETY: close the unused dup on failure.
281            unsafe {
282                libc::close(dup);
283            }
284            return Err(err);
285        }
286        Ok(Self { ptr: dir })
287    }
288
289    /// Next entry: `(name_bytes, d_type)`. `None` at end of stream.
290    pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
291        use std::ffi::CStr;
292        loop {
293            // SAFETY: `ptr` from fdopendir; readdir is the iterator.
294            let ent = unsafe { libc::readdir(self.ptr) };
295            if ent.is_null() {
296                return None;
297            }
298            // SAFETY: ent valid until next readdir/closedir.
299            let d_type = unsafe { (*ent).d_type };
300            let name_ptr = unsafe { (*ent).d_name.as_ptr() };
301            let name = unsafe { CStr::from_ptr(name_ptr) };
302            let bytes = name.to_bytes().to_vec();
303            if bytes.is_empty() {
304                continue;
305            }
306            return Some((bytes, d_type));
307        }
308    }
309}
310
311impl Drop for HostDir {
312    fn drop(&mut self) {
313        if !self.ptr.is_null() {
314            // SAFETY: owns DIR* from fdopendir.
315            unsafe {
316                let _ = libc::closedir(self.ptr);
317            }
318            self.ptr = ptr::null_mut();
319        }
320    }
321}
322
323fn last_errno_i32() -> i32 {
324    let raw = io::Error::last_os_error()
325        .raw_os_error()
326        .unwrap_or(1)
327        .unsigned_abs();
328    i32::try_from(raw).unwrap_or(1)
329}