Skip to main content

kh_loader/
execute.rs

1//! Micro execution: map, patch traps, bootstrap stack, jump to entry.
2#![allow(unsafe_code)]
3
4use std::path::{Path, PathBuf};
5
6use kh_runtime::{
7    AddressSpace, GuestPageSize, TrapConfig, TrapError, TrapEvent, bootstrap_stack,
8    call_guest_args, finish_with_exit_code, install_main_guest_tls, install_trap_handlers,
9    map_stack, patch_svc_to_brk, registry_install, registry_take, set_bottle_root,
10};
11#[cfg(all(target_arch = "aarch64", target_os = "linux"))]
12use kh_runtime::{VM_PROT_EXECUTE, VM_PROT_READ, VM_PROT_WRITE, mprotect_darwin, mprotect_rw};
13
14use crate::error::LoadError;
15use crate::init;
16use crate::session::LoadSession;
17
18/// Default guest stack size for the micro spike (1 MiB).
19/// Guest stack for micro execution (8 MiB — C++ guests like `7zz` use deep frames).
20pub const DEFAULT_STACK_SIZE: u64 = 8 * 1024 * 1024;
21
22/// Options for a micro run / trace.
23#[derive(Debug, Clone)]
24pub struct RunOptions {
25    /// Bottle root (`KAKEHASHI_ROOT` / `--root`) for path translation.
26    pub root: Option<PathBuf>,
27    /// Guest page size policy.
28    pub guest_page_size: GuestPageSize,
29    /// Guest argv (not including argv0 = executable path — that is prepended).
30    pub guest_args: Vec<String>,
31    /// Maximum trap events to retain.
32    pub max_events: usize,
33    /// Maximum syscalls before forced process exit.
34    pub max_syscalls: usize,
35    /// When true, only map (caller should use [`LoadSession::dry_load`] instead).
36    pub dry_load: bool,
37}
38
39impl Default for RunOptions {
40    fn default() -> Self {
41        Self {
42            root: None,
43            guest_page_size: GuestPageSize::default(),
44            guest_args: Vec::new(),
45            max_events: 256,
46            max_syscalls: 256,
47            dry_load: false,
48        }
49    }
50}
51
52/// Result of a completed micro run (when the host does not process-exit).
53#[derive(Debug)]
54pub struct RunResult {
55    /// Exit code if the guest called `exit` without `_exit` from the handler.
56    pub exit_code: Option<i32>,
57    /// Captured trap events (empty if process already exited).
58    pub events: Vec<TrapEvent>,
59    /// Number of `svc` instructions patched to `brk`.
60    pub patched_svc: usize,
61    /// Entry VA used for the jump.
62    pub entry: u64,
63    /// Stack pointer passed to the guest.
64    pub sp: u64,
65    /// Applied **main** image slide.
66    pub slide: u64,
67    /// Number of `mod_init` functions invoked before main.
68    pub initializers_run: usize,
69}
70
71/// Maps, patches, and transfers control to the guest entry.
72///
73/// On a successful guest `exit`, this function **does not return**: the trap
74/// handler terminates the process with the guest status.
75pub fn run_micro(path: &Path, opts: &RunOptions) -> Result<RunResult, LoadError> {
76    if opts.dry_load {
77        return Err(LoadError::NotImplemented(
78            "run_micro: use LoadSession::dry_load for --dry-load",
79        ));
80    }
81
82    set_bottle_root(opts.root.clone());
83    // Drop any previous active address space (unmaps owned guest mmaps).
84    drop(registry_take());
85
86    let mut session = LoadSession::open_with_guest(path, opts.root.clone(), opts.guest_page_size)?;
87    let _ = session.map_process()?;
88
89    let slide = session
90        .images()
91        .first()
92        .map_or(0, crate::session::ProcessImage::slide);
93    let entry = session
94        .entry_va()
95        .ok_or(LoadError::NotImplemented("image has no entry point"))?;
96
97    let host = session
98        .images()
99        .first()
100        .and_then(|img| img.memory.as_ref())
101        .map(kh_runtime::GuestMemory::host)
102        .ok_or(LoadError::NotImplemented("memory missing"))?;
103
104    let mut stack = map_stack(host, DEFAULT_STACK_SIZE)?;
105
106    let argv0 = path.file_name().and_then(|s| s.to_str()).unwrap_or("guest");
107    let mut argv_owned = Vec::with_capacity(opts.guest_args.len().saturating_add(1));
108    argv_owned.push(argv0.to_owned());
109    argv_owned.extend(opts.guest_args.iter().cloned());
110    let argv_refs: Vec<&str> = argv_owned.iter().map(String::as_str).collect();
111    // Minimal macOS-like environment so guests see a real PATH under the bottle.
112    // HOME bridges the host home via `/Volumes/linux…` so host
113    // `git config --global` (and `~/.gitconfig`) is visible to Apple git under
114    // `kh run`. Fall back to bottle `/var/root` when host HOME is unset/odd.
115    let home = guest_home_env();
116    let env_owned = [
117        "PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin".to_owned(),
118        home,
119        "TMPDIR=/tmp".to_owned(),
120    ];
121    let env_refs: Vec<&str> = env_owned.iter().map(String::as_str).collect();
122
123    let stack_base = stack.guest_addr;
124    let sp = bootstrap_stack(stack.host_bytes_mut(), stack_base, &argv_refs, &env_refs)
125        .map_err(|err| LoadError::NotImplemented(stack_err_static(&err)))?;
126
127    // Build process address space, then install for trap-path checks / mmap bookkeeping.
128    // Hypercall NEON tramp is mapped separately (once, process-local); residual `svc`→`brk`
129    // needs the registry only for later mmap bookkeeping and SIGTRAP translation.
130    let mut address_space = AddressSpace::new();
131    for img in session.images() {
132        if let Some(memory) = img.memory.as_ref() {
133            for region in memory.regions() {
134                address_space.register_borrowed(region);
135            }
136        }
137    }
138    address_space.register_borrowed(&stack);
139    drop(registry_install(address_space));
140
141    // Wire freestanding libSystem → `kh_hypercall_entry` (production path).
142    // Opt out with `KAKEHASHI_HYPERCALL=0|false|off|no` (debug: residual svc→brk).
143    let hypercall_wired = if hypercall_enabled() {
144        install_libsystem_hypercall(&mut session)
145    } else {
146        false
147    };
148    // Rewrite any leftover Darwin `svc` so Linux never executes them as host syscalls.
149    let mut patched_svc = 0usize;
150    for memory in session.mapped_memories_mut() {
151        patched_svc = patched_svc
152            .saturating_add(patch_svc_to_brk(memory.regions_mut()).map_err(trap_to_load)?);
153    }
154
155    install_trap_handlers(&TrapConfig {
156        max_events: opts.max_events,
157        max_syscalls: opts.max_syscalls,
158    })
159    .map_err(trap_to_load)?;
160
161    // Main-thread guest TLS (TPIDR_EL0) before constructors / LC_MAIN touch errno.
162    let main_tls = install_main_guest_tls();
163    if main_tls != 0 {
164        tracing::debug!(
165            main_tls = format_args!("{main_tls:#x}"),
166            "installed main guest TLS (TPIDR_EL0)"
167        );
168    }
169
170    // dyld-order: constructors (dylibs bottom-up, then main) before LC_MAIN.
171    let initializers_run = init::run_initializers(&session, sp)?;
172
173    tracing::info!(
174        entry = format_args!("{entry:#x}"),
175        sp = format_args!("{sp:#x}"),
176        slide,
177        patched_svc,
178        hypercall_wired,
179        main_tls = format_args!("{main_tls:#x}"),
180        initializers_run,
181        images = session.images().len(),
182        root = ?opts.root,
183        "jumping to guest entry"
184    );
185
186    // Darwin `main(argc, argv, envp, apple)` register setup from the stack image:
187    //   [sp+0] = argc, [sp+8] = argv[0], …, NULL, envp…, NULL, apple NULL.
188    let argc = u64::try_from(argv_owned.len()).unwrap_or(0);
189    let argv_ptr = sp.wrapping_add(8);
190    let envp_ptr = argv_ptr.wrapping_add(argc.saturating_add(1).saturating_mul(8));
191    let apple_ptr = envp_ptr.wrapping_add(8); // empty env → envp NULL then apple NULL
192
193    // Keep stack / session alive across the call (may noreturn via guest exit).
194    // `forget` retains all GuestMemory owners if exit traps.
195    std::mem::forget(stack);
196    std::mem::forget(session);
197
198    // SAFETY: image is mapped RX, entry points into __TEXT, stack is bootstrapped,
199    // trap handlers installed for Linux aarch64. Uses `blr` so `return` from
200    // `main` resumes the host (dyld-equivalent); guest `exit` still `_exit`s.
201    let status = unsafe {
202        call_guest_args(entry, sp, argc, argv_ptr, envp_ptr, apple_ptr)
203            .map_err(|err| LoadError::PageLayout(err.to_string()))?
204    };
205
206    // dyld: exit(main(...)). Low 32 bits as signed process status (Darwin int).
207    let low = u32::try_from(status & 0xffff_ffff).unwrap_or(0);
208    let code = i32::from_ne_bytes(low.to_ne_bytes());
209    finish_with_exit_code(code);
210}
211
212fn stack_err_static(err: &kh_runtime::StackError) -> &'static str {
213    match err {
214        kh_runtime::StackError::TooSmall { .. } => "guest stack too small",
215        kh_runtime::StackError::InvalidString => "invalid stack string",
216    }
217}
218
219/// Guest `HOME=…` for the bootstrap env block.
220///
221/// Prefer host `$HOME` under the `/Volumes/linux` bridge so tools that honour
222/// global config (Apple `git` → `~/.gitconfig`) see the same files as host CLI
223/// config commands. Falls back to bottle `/var/root`.
224fn guest_home_env() -> String {
225    match std::env::var("HOME") {
226        Ok(h) if h.starts_with('/') && !h.contains('\0') => {
227            format!("HOME=/Volumes/linux{h}")
228        }
229        _ => "HOME=/var/root".to_owned(),
230    }
231}
232
233fn trap_to_load(err: TrapError) -> LoadError {
234    match err {
235        TrapError::Map(map_err) => LoadError::Map(map_err),
236        TrapError::UnsupportedArch => LoadError::PageLayout(
237            "trap backend requires Linux aarch64 for live execution".to_owned(),
238        ),
239        TrapError::SignalSetup(io_err) => {
240            LoadError::PageLayout(format!("trap signal setup: {io_err}"))
241        }
242    }
243}
244
245/// Freestanding libSystem hypercall is on by default (avoids SIGTRAP).
246///
247/// Disable with `KAKEHASHI_HYPERCALL=0|false|off|no`.
248fn hypercall_enabled() -> bool {
249    match std::env::var_os("KAKEHASHI_HYPERCALL") {
250        None => true,
251        Some(v) => {
252            !(v == "0"
253                || v.eq_ignore_ascii_case("false")
254                || v.eq_ignore_ascii_case("no")
255                || v.eq_ignore_ascii_case("off"))
256        }
257    }
258}
259
260/// Point freestanding `libSystem`'s `_kh_bsd_hypercall` at host dispatch.
261///
262/// Returns whether the slot was found and written. On non-Linux hosts this is a
263/// no-op (`false`).
264fn install_libsystem_hypercall(session: &mut LoadSession) -> bool {
265    #[cfg(not(all(target_arch = "aarch64", target_os = "linux")))]
266    {
267        let _ = session;
268        false
269    }
270    #[cfg(all(target_arch = "aarch64", target_os = "linux"))]
271    {
272        install_libsystem_hypercall_linux(session)
273    }
274}
275
276#[cfg(all(target_arch = "aarch64", target_os = "linux"))]
277fn install_libsystem_hypercall_linux(session: &mut LoadSession) -> bool {
278    // Freestanding thin call → host alt stack + NEON tramp + dispatch.
279    let entry_u64 = kh_runtime::hypercall_entry_addr();
280    if entry_u64 == 0 {
281        return false;
282    }
283
284    let mut wired_entry = false;
285    for img in session.images_mut() {
286        let slide = img.slide();
287        let exports: Vec<_> = img.exports.clone();
288        for exp in exports {
289            let slot = exp.name.as_str();
290            if slot != "_kh_bsd_hypercall" && slot != "kh_bsd_hypercall" {
291                continue;
292            }
293            let va = exp.value.saturating_add(slide);
294            if !write_libsystem_u64(img, va, entry_u64) {
295                continue;
296            }
297            wired_entry = true;
298            tracing::info!(
299                va = format_args!("{va:#x}"),
300                entry = format_args!("{entry_u64:#x}"),
301                "wired libSystem BSD hypercall"
302            );
303        }
304    }
305    wired_entry
306}
307
308/// Write 8 little-endian bytes at guest VA in an image mapping (mprotect if needed).
309#[cfg(all(target_arch = "aarch64", target_os = "linux"))]
310fn write_libsystem_u64(img: &mut crate::session::ProcessImage, va: u64, value: u64) -> bool {
311    let Some(memory) = img.memory.as_mut() else {
312        return false;
313    };
314    let Some(region_idx) = memory.regions().iter().position(|region| {
315        let start = region.guest_addr;
316        let end = start.saturating_add(u64::try_from(region.host_len()).unwrap_or(0));
317        va >= start && va.saturating_add(8) <= end
318    }) else {
319        return false;
320    };
321    let Some(region) = memory.regions().get(region_idx) else {
322        return false;
323    };
324    let old_prot = region.prot;
325    let need_rw = old_prot & VM_PROT_WRITE == 0;
326    if need_rw {
327        let Some(region) = memory.regions_mut().get_mut(region_idx) else {
328            return false;
329        };
330        if mprotect_rw(region).is_err() {
331            return false;
332        }
333    }
334    let ok = memory.write_u64_le(va, value).is_some();
335    if need_rw {
336        let mut restore = (old_prot | VM_PROT_READ) & !VM_PROT_WRITE;
337        if old_prot & VM_PROT_EXECUTE != 0 {
338            restore |= VM_PROT_EXECUTE;
339        }
340        if let Some(region) = memory.regions_mut().get_mut(region_idx) {
341            drop(mprotect_darwin(region, restore));
342            region.prot = restore;
343        }
344    }
345    ok
346}