kh-runtime 0.1.2

Kakehashi native ARM64 execution context, memory layout, traps, and bottle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Host OS primitives: the **only** crate-level home for most libc I/O and
//! memory syscalls used by the translator.
//!
//! Call sites should prefer these wrappers so `unsafe` does not scatter across
//! BSD handlers. Each function documents the ownership / validity contract.
#![allow(unsafe_code)]

use std::io;
use std::os::fd::RawFd;
use std::ptr;

/// Linux `MAP_FIXED_NOREPLACE` (do not clobber existing maps).
#[cfg(target_os = "linux")]
pub const MAP_FIXED_NOREPLACE: libc::c_int = 0x100_000;

/// Preferred fixed-map flag for this host.
#[must_use]
pub fn fixed_map_flag() -> libc::c_int {
    #[cfg(target_os = "linux")]
    {
        MAP_FIXED_NOREPLACE
    }
    #[cfg(not(target_os = "linux"))]
    {
        libc::MAP_FIXED
    }
}

/// Host page size in bytes, or `None` if `sysconf` fails.
#[must_use]
pub fn page_size() -> Option<usize> {
    // SAFETY: `sysconf(_SC_PAGESIZE)` returns a scalar; no memory is touched.
    let raw = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
    if raw <= 0 {
        return None;
    }
    usize::try_from(raw).ok()
}

/// Physical page count from `sysconf(_SC_PHYS_PAGES)`, when available.
#[must_use]
pub fn phys_pages() -> Option<u64> {
    // SAFETY: scalar sysconf; no memory is touched.
    let raw = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
    if raw <= 0 {
        return None;
    }
    u64::try_from(raw).ok()
}

/// Best-effort host RAM size in bytes.
#[must_use]
pub fn phys_mem_bytes() -> u64 {
    match (phys_pages(), page_size()) {
        (Some(pages), Some(page)) => {
            let s = u64::try_from(page).unwrap_or(0);
            pages.saturating_mul(s).max(64 * 1024 * 1024)
        }
        _ => 8 * 1024 * 1024 * 1024, // 8 GiB fallback
    }
}

/// Close a host file descriptor. Errors are ignored (best-effort cleanup).
pub fn close_fd(fd: RawFd) {
    // SAFETY: caller owned `fd` and will not use it after this call.
    unsafe {
        let _ = libc::close(fd);
    }
}

/// Duplicate a host fd. Returns the new fd or `None` on failure.
#[must_use]
pub fn dup_fd(fd: RawFd) -> Option<RawFd> {
    // SAFETY: `fd` is a live host descriptor.
    let rc = unsafe { libc::dup(fd) };
    if rc < 0 { None } else { Some(rc) }
}

/// `lseek` on a host fd.
pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
    // SAFETY: live fd; whence is a SEEK_* constant.
    let rc = unsafe { libc::lseek(fd, offset, whence) };
    if rc < 0 { None } else { Some(rc) }
}

/// `fcntl` with no extra arg (`F_GETFD` / `F_GETFL`).
pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
    // SAFETY: live fd; cmd is a valid fcntl command.
    let rc = unsafe { libc::fcntl(fd, cmd) };
    if rc < 0 { None } else { Some(rc) }
}

/// `fcntl` with one integer arg (`F_SETFD` / `F_SETFL` / `F_DUPFD`).
pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
    // SAFETY: live fd; cmd/arg match the fcntl ABI.
    let rc = unsafe { libc::fcntl(fd, cmd, arg) };
    if rc < 0 { None } else { Some(rc) }
}

/// `open(path, flags, mode)` — prefers libc over `std::fs::OpenOptions` so
/// directories open with `O_RDONLY` (archive walks) and we avoid extra syscalls.
pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
    // SAFETY: path is a valid C string for the duration of the call.
    let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
    if rc < 0 { None } else { Some(rc) }
}

/// `openat(dirfd, path, flags, mode)`.
pub fn openat(
    dirfd: RawFd,
    path: &std::ffi::CStr,
    flags: libc::c_int,
    mode: libc::c_uint,
) -> Option<RawFd> {
    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
    let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
    if rc < 0 { None } else { Some(rc) }
}

/// Write bytes to a host fd (`write(2)`).
pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
    if data.is_empty() {
        return Ok(0);
    }
    // SAFETY: fd live; buffer valid for `data.len()` bytes.
    let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
    if n < 0 {
        return Err(io::Error::last_os_error());
    }
    usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
}

/// Read bytes from a host fd (`read(2)`).
pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
    if buf.is_empty() {
        return Ok(0);
    }
    // SAFETY: fd live; buffer valid for `buf.len()` bytes.
    let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
    if n < 0 {
        return Err(io::Error::last_os_error());
    }
    usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
}

