kh-runtime 0.1.14

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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! Host OS primitives and fat Mach-O helpers.
//!
//! 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)]

pub mod fat_thin;

use std::fs::File;
use std::io;
use std::os::fd::{AsRawFd, RawFd};
use std::path::Path;
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) }
}

/// `dup2(old, new)` on the host. Returns `new` or `None` on failure.
#[must_use]
pub fn dup2_fd(old: RawFd, new: RawFd) -> Option<RawFd> {
    // SAFETY: both fds are valid host descriptors for the duration of the call.
    let rc = unsafe { libc::dup2(old, new) };
    if rc < 0 { None } else { Some(rc) }
}

/// Host `fork`. Returns `Ok(pid)` where pid is 0 in the child, or `Err(errno)`.
pub fn fork_process() -> Result<i32, i32> {
    // SAFETY: Linux fork; only the calling thread is duplicated.
    let rc = unsafe { libc::fork() };
    if rc < 0 {
        Err(last_errno())
    } else {
        Ok(rc)
    }
}

/// Host `waitpid`. Returns `(pid, status)` or `Err(errno)`. `pid == 0` with
/// `WNOHANG` means no child ready.
pub fn wait_pid(pid: i32, options: i32) -> Result<(i32, i32), i32> {
    let mut status: libc::c_int = 0;
    // SAFETY: status is stack-local; waitpid is well-defined.
    let rc = unsafe { libc::waitpid(pid, &raw mut status, options) };
    if rc < 0 {
        Err(last_errno())
    } else {
        Ok((rc, status))
    }
}

/// Host `execve` with owned C strings (never returns on success).
///
/// # Safety
///
/// `argv` and `envp` must be NULL-terminated arrays of valid C strings; this
/// process image is replaced on success.
pub unsafe fn execve_host(
    path: &std::ffi::CStr,
    argv: &[*const libc::c_char],
    envp: &[*const libc::c_char],
) -> i32 {
    // SAFETY: caller guarantees NUL-terminated argv/envp; path is a CStr.
    let rc = unsafe { libc::execve(path.as_ptr(), argv.as_ptr().cast(), envp.as_ptr().cast()) };
    let _ = rc;
    last_errno()
}

/// Host `posix_spawn` without forking this process's address space.
///
/// Prefer this over guest `fork`+`execve` when the parent has large mappings
/// (CLT tools): CoW of a 100+ MiB guest image is pure tax before the child
/// replaces itself with nested `kh`.
///
/// # Safety
///
/// `argv` / `envp` must be NULL-terminated C string pointer arrays (as for
/// `execve`). On success returns the child pid; on failure returns `Err(errno)`.
pub unsafe fn posix_spawn_host(
    path: &std::ffi::CStr,
    argv: &[*const libc::c_char],
    envp: &[*const libc::c_char],
) -> Result<i32, i32> {
    let mut pid: libc::pid_t = 0;
    // Linux libc wants `*const *mut c_char`; our slices are `*const *const`.
    // SAFETY: argv/envp are live NUL-terminated arrays for the duration of the call.
    let rc = unsafe {
        libc::posix_spawn(
            &raw mut pid,
            path.as_ptr(),
            core::ptr::null(),
            core::ptr::null(),
            argv.as_ptr().cast_mut().cast(),
            envp.as_ptr().cast_mut().cast(),
        )
    };
    if rc != 0 {
        Err(rc)
    } else {
        Ok(pid)
    }
}

fn last_errno() -> i32 {
    io::Error::last_os_error()
        .raw_os_error()
        .unwrap_or(libc::EIO)
}

fn socklen_of(len: usize) -> Option<libc::socklen_t> {
    libc::socklen_t::try_from(len).ok()
}

/// `pipe(2)` — returns `(read_fd, write_fd)` or `None` on failure.
///
/// Both ends are set `O_NONBLOCK|O_CLOEXEC`. Freestanding curl/c-ares often
/// `poll` then `read` the wakeup pipe; a **blocking** host pipe deadlocks the
/// single-threaded guest when nothing is readable yet (tier1 hang).
///
/// Darwin default is blocking; guest-visible semantics are tracked in
/// [`crate::process::fd_guest_nonblock`]. I/O waits on `EAGAIN` until the guest
/// sets `O_NONBLOCK` via `fcntl`. Nested helpers also call
/// [`crate::process::normalize_stdio_pipes_blocking`] so inherited command
/// pipes behave as Darwin blocking stdin/stdout.
#[must_use]
pub fn pipe_fds() -> Option<(RawFd, RawFd)> {
    let mut fds = [0_i32; 2];
    // Prefer pipe2 when available (Linux).
    #[cfg(target_os = "linux")]
    {
        // SAFETY: stack buffer of two ints for the kernel to fill.
        let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) };
        if rc != 0 {
            return None;
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        // SAFETY: stack buffer of two ints for the kernel to fill.
        let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
        if rc != 0 {
            return None;
        }
        for fd in fds {
            set_nonblock(fd);
            // SAFETY: freshly created pipe ends.
            unsafe {
                let _ = libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
            }
        }
    }
    match (fds.first().copied(), fds.get(1).copied()) {
        (Some(r), Some(w)) => Some((r, w)),
        _ => None,
    }
}

