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    let env_owned = [
113        "PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin".to_owned(),
114        "HOME=/var/root".to_owned(),
115        "TMPDIR=/tmp".to_owned(),
116    ];
117    let env_refs: Vec<&str> = env_owned.iter().map(String::as_str).collect();
118
119    let stack_base = stack.guest_addr;
120    let sp = bootstrap_stack(stack.host_bytes_mut(), stack_base, &argv_refs, &env_refs)
121        .map_err(|err| LoadError::NotImplemented(stack_err_static(&err)))?;
122
123    // Build process address space, then install for trap-path checks / mmap bookkeeping.
124    // Hypercall NEON tramp is mapped separately (once, process-local); residual `svc`→`brk`
125    // needs the registry only for later mmap bookkeeping and SIGTRAP translation.
126    let mut address_space = AddressSpace::new();
127    for img in session.images() {
128        if let Some(memory) = img.memory.as_ref() {
129            for region in memory.regions() {
130                address_space.register_borrowed(region);
131            }
132        }
133    }
134    address_space.register_borrowed(&stack);
135    drop(registry_install(address_space));
136
137    // Wire freestanding libSystem → `kh_hypercall_entry` (production path).
138    // Opt out with `KAKEHASHI_HYPERCALL=0|false|off|no` (debug: residual svc→brk).
139    let hypercall_wired = if hypercall_enabled() {
140        install_libsystem_hypercall(&mut session)
141    } else {
142        false
143    };
144    // Rewrite any leftover Darwin `svc` so Linux never executes them as host syscalls.
145    let mut patched_svc = 0usize;
146    for memory in session.mapped_memories_mut() {
147        patched_svc = patched_svc
148            .saturating_add(patch_svc_to_brk(memory.regions_mut()).map_err(trap_to_load)?);
149    }
150
151    install_trap_handlers(&TrapConfig {
152        max_events: opts.max_events,
153        max_syscalls: opts.max_syscalls,
154    })
155    .map_err(trap_to_load)?;
156
157    // Main-thread guest TLS (TPIDR_EL0) before constructors / LC_MAIN touch errno.
158    let main_tls = install_main_guest_tls();
159    if main_tls != 0 {
160        tracing::debug!(
161            main_tls = format_args!("{main_tls:#x}"),
162            "installed main guest TLS (TPIDR_EL0)"
163        );
164    }
165
166    // dyld-order: constructors (dylibs bottom-up, then main) before LC_MAIN.
167    let initializers_run = init::run_initializers(&session, sp)?;
168
169    tracing::info!(
170        entry = format_args!("{entry:#x}"),
171        sp = format_args!("{sp:#x}"),
172        slide,
173        patched_svc,
174        hypercall_wired,
175        main_tls = format_args!("{main_tls:#x}"),
176        initializers_run,
177        images = session.images().len(),
178        root = ?opts.root,
179        "jumping to guest entry"
180    );
181
182    // Darwin `main(argc, argv, envp, apple)` register setup from the stack image:
183    //   [sp+0] = argc, [sp+8] = argv[0], …, NULL, envp…, NULL, apple NULL.
184    let argc = u64::try_from(argv_owned.len()).unwrap_or(0);
185    let argv_ptr = sp.wrapping_add(8);
186    let envp_ptr = argv_ptr.wrapping_add(argc.saturating_add(1).saturating_mul(8));
187    let apple_ptr = envp_ptr.wrapping_add(8); // empty env → envp NULL then apple NULL
188
189    // Keep stack / session alive across the call (may noreturn via guest exit).
190    // `forget` retains all GuestMemory owners if exit traps.
191    std::mem::forget(stack);
192    std::mem::forget(session);
193
194    // SAFETY: image is mapped RX, entry points into __TEXT, stack is bootstrapped,
195    // trap handlers installed for Linux aarch64. Uses `blr` so `return` from
196    // `main` resumes the host (dyld-equivalent); guest `exit` still `_exit`s.
197    let status = unsafe {
198        call_guest_args(entry, sp, argc, argv_ptr, envp_ptr, apple_ptr)
199            .map_err(|err| LoadError::PageLayout(err.to_string()))?
200    };
201
202    // dyld: exit(main(...)). Low 32 bits as signed process status (Darwin int).
203    let low = u32::try_from(status & 0xffff_ffff).unwrap_or(0);
204    let code = i32::from_ne_bytes(low.to_ne_bytes());
205    finish_with_exit_code(code);
206}
207
208fn stack_err_static(err: &kh_runtime::StackError) -> &'static str {
209    match err {
210        kh_runtime::StackError::TooSmall { .. } => "guest stack too small",
211        kh_runtime::StackError::InvalidString => "invalid stack string",
212    }
213}
214
215fn trap_to_load(err: TrapError) -> LoadError {
216    match err {
217        TrapError::Map(map_err) => LoadError::Map(map_err),
218        TrapError::UnsupportedArch => LoadError::PageLayout(
219            "trap backend requires Linux aarch64 for live execution".to_owned(),
220        ),
221        TrapError::SignalSetup(io_err) => {
222            LoadError::PageLayout(format!("trap signal setup: {io_err}"))
223        }
224    }
225}
226
227/// Freestanding libSystem hypercall is on by default (avoids SIGTRAP).
228///
229/// Disable with `KAKEHASHI_HYPERCALL=0|false|off|no`.
230fn hypercall_enabled() -> bool {
231    match std::env::var_os("KAKEHASHI_HYPERCALL") {
232        None => true,
233        Some(v) => {
234            !(v == "0"
235                || v.eq_ignore_ascii_case("false")
236                || v.eq_ignore_ascii_case("no")
237                || v.eq_ignore_ascii_case("off"))
238        }
239    }
240}
241
242/// Point freestanding `libSystem`'s `_kh_bsd_hypercall` at host dispatch.
243///
244/// Returns whether the slot was found and written. On non-Linux hosts this is a
245/// no-op (`false`).
246fn install_libsystem_hypercall(session: &mut LoadSession) -> bool {
247    #[cfg(not(all(target_arch = "aarch64", target_os = "linux")))]
248    {
249        let _ = session;
250        false
251    }
252    #[cfg(all(target_arch = "aarch64", target_os = "linux"))]
253    {
254        install_libsystem_hypercall_linux(session)
255    }
256}
257
258#[cfg(all(target_arch = "aarch64", target_os = "linux"))]
259fn install_libsystem_hypercall_linux(session: &mut LoadSession) -> bool {
260    // Freestanding thin call → host alt stack + NEON tramp + dispatch.
261    let entry_u64 = kh_runtime::hypercall_entry_addr();
262    if entry_u64 == 0 {
263        return false;
264    }
265
266    let mut wired_entry = false;
267    for img in session.images_mut() {
268        let slide = img.slide();
269        let exports: Vec<_> = img.exports.clone();
270        for exp in exports {
271            let slot = exp.name.as_str();
272            if slot != "_kh_bsd_hypercall" && slot != "kh_bsd_hypercall" {
273                continue;
274            }
275            let va = exp.value.saturating_add(slide);
276            if !write_libsystem_u64(img, va, entry_u64) {
277                continue;
278            }
279            wired_entry = true;
280            tracing::info!(
281                va = format_args!("{va:#x}"),
282                entry = format_args!("{entry_u64:#x}"),
283                "wired libSystem BSD hypercall"
284            );
285        }
286    }
287    wired_entry
288}
289
290/// Write 8 little-endian bytes at guest VA in an image mapping (mprotect if needed).
291#[cfg(all(target_arch = "aarch64", target_os = "linux"))]
292fn write_libsystem_u64(img: &mut crate::session::ProcessImage, va: u64, value: u64) -> bool {
293    let Some(memory) = img.memory.as_mut() else {
294        return false;
295    };
296    let Some(region_idx) = memory.regions().iter().position(|region| {
297        let start = region.guest_addr;
298        let end = start.saturating_add(u64::try_from(region.host_len()).unwrap_or(0));
299        va >= start && va.saturating_add(8) <= end
300    }) else {
301        return false;
302    };
303    let Some(region) = memory.regions().get(region_idx) else {
304        return false;
305    };
306    let old_prot = region.prot;
307    let need_rw = old_prot & VM_PROT_WRITE == 0;
308    if need_rw {
309        let Some(region) = memory.regions_mut().get_mut(region_idx) else {
310            return false;
311        };
312        if mprotect_rw(region).is_err() {
313            return false;
314        }
315    }
316    let ok = memory.write_u64_le(va, value).is_some();
317    if need_rw {
318        let mut restore = (old_prot | VM_PROT_READ) & !VM_PROT_WRITE;
319        if old_prot & VM_PROT_EXECUTE != 0 {
320            restore |= VM_PROT_EXECUTE;
321        }
322        if let Some(region) = memory.regions_mut().get_mut(region_idx) {
323            drop(mprotect_darwin(region, restore));
324            region.prot = restore;
325        }
326    }
327    ok
328}