/// `fstat` into a host `stat` buffer.
pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
    // SAFETY: live fd; stack buffer is valid for the duration of the call.
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
    if rc == 0 { Some(st) } else { None }
}

/// `ftruncate(fd, length)`.
pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
    // SAFETY: live fd.
    let rc = unsafe { libc::ftruncate(fd, length) };
    if rc == 0 { Some(()) } else { None }
}

/// `fsync(fd)`.
pub fn fsync_fd(fd: RawFd) -> Option<()> {
    // SAFETY: live fd.
    let rc = unsafe { libc::fsync(fd) };
    if rc == 0 { Some(()) } else { None }
}

/// Host `gettimeofday` (timezone ignored).
pub fn gettimeofday() -> Option<libc::timeval> {
    // SAFETY: stack timeval; null tz pointer is allowed.
    let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
    let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
    if rc == 0 { Some(tv) } else { None }
}

/// Host `clock_gettime`.
pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
    // SAFETY: stack timespec; clock_id is a host constant.
    let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
    let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
    if rc == 0 { Some(ts) } else { None }
}

/// Anonymous or file-backed `mmap`. Returns host base or `None` on failure.
///
/// When `fixed_addr` is `Some(va)`, the call uses that as the address hint
/// (combine with [`fixed_map_flag`] / `MAP_FIXED` as appropriate).
#[must_use]
pub fn mmap(
    fixed_addr: Option<u64>,
    len: usize,
    prot: libc::c_int,
    flags: libc::c_int,
    fd: RawFd,
    offset: i64,
) -> Option<*mut u8> {
    if len == 0 {
        return None;
    }
    let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
    // SAFETY: length non-zero; flags/prot valid combinations; fd matches flags;
    // `addr` is either null or a page-aligned VA for fixed placement.
    let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
    if raw == libc::MAP_FAILED {
        None
    } else {
        Some(raw.cast())
    }
}

/// `munmap` a mapping previously returned by [`mmap`].
pub fn munmap(ptr: *mut u8, len: usize) -> bool {
    if ptr.is_null() || len == 0 {
        return true;
    }
    // SAFETY: ptr/len came from a successful mmap owned by the caller.
    let rc = unsafe { libc::munmap(ptr.cast(), len) };
    rc == 0
}

/// `mprotect` on a host mapping range.
pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
    if ptr.is_null() || len == 0 {
        return true;
    }
    // SAFETY: range is a live mapping owned by the caller.
    let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
    rc == 0
}

/// `msync` on a host mapping range.
pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
    if ptr.is_null() || len == 0 {
        return true;
    }
    // SAFETY: range is a live mapping; flags are MS_* bits.
    let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
    rc == 0
}

/// Pointer address as `u64` (identity guest/host model helpers).
#[must_use]
pub fn ptr_addr_u64(p: *mut u8) -> u64 {
    u64::try_from(p.addr()).unwrap_or(0)
}

/// `u64` address → void pointer (fixed mmap hints).
#[must_use]
pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
    let u = usize::try_from(addr).unwrap_or(0);
    ptr::with_exposed_provenance_mut::<u8>(u).cast()
}

// ── path / stat ─────────────────────────────────────────────────────────────

/// `stat(path, …)` into a host `stat` buffer.
pub fn stat_path(path: &std::ffi::CStr) -> Option<libc::stat> {
    // SAFETY: path is a valid C string for the duration of the call.
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    let rc = unsafe { libc::stat(path.as_ptr(), std::ptr::addr_of_mut!(st)) };
    if rc == 0 { Some(st) } else { None }
}

/// `lstat(path, …)` into a host `stat` buffer.
pub fn lstat_path(path: &std::ffi::CStr) -> Option<libc::stat> {
    // SAFETY: path is a valid C string for the duration of the call.
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    let rc = unsafe { libc::lstat(path.as_ptr(), std::ptr::addr_of_mut!(st)) };
    if rc == 0 { Some(st) } else { None }
}

/// `fstatat(dirfd, path, …, flags)`.
pub fn fstatat_path(
    dirfd: RawFd,
    path: &std::ffi::CStr,
    flags: libc::c_int,
) -> Option<libc::stat> {
    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    let rc = unsafe {
        libc::fstatat(
            dirfd,
            path.as_ptr(),
            std::ptr::addr_of_mut!(st),
            flags,
        )
    };
    if rc == 0 { Some(st) } else { None }
}

/// `access(path, mode)` — returns `true` when allowed.
pub fn access_path(path: &std::ffi::CStr, mode: libc::c_int) -> bool {
    // SAFETY: path is a valid C string for the duration of the call.
    let rc = unsafe { libc::access(path.as_ptr(), mode) };
    rc == 0
}