/// Block until `fd` is readable, hung-up, or errored. `timeout_ms` as in
/// `poll(2)` (`-1` = forever). Returns `true` if any interesting revent.
#[must_use]
pub fn poll_fd_readable(fd: RawFd, timeout_ms: i32) -> bool {
    poll_fd(fd, libc::POLLIN, timeout_ms)
}

/// Block until `fd` is writable, hung-up, or errored.
#[must_use]
pub fn poll_fd_writable(fd: RawFd, timeout_ms: i32) -> bool {
    poll_fd(fd, libc::POLLOUT, timeout_ms)
}

/// Block until `fd` is readable **or** writable (TLS may need both).
#[must_use]
pub fn poll_fd_io(fd: RawFd, timeout_ms: i32) -> bool {
    poll_fd(fd, libc::POLLIN | libc::POLLOUT, timeout_ms)
}

fn poll_fd(fd: RawFd, events: libc::c_short, timeout_ms: i32) -> bool {
    let mut pfd = libc::pollfd {
        fd,
        events,
        revents: 0,
    };
    loop {
        // SAFETY: single pollfd on the stack; fd is a live host descriptor.
        let rc = unsafe { libc::poll(&raw mut pfd, 1, timeout_ms) };
        if rc < 0 {
            let err = io::Error::last_os_error()
                .raw_os_error()
                .unwrap_or(0);
            if err == libc::EINTR {
                continue;
            }
            return false;
        }
        if rc == 0 {
            return false;
        }
        let interest = events | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL;
        return pfd.revents & interest != 0;
    }
}

/// Mark a host fd non-blocking (best-effort).
fn set_nonblock(fd: RawFd) {
    // SAFETY: live fd from socket/accept/pipe.
    unsafe {
        let fl = libc::fcntl(fd, libc::F_GETFL);
        if fl >= 0 {
            let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
        }
    }
}

/// Clear host `O_NONBLOCK` (best-effort). Used for nested-helper stdio pipes.
pub fn clear_nonblock(fd: RawFd) {
    // SAFETY: live fd.
    unsafe {
        let fl = libc::fcntl(fd, libc::F_GETFL);
        if fl >= 0 {
            let _ = libc::fcntl(fd, libc::F_SETFL, fl & !libc::O_NONBLOCK);
        }
    }
}

/// `true` when `fd` is a FIFO/pipe (`S_IFIFO`).
#[must_use]
pub fn fd_is_fifo(fd: RawFd) -> bool {
    // SAFETY: fstat on a live fd.
    unsafe {
        let mut st: libc::stat = core::mem::zeroed();
        if libc::fstat(fd, &raw mut st) != 0 {
            return false;
        }
        (st.st_mode & libc::S_IFMT) == libc::S_IFIFO
    }
}

/// `socket(domain, type, protocol)` — host libc. Returns host fd or `None`.
///
/// Sockets are forced `O_NONBLOCK`. Curl/c-ares (and the multi interface)
/// expect non-blocking I/O; a blocking `recv` on a keep-alive TCP socket after
/// the response body is complete hangs the guest forever (clean-exit G3).
#[must_use]
pub fn socket(domain: libc::c_int, ty: libc::c_int, protocol: libc::c_int) -> Option<RawFd> {
    // SAFETY: standard socket(2). Strip Darwin-only type flags if any sneak in;
    // Linux SOCK_NONBLOCK/CLOEXEC bits differ and are applied via fcntl below.
    let ty_plain = ty & 0xf;
    let rc = unsafe { libc::socket(domain, ty_plain, protocol) };
    if rc < 0 {
        return None;
    }
    set_nonblock(rc);
    // SAFETY: freshly created socket.
    unsafe {
        let _ = libc::fcntl(rc, libc::F_SETFD, libc::FD_CLOEXEC);
    }
    Some(rc)
}

/// `socketpair(domain, type, protocol, sv[2])`.
pub fn socketpair(
    domain: libc::c_int,
    ty: libc::c_int,
    protocol: libc::c_int,
) -> Option<(RawFd, RawFd)> {
    let mut sv = [0_i32; 2];
    let ty_plain = ty & 0xf;
    // SAFETY: stack pair for the kernel to fill.
    let rc = unsafe { libc::socketpair(domain, ty_plain, protocol, sv.as_mut_ptr()) };
    if rc != 0 {
        return None;
    }
    set_nonblock(sv[0]);
    set_nonblock(sv[1]);
    // SAFETY: freshly created sockets.
    unsafe {
        let _ = libc::fcntl(sv[0], libc::F_SETFD, libc::FD_CLOEXEC);
        let _ = libc::fcntl(sv[1], libc::F_SETFD, libc::FD_CLOEXEC);
    }
    Some((sv[0], sv[1]))
}

/// `connect(fd, sockaddr_bytes)`.
pub fn connect(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
    let Some(len) = socklen_of(addr.len()) else {
        return Err(libc::EINVAL);
    };
    // SAFETY: `addr` is a valid host buffer for `len` bytes.
    let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), len) };
    if rc == 0 { Ok(()) } else { Err(last_errno()) }
}

/// `bind(fd, sockaddr_bytes)`.
pub fn bind(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
    let Some(len) = socklen_of(addr.len()) else {
        return Err(libc::EINVAL);
    };
    // SAFETY: `addr` is a valid host buffer for `len` bytes.
    let rc = unsafe { libc::bind(fd, addr.as_ptr().cast(), len) };
    if rc == 0 { Ok(()) } else { Err(last_errno()) }
}

/// `listen(fd, backlog)`.
pub fn listen(fd: RawFd, backlog: libc::c_int) -> Result<(), i32> {
    // SAFETY: live socket fd.
    let rc = unsafe { libc::listen(fd, backlog) };
    if rc == 0 { Ok(()) } else { Err(last_errno()) }
}

/// `accept(fd)` — peer address discarded (curl client path rarely needs it).
pub fn accept(fd: RawFd) -> Result<RawFd, i32> {
    // SAFETY: live listening socket; null addr is allowed by accept(2).
    let rc = unsafe { libc::accept(fd, ptr::null_mut(), ptr::null_mut()) };
    if rc < 0 {
        Err(last_errno())
    } else {
        set_nonblock(rc);
        Ok(rc)
    }
}

/// `accept` with peer sockaddr written into `addr_out` (truncated to buffer len).
///
/// Returns `(new_fd, bytes_written_into_addr_out)`.
pub fn accept_addr(fd: RawFd, addr_out: &mut [u8]) -> Result<(RawFd, usize), i32> {
    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
    // SAFETY: live socket; `addr_out` is writable for `alen` bytes.
    let rc = unsafe {
        libc::accept(
            fd,
            addr_out.as_mut_ptr().cast(),
            ptr::addr_of_mut!(alen),
        )
    };
    if rc < 0 {
        return Err(last_errno());
    }
    set_nonblock(rc);
    let n = usize::try_from(alen).unwrap_or(0).min(addr_out.len());
    Ok((rc, n))
}

/// `setsockopt(fd, level, optname, value_bytes)`.
pub fn setsockopt(
    fd: RawFd,
    level: libc::c_int,
    optname: libc::c_int,
    value: &[u8],
) -> Result<(), i32> {
    let Some(len) = socklen_of(value.len()) else {
        return Err(libc::EINVAL);
    };
    // SAFETY: live socket; value buffer valid for `len` bytes.
    let rc = unsafe {
        libc::setsockopt(
            fd,
            level,
            optname,
            value.as_ptr().cast(),
            len,
        )
    };
    if rc == 0 { Ok(()) } else { Err(last_errno()) }
}

/// `getsockopt` — writes into `value`, returns updated length.
pub fn getsockopt(
    fd: RawFd,
    level: libc::c_int,
    optname: libc::c_int,
    value: &mut [u8],
) -> Result<usize, i32> {
    let mut len = socklen_of(value.len()).unwrap_or(0);
    // SAFETY: live socket; value buffer writable.
    let rc = unsafe {
        libc::getsockopt(
            fd,
            level,
            optname,
            value.as_mut_ptr().cast(),
            ptr::addr_of_mut!(len),
        )
    };
    if rc == 0 {
        Ok(usize::try_from(len).unwrap_or(0).min(value.len()))
    } else {
        Err(last_errno())
    }
}

/// `shutdown(fd, how)`.
pub fn shutdown(fd: RawFd, how: libc::c_int) -> Result<(), i32> {
    // SAFETY: live socket fd.
    let rc = unsafe { libc::shutdown(fd, how) };
    if rc == 0 { Ok(()) } else { Err(last_errno()) }
}

/// `sendto` / `send` — optional peer address bytes.
pub fn sendto(
    fd: RawFd,
    buf: &[u8],
    flags: libc::c_int,
    addr: Option<&[u8]>,
) -> Result<usize, i32> {
    let (ap, alen) = if let Some(a) = addr {
        let Some(len) = socklen_of(a.len()) else {
            return Err(libc::EINVAL);
        };
        (a.as_ptr().cast(), len)
    } else {
        (ptr::null(), 0)
    };
    // SAFETY: live fd; buffer valid; optional sockaddr.
    let n = unsafe { libc::sendto(fd, buf.as_ptr().cast(), buf.len(), flags, ap, alen) };
    if n < 0 {
        Err(last_errno())
    } else {
        usize::try_from(n).map_err(|_| libc::EIO)
    }
}

/// `recvfrom` / `recv` — optional peer address out-buffer.
///
/// Returns `(bytes_read, peer_addr_len)` when `addr_out` is `Some`.
pub fn recvfrom(
    fd: RawFd,
    buf: &mut [u8],
    flags: libc::c_int,
    addr_out: Option<&mut [u8]>,
) -> Result<(usize, usize), i32> {
    let (n, peer_len) = if let Some(a) = addr_out {
        let mut alen = socklen_of(a.len()).unwrap_or(0);
        // SAFETY: live fd; buffers valid.
        let n = unsafe {
            libc::recvfrom(
                fd,
                buf.as_mut_ptr().cast(),
                buf.len(),
                flags,
                a.as_mut_ptr().cast(),
                ptr::addr_of_mut!(alen),
            )
        };
        (n, usize::try_from(alen).unwrap_or(0).min(a.len()))
    } else {
        // SAFETY: live fd; buffer valid; null peer.
        let n = unsafe {
            libc::recvfrom(
                fd,
                buf.as_mut_ptr().cast(),
                buf.len(),
                flags,
                ptr::null_mut(),
                ptr::null_mut(),
            )
        };
        (n, 0)
    };
    if n < 0 {
        Err(last_errno())
    } else {
        let nr = usize::try_from(n).map_err(|_| libc::EIO)?;
        Ok((nr, peer_len))
    }
}

/// `getsockname(fd, addr_out)`.
pub fn getsockname(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
    // SAFETY: live socket; buffer writable for `alen` bytes.
    let rc = unsafe {
        libc::getsockname(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
    };
    if rc == 0 {
        Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
    } else {
        Err(last_errno())
    }
}

/// `getpeername(fd, addr_out)`.
pub fn getpeername(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
    let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
    // SAFETY: live socket; buffer writable for `alen` bytes.
    let rc = unsafe {
        libc::getpeername(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
    };
    if rc == 0 {
        Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
    } else {
        Err(last_errno())
    }
}

/// `poll(fds, timeout_ms)` — empty slice sleeps / checks timeout only.
pub fn poll(fds: &mut [libc::pollfd], timeout: libc::c_int) -> Result<i32, i32> {
    let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
    // SAFETY: `fds` is a valid pollfd array of `nfds` entries (or empty).
    let rc = unsafe {
        libc::poll(
            if fds.is_empty() {
                ptr::null_mut()
            } else {
                fds.as_mut_ptr()
            },
            nfds,
            timeout,
        )
    };
    if rc < 0 { Err(last_errno()) } else { Ok(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) }
}

/// Open a directory as `O_RDONLY|O_DIRECTORY|O_CLOEXEC` (bottle root dirfd, B1).
pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
    open_path(
        path,
        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
        0,
    )
}

/// `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) }
}

/// `mkdirat(dirfd, path, mode)` — returns `Ok(())` on success or `EEXIST`.
pub fn mkdirat(dirfd: RawFd, path: &std::ffi::CStr, mode: libc::mode_t) -> io::Result<()> {
    // SAFETY: dirfd live; path is a valid C string for the duration of the call.
    let rc = unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) };
    if rc == 0 {
        return Ok(());
    }
    let err = io::Error::last_os_error();
    if err.raw_os_error() == Some(libc::EEXIST) {
        Ok(())
    } else {
        Err(err)
    }
}

/// `fstatat(dirfd, path, …)` — used by B1 bottle-relative `stat`/`lstat`.
pub fn fstatat(dirfd: RawFd, path: &std::ffi::CStr, no_follow: bool) -> Option<libc::stat> {
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    let flags = if no_follow {
        libc::AT_SYMLINK_NOFOLLOW
    } else {
        0
    };
    // SAFETY: dirfd live; path valid C string; stack `stat` buffer.
    let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
    if rc == 0 { Some(st) } else { None }
}