/// `unlink(path)`.
pub fn unlink_path(path: &std::ffi::CStr) -> Result<(), i32> {
    // SAFETY: path is a valid C string for the duration of the call.
    let rc = unsafe { libc::unlink(path.as_ptr()) };
    if rc == 0 {
        Ok(())
    } else {
        Err(last_errno_i32())
    }
}

/// `mkdir(path, mode)`.
pub fn mkdir_path(path: &std::ffi::CStr, mode: libc::mode_t) -> Result<(), i32> {
    // SAFETY: path is a valid C string for the duration of the call.
    let rc = unsafe { libc::mkdir(path.as_ptr(), mode) };
    if rc == 0 {
        Ok(())
    } else {
        Err(last_errno_i32())
    }
}

/// `rmdir(path)`.
pub fn rmdir_path(path: &std::ffi::CStr) -> Result<(), i32> {
    // SAFETY: path is a valid C string for the duration of the call.
    let rc = unsafe { libc::rmdir(path.as_ptr()) };
    if rc == 0 {
        Ok(())
    } else {
        Err(last_errno_i32())
    }
}

/// `rename(from, to)`.
pub fn rename_path(from: &std::ffi::CStr, to: &std::ffi::CStr) -> Result<(), i32> {
    // SAFETY: paths are valid C strings for the duration of the call.
    let rc = unsafe { libc::rename(from.as_ptr(), to.as_ptr()) };
    if rc == 0 {
        Ok(())
    } else {
        Err(last_errno_i32())
    }
}

// ── directory streams (for guest readdir) ───────────────────────────────────

/// Opaque host directory stream (`DIR*`) with optional getdents batching.
#[derive(Debug)]
pub struct HostDir {
    ptr: *mut libc::DIR,
}

// SAFETY: exclusive use under the dir-streams mutex only.
unsafe impl Send for HostDir {}
// SAFETY: exclusive use under the dir-streams mutex only.
unsafe impl Sync for HostDir {}

impl HostDir {
    /// Open a directory stream on a **duplicate** of `host_fd` (does not own `host_fd`).
    pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
        // SAFETY: dup of a live host FD.
        let dup = unsafe { libc::dup(host_fd) };
        if dup < 0 {
            return Err(last_errno_i32());
        }
        // SAFETY: fdopendir takes ownership of `dup`.
        let dir = unsafe { libc::fdopendir(dup) };
        if dir.is_null() {
            let err = last_errno_i32();
            // SAFETY: close the unused dup on failure.
            unsafe {
                libc::close(dup);
            }
            return Err(err);
        }
        Ok(Self { ptr: dir })
    }

    /// Next entry into `name_out` (NUL-terminated). Returns `d_type`, or `None` at EOF.
    ///
    /// No heap allocation: name is copied into the caller buffer (max `name_out.len()-1` bytes).
    pub fn read_next_into(&mut self, name_out: &mut [u8]) -> Option<u8> {
        use std::ffi::CStr;
        if name_out.is_empty() {
            return None;
        }
        loop {
            // SAFETY: `ptr` from fdopendir; readdir is the iterator.
            let ent = unsafe { libc::readdir(self.ptr) };
            if ent.is_null() {
                return None;
            }
            // SAFETY: ent valid until next readdir/closedir.
            let d_type = unsafe { (*ent).d_type };
            let name_ptr = unsafe { (*ent).d_name.as_ptr() };
            let name = unsafe { CStr::from_ptr(name_ptr) };
            let bytes = name.to_bytes();
            if bytes.is_empty() {
                continue;
            }
            let max = name_out.len().saturating_sub(1);
            let n = bytes.len().min(max);
            if let (Some(dst), Some(src)) = (name_out.get_mut(..n), bytes.get(..n)) {
                dst.copy_from_slice(src);
            }
            if let Some(slot) = name_out.get_mut(n) {
                *slot = 0;
            }
            // Clear any leftover tail so guest strlen/scan stops cleanly.
            if let Some(tail) = name_out.get_mut(n.saturating_add(1)..) {
                tail.fill(0);
            }
            return Some(d_type);
        }
    }
}

impl Drop for HostDir {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            // SAFETY: owns DIR* from fdopendir.
            unsafe {
                let _ = libc::closedir(self.ptr);
            }
            self.ptr = ptr::null_mut();
        }
    }
}

fn last_errno_i32() -> i32 {
    let raw = io::Error::last_os_error()
        .raw_os_error()
        .unwrap_or(1)
        .unsigned_abs();
    i32::try_from(raw).unwrap_or(1)
}