/// `faccessat(dirfd, path, F_OK, 0)` — existence check without full path build.
pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
    // SAFETY: dirfd live; path valid C string.
    let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
    rc == 0
}

/// 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 }
}

/// `fchmod(fd, mode)` — needed so guest `ld` can mark products executable.
pub fn fchmod_fd(fd: RawFd, mode: u32) -> Option<()> {
    let mode = libc::mode_t::try_from(mode).unwrap_or(0);
    // SAFETY: live fd; mode is Darwin permission bits (subset of POSIX).
    let rc = unsafe { libc::fchmod(fd, mode) };
    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 }
}

/// `readlink(path)` into `buf` (no trailing NUL). Returns bytes written or host errno.
pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
    if buf.is_empty() {
        return Ok(0);
    }
    // SAFETY: path is a valid C string; buffer is writable for `buf.len()`.
    let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
    if n < 0 {
        return Err(io::Error::last_os_error()
            .raw_os_error()
            .unwrap_or(libc::EIO));
    }
    usize::try_from(n).map_err(|_| libc::EIO)
}

/// `symlink(target, linkpath)`.
pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
    // SAFETY: both are valid C strings for the duration of the call.
    let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
    if rc == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error()
            .raw_os_error()
            .unwrap_or(libc::EIO))
    }
}

/// `link(existing, newpath)` hard link.
pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
    // SAFETY: both are valid C strings for the duration of the call.
    let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
    if rc == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error()
            .raw_os_error()
            .unwrap_or(libc::EIO))
    }
}

/// 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 }
}

/// Read-only file-backed mapping of an entire file (lazy page faults).
///
/// Used by the loader to parse and fill guest segments without
/// `fs::read` of multi‑hundred‑MiB containers (demand-paged I/O).
///
/// Dropping unmaps the range. Safe for concurrent shared reads only while
/// this owner is alive (not `Sync`; single-threaded load path).
pub struct MappedFile {
    ptr: *mut u8,
    len: usize,
}

impl std::fmt::Debug for MappedFile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MappedFile")
            .field("len", &self.len)
            .finish_non_exhaustive()
    }
}

// SAFETY: unique owner of the mapping; no interior mutation after create.
unsafe impl Send for MappedFile {}

impl MappedFile {
    /// `mmap` the whole file `PROT_READ` / `MAP_PRIVATE`. Empty files yield a
    /// zero-length mapping (`as_slice` is empty).
    pub fn open(path: &Path) -> io::Result<Self> {
        let file = File::open(path)?;
        let len_u64 = file.metadata()?.len();
        let len = usize::try_from(len_u64).map_err(|_| {
            io::Error::new(io::ErrorKind::InvalidData, "file too large to map")
        })?;
        if len == 0 {
            return Ok(Self {
                ptr: ptr::null_mut(),
                len: 0,
            });
        }
        let fd = file.as_raw_fd();
        // Lazy faults: do **not** use MAP_POPULATE — parse only needs headers;
        // segment fill touches only file-backed ranges.
        let Some(base) = mmap(
            None,
            len,
            libc::PROT_READ,
            libc::MAP_PRIVATE,
            fd,
            0,
        ) else {
            return Err(io::Error::last_os_error());
        };
        // Mapping keeps its own reference; fd may close with `file` drop.
        Ok(Self { ptr: base, len })
    }

    /// Byte view of the mapped file (or empty).
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        if self.ptr.is_null() || self.len == 0 {
            return &[];
        }
        // SAFETY: mapping is live, PROT_READ, length is exact file size.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }

    /// Mapped length in bytes.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Whether the file was empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }
}

impl Drop for MappedFile {
    fn drop(&mut self) {
        if !self.ptr.is_null() && self.len > 0 {
            let _ = munmap(self.ptr, self.len);
            self.ptr = ptr::null_mut();
            self.len = 0;
        }
    }
}

/// 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()
}

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

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

// SAFETY: process-wide guest model serializes dir mutation under ProcessState
// write lock; readers never touch `HostDir`.
unsafe impl Send for HostDir {}
// SAFETY: same as `Send` — exclusive dir use under write lock 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: `(name_bytes, d_type)`. `None` at end of stream.
    pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
        use std::ffi::CStr;
        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().to_vec();
            if bytes.is_empty() {
                continue;
            }
            return Some((bytes, 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)
}