From 4489455b5f83360c28c033887b4e9976e703ddc6 Mon Sep 17 00:00:00 2001 From: "Shane B." Date: Fri, 23 Oct 2026 17:06:33 +0200 Subject: [PATCH] Record the emulated Mac's emulator choice, with an offline Unicorn/icicle diff #274 runs Apple's macOS CoreADI under Unicorn, which is GPL-2.0. The decision is to ship it, with a licence notice and the library in its own process, and to swap it only if somebody has a reason to. A swap is invisible to users only if the replacement produces the same bytes, so scripts/adi-emulator-diff/ puts icicle (MIT OR Apache-2.0) under os-findmy-e's adi-core and diffs it against Unicorn. Every offline call matched byte for byte; the OTP path, which needs a provisioned machine, has not been compared. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 8 + CONTRIBUTING.md | 12 + docs/README.md | 1 + docs/emulated-mac-emulator-choice.md | 87 +++++++ scripts/adi-emulator-diff/adi-diff.rs | 71 +++++ scripts/adi-emulator-diff/run.sh | 94 +++++++ scripts/adi-emulator-diff/vm_icicle.rs | 348 +++++++++++++++++++++++++ 7 files changed, 621 insertions(+) create mode 100644 docs/emulated-mac-emulator-choice.md create mode 100644 scripts/adi-emulator-diff/adi-diff.rs create mode 100755 scripts/adi-emulator-diff/run.sh create mode 100644 scripts/adi-emulator-diff/vm_icicle.rs diff --git a/AGENTS.md b/AGENTS.md index 5fe25e58..16ca0ec1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,6 +89,14 @@ python -m venv .venv && .venv/bin/pip install "FindMy==" emulator Chaquopy cannot build for Android. `app/stubs/unicorn/` is a stand-in that makes the dependency tree resolve; every method raises. The stub is not a step toward enabling `aniLocal`, and never will be. +- **Unicorn ships as native code, GPL-2.0 and all, and that was decided rather than missed.** + The emulated Mac (#274, in review) runs it in `libmacadi.so`. Before replacing it with a permissive + emulator for licence reasons, read + [docs/emulated-mac-emulator-choice.md](./docs/emulated-mac-emulator-choice.md): a replacement + is invisible to users **only if it produces the same bytes**, because the emulator is not part + of the machine identity but its output is. `scripts/adi-emulator-diff/` is the check, and it has + not yet been run over the OTP path. The same doc says what the GPL obliges: a notice, and the + library kept in its own process. - **The app does run ADI locally, by a different route.** `app/src/main/java/.../anisette/` loads Apple's real Android ADI libraries in-process and produces Anisette here, falling back to a remote server when it cannot. That is unrelated to `aniLocal` and needs no diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5f6c3407..b4f7dcbf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -856,6 +856,18 @@ python scripts/make_test_beacon_plist.py out.plist --days-old 730 python scripts/make_locked_bundle_fixture.py ``` +### Comparing CPU emulators for the emulated Mac + +```bash +scripts/adi-emulator-diff/run.sh /tmp/CoreADI.x86_64 +``` + +Runs Apple's macOS CoreADI under Unicorn and under icicle with the same inputs and diffs the +output; it exits non-zero on any difference. Unlike the scripts above it does need the network, +to clone three repositories at pinned commits, but it sends nothing to Apple. Nobody needs to run +it routinely; it exists for whoever wants to replace Unicorn. Why, what it showed and what it +does not cover: [docs/emulated-mac-emulator-choice.md](docs/emulated-mac-emulator-choice.md). + ### The locked-bundle fixture `app/src/androidTest/assets/locked_bundle_fixture.zip` is committed rather than built by the diff --git a/docs/README.md b/docs/README.md index 8100175c..389c14b9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ no natural home in a source comment. | [how-to-export-with-the-cli.md](./how-to-export-with-the-cli.md) | How to export AirTags out of iCloud with no Mac. Written for whoever is running it rather than for whoever is changing it, which is why it is the one page here addressed to a user. | | [android-import-handover.md](./android-import-handover.md) | What the Android app has to do to catch up with the exporter: the shared package's Chaquopy wiring, encrypted bundles, self-generated tags. A task brief - delete it when the work lands. | | [anisette-native-android.md](./anisette-native-android.md) | Proof-of-concept log for running Apple's ADI libraries in-process on Android, and the measurements that came out of it. Historical; the implementation shipped. | +| [emulated-mac-emulator-choice.md](./emulated-mac-emulator-choice.md) | Why the emulated Mac (#274) runs on Unicorn despite GPL-2.0, which permissive emulators exist, and an offline byte-for-byte comparison of Unicorn against icicle. Read before replacing the emulator. | | [findmy-export/](./findmy-export/) | Clean-room specification of the protocol for reading FindMy accessory keys from iCloud without a Mac. Stage 1 written; five stages to go. | | [owner-connected-tags.md](./owner-connected-tags.md) | Reading list for the one case the app cannot handle: matching or ringing a tag while it is with its owner, so the Find My network never sees it. Links plus what each one actually establishes — including that authorised and unauthorised ringing are different protocols. | diff --git a/docs/emulated-mac-emulator-choice.md b/docs/emulated-mac-emulator-choice.md new file mode 100644 index 00000000..7c43c828 --- /dev/null +++ b/docs/emulated-mac-emulator-choice.md @@ -0,0 +1,87 @@ +# The emulated Mac's CPU emulator: Unicorn, and how to swap it + +Decision record, 2026-10-23. Context: [#248](https://github.com/parawanderer/OpenTagViewer/issues/248) +and [#274](https://github.com/parawanderer/OpenTagViewer/pull/274), which signs in with Apple's +macOS CoreADI running under an x86_64 emulator on the phone. + +## Decision + +**Ship Unicorn**, and replace it later only if somebody has a concrete reason to. Unicorn is +GPL-2.0, so an APK containing it is distributed under GPL-2.0 terms. That carries two +obligations that are not optional and are owed from the first release, not from the first +complaint: + +- a licence notice for Unicorn in the app or the release; +- `libmacadi.so` loaded **in its own process**, not the app's. That is needed for crash + isolation regardless (AGENTS.md rule 4, #232), and it also keeps the GPL code at arm's length + from the Apache-2.0 libraries and the proprietary map SDKs. Loaded in-process, the FSF's view + is that the whole APK is one combined work, and GPL-2.0 is incompatible with both of those. + +## Why replacing it later is cheap + +The emulated Mac's identity lives in its store and host UUID, not in the emulator. An emulator +that produces **the same bytes** for the same inputs is invisible to Apple and to users: no new +device-list entry, no sign-in. So the swap is reversible, on one condition, which +`scripts/adi-emulator-diff/` checks. + +## What was surveyed + +Permissively licensed x86-64 emulators, as of 2026-10: + +| Project | Licence | Verdict | +| --- | --- | --- | +| [icicle-emu](https://github.com/icicle-emu/icicle-emu) | MIT OR Apache-2.0 | Tried; see below. Library-first, Unicorn-like (map, hooks, registers), x86-64 through Ghidra's SLEIGH specification | +| [mwemu](https://github.com/mwemuorg/mwemu) | Apache-2.0 | Second candidate. Pure-Rust interpreter with a Mach-O loader; 339 instructions implemented, so obfuscated SSE code is the risk | +| [remu64](https://github.com/trumank/remu64) | MIT | Weekend project by its own description. Too thin | +| [Triton](https://github.com/JonathanSalwan/Triton) | Apache-2.0 | Can execute concretely, but far slower per instruction | +| [FEX](https://github.com/FEX-Emu/FEX), [box64](https://github.com/ptitSeb/box64) | MIT | Fast and mature, but they run whole Linux processes; not embeddable to call one function in a Mach-O with our own stubs | + +## The icicle experiment + +`scripts/adi-emulator-diff/run.sh` puts icicle under [sacca97/os-findmy-e](https://github.com/sacca97/os-findmy-e)'s +Rust `adi-core` as a second `vm.rs`. The macOS userland is os-findmy-e's own, generated +verbatim from its `vm.rs`; only the CPU underneath changes. Unicorn's code hook on the import +stub page becomes one breakpoint per handled stub. Both builds then make the same calls with a +frozen clock and a fixed host UUID, and the outputs are diffed. + +Result on an Apple M-series Mac, iTunes 12.8.3 CoreADI 4.19: `Initialize`; `IsMachineProvisioned`, +`RequestOTP` and `GetIDMSRouting` on an unprovisioned machine; and `ProvisioningStart` with five +synthetic spims of 0 to 4096 bytes are **byte-identical** under both - return codes, outputs and +the hash of every file the library wrote. + +| | Unicorn | icicle | +| --- | --- | --- | +| Load | 4 ms | ~70 ms (compiles the SLEIGH spec) | +| The calls above, 5.5M guest instructions | 13 ms | ~410 ms interpreted, ~515 ms with its JIT | + +### What that does not establish + +- **The OTP path was never reached.** Every call above can be answered offline, and a synthetic + spim is rejected early. The heavily obfuscated code that computes a real OTP only runs on a + provisioned machine, which needs one anonymous provisioning exchange with Apple. That is the + comparison that settles it, and it has not been run. The driver already has the shape for it: + load a provisioned store, freeze the clock, compare `RequestOTP`. +- **Speed on a phone is unmeasured.** Roughly 30x slower than Unicorn on a Mac, for a sum of + about fifteen calls rather than one header set. Fine for a sign-in, possibly not for every + background fetch. +- icicle needs Ghidra's x86 processor files at runtime (Apache-2.0, a few MB of text), so an APK + would have to carry them or a precompiled form. +- **#274's C++ port is a third implementation.** This compares os-findmy-e's Rust under two + emulators; it says nothing about whether `app/src/main/cpp/macadi/` matches either. The same + driver pointed at `libmacadi.so` would. + +## Running it + +```bash +python scripts/locate_mac_coreadi.py --remote --out /tmp/CoreADI.x86_64 # from #274 +scripts/adi-emulator-diff/run.sh /tmp/CoreADI.x86_64 +``` + +Needs git, cargo and cmake. It clones os-findmy-e, icicle and a sparse Ghidra at pinned commits +into a work directory, and sends nothing to Apple. It exits non-zero if either icicle run +differs from Unicorn. + +One trap, for whoever extends the shim: **icicle's memory and register reads take `&mut self`** +(they fill translation caches). Casting `&` to `*mut` to call them from a `&self` reader is +undefined behaviour, and in release builds it segfaulted before printing anything, which looks +like a broken spec or a stack overflow. The shim holds the VM in an `UnsafeCell` instead. diff --git a/scripts/adi-emulator-diff/adi-diff.rs b/scripts/adi-emulator-diff/adi-diff.rs new file mode 100644 index 00000000..309548fe --- /dev/null +++ b/scripts/adi-emulator-diff/adi-diff.rs @@ -0,0 +1,71 @@ +//! Offline differential run: the same CoreADI calls, deterministic inputs, no network. +//! Build once with and once without `--features icicle` and diff stdout. +use std::time::Instant; + +use adi_core::CoreAdi; +use sha2::{Digest, Sha256}; + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +fn store_sha(adi: &mut CoreAdi) -> String { + let mut h = Sha256::new(); + for (k, v) in adi.vm().files() { + h.update(k.as_bytes()); + h.update((v.len() as u64).to_le_bytes()); + h.update(v); + } + hex(&h.finalize()[..8]) +} + +fn main() { + std::thread::Builder::new().stack_size(512 << 20).spawn(run).unwrap().join().unwrap(); +} + +fn run() { + let path = std::env::args().nth(1).expect("path to CoreADI"); + let image = std::fs::read(path).unwrap(); + let t = Instant::now(); + let mut adi = CoreAdi::new(&image).unwrap(); + eprintln!("load {:?}", t.elapsed()); + adi.set_host_uuid(*b"\x10\x32\x54\x76\x98\xba\xdc\xfe\x01\x23\x45\x67\x89\xab\xcd\xef"); + adi.set_frozen_time(Some(1_790_000_000)); + + let t = Instant::now(); + println!("begin_session {:?}", adi.begin_session()); + println!("is_machine_provisioned {:?}", adi.is_machine_provisioned(-2)); + println!("request_otp(unprovisioned) {:?}", adi.request_otp(-2).map(|o| (o.reply, hex(&o.mid), hex(&o.otp)))); + println!("get_routing {:?}", adi.get_routing(-2)); + println!("store {}", store_sha(&mut adi)); + + // ProvisioningStart parses Apple's spim and builds the client message from it. Without + // Apple there is no valid spim, so feed several deterministic blobs and compare whatever the + // library does with each, byte for byte. + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + for (i, len) in [0usize, 16, 256, 1024, 4096].into_iter().enumerate() { + let spim: Vec = (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as u8 + }) + .collect(); + println!("begin_session {:?}", adi.begin_session()); + match adi.provisioning_start(-2, &spim) { + Ok(p) => println!( + "provisioning_start[{i}] len={len} {:?} session={} cpim({})={}", + p.reply, + p.session, + p.cpim.len(), + hex(&Sha256::digest(&p.cpim)[..16]) + ), + Err(e) => println!("provisioning_start[{i}] len={len} error {e}"), + } + println!("store {}", store_sha(&mut adi)); + } + eprintln!("calls {:?}", t.elapsed()); + #[cfg(feature = "icicle")] + eprintln!("guest instructions {}", adi.vm().icount()); +} diff --git a/scripts/adi-emulator-diff/run.sh b/scripts/adi-emulator-diff/run.sh new file mode 100755 index 00000000..ae831787 --- /dev/null +++ b/scripts/adi-emulator-diff/run.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# Run Apple's macOS CoreADI under Unicorn and under icicle, with the same inputs, and diff the +# results. See docs/emulated-mac-emulator-choice.md for why this exists and what it showed. +# +# scripts/adi-emulator-diff/run.sh [work dir] +# +# The library is the one the emulated Mac downloads from Apple (iTunes 12.8.3, CoreADI 4.19, +# sha256 2eafc3c7...). It is never committed; get it with +# python scripts/locate_mac_coreadi.py --remote --out /tmp/CoreADI.x86_64 +# (added by #274), or from an iTunes 12.8.3 disk image. +# +# Needs git, cargo and cmake. Clones three repositories at pinned commits into the work dir and +# sends nothing to Apple: every call made is answerable offline. +set -euo pipefail + +OS_FINDMY_E=374d83854f657a7fdca45f813387d99d491db0e2 +ICICLE=638508b72f480f9be6fe2e267ef09de8f1541f9a +GHIDRA=164003036607e669226647bd0f7bedaf281e56a6 + +here="$(cd "$(dirname "$0")" && pwd)" +dylib="$(cd "$(dirname "${1:?usage: run.sh [work dir]}")" && pwd)/$(basename "$1")" +work="${2:-${TMPDIR:-/tmp}/adi-emulator-diff}" +mkdir -p "$work" && cd "$work" + +fetch() { # url commit dir [sparse path] + if [ ! -d "$3" ]; then + git init -q "$3" + git -C "$3" remote add origin "$1" + if [ -n "${4:-}" ]; then + git -C "$3" sparse-checkout set "$4" + fi + fi + git -C "$3" fetch -q --depth 1 --filter=blob:none origin "$2" + git -C "$3" checkout -q FETCH_HEAD +} +fetch https://github.com/sacca97/os-findmy-e "$OS_FINDMY_E" os-findmy-e +fetch https://github.com/icicle-emu/icicle-emu "$ICICLE" icicle-emu +fetch https://github.com/NationalSecurityAgency/ghidra "$GHIDRA" ghidra Ghidra/Processors/x86 + +core=os-findmy-e/native/adi-core +git -C os-findmy-e checkout -q -- native/adi-core +mkdir -p "$core/src/bin" +cp "$here/vm_icicle.rs" "$core/src/" +cp "$here/adi-diff.rs" "$core/src/bin/" + +# vm.rs's userland, verbatim, with only the CPU type swapped for the icicle shim. +python3 - "$core" <<'EOF' +import sys +core = sys.argv[1] +src = open(f"{core}/src/vm.rs").read() +body = src[:src.index("/// The pristine state")] +body = "\n".join(l for l in body.splitlines() if not l.startswith("//!")) + "\n" +for old, new in [ + ("use unicorn_engine::unicorn_const::{Arch, HookType, MemType, Mode, Prot};\n" + "use unicorn_engine::{RegisterX86, Unicorn};\n", "use shim::{Cpu as Uc, RegisterX86};\n"), + ("type Uc<'a> = Unicorn<'a, Env>;\n", ""), + ("Uc<'_>", "Uc"), +]: + if old not in body: + sys.exit(f"vm.rs no longer contains {old!r}; the generator needs updating") + body = body.replace(old, new) +open(f"{core}/src/vm_icicle_env.rs", "w").write(body) + +toml = open(f"{core}/Cargo.toml").read() +toml = toml.replace('jni = { version = "0.21", optional = true }', + 'jni = { version = "0.21", optional = true }\n' + 'icicle-vm = { path = "../../../icicle-emu/icicle-vm", optional = true }\n' + 'pcode = { path = "../../../icicle-emu/sleigh/pcode", optional = true }') +toml = toml.replace('jni = ["dep:jni"]', 'jni = ["dep:jni"]\nicicle = ["dep:icicle-vm", "dep:pcode"]') +open(f"{core}/Cargo.toml", "w").write(toml) + +lib = open(f"{core}/src/lib.rs").read() +lib = lib.replace("mod vm;\n", '#[cfg(not(feature = "icicle"))]\nmod vm;\n' + '#[cfg(feature = "icicle")]\n#[path = "vm_icicle.rs"]\nmod vm;\n', 1) +open(f"{core}/src/lib.rs", "w").write(lib) +EOF + +(cd "$core" && cargo build -q --release --bin adi-diff --target-dir target-unicorn) +(cd "$core" && cargo build -q --release --bin adi-diff --features icicle --target-dir target-icicle) + +export GHIDRA_SRC="$work/ghidra" +"$core/target-unicorn/release/adi-diff" "$dylib" > unicorn.txt +ICICLE_NO_JIT=1 "$core/target-icicle/release/adi-diff" "$dylib" > icicle.txt +"$core/target-icicle/release/adi-diff" "$dylib" > icicle-jit.txt + +cat unicorn.txt +for out in icicle.txt icicle-jit.txt; do + if diff -u unicorn.txt "$out"; then + echo "$out: identical to Unicorn" + else + echo "$out: DIFFERS from Unicorn" >&2 + exit 1 + fi +done diff --git a/scripts/adi-emulator-diff/vm_icicle.rs b/scripts/adi-emulator-diff/vm_icicle.rs new file mode 100644 index 00000000..df0440d1 --- /dev/null +++ b/scripts/adi-emulator-diff/vm_icicle.rs @@ -0,0 +1,348 @@ +//! The same runtime as `vm.rs`, on icicle (MIT OR Apache-2.0) instead of Unicorn (GPL-2.0). +//! +//! The macOS userland (`Env`) is `vm.rs`'s, copied verbatim into `vm_icicle_env.rs`; only the CPU +//! underneath differs. Unicorn's code hook on the stub page becomes a breakpoint per handled stub: +//! run the handler, set `rax`, and perform the stub's `ret` by hand. +//! +//! `vm_icicle_env.rs` is not in this repository: `run.sh` generates it from os-findmy-e's `vm.rs` +//! at the pinned commit, so the userland can never drift from the one it is compared against. +//! `Vm` below follows os-findmy-e's `Vm` (MIT, Copyright (c) 2026 sacca) line for line where it can. + +include!("vm_icicle_env.rs"); + +mod shim { + use icicle_vm::cpu::mem::perm; + use pcode::VarNode; + + #[derive(Clone, Copy)] + pub enum RegisterX86 { + RAX, + RBP, + RSP, + RIP, + RDI, + RSI, + RDX, + RCX, + R8, + R9, + } + + pub struct Cpu { + vm: std::cell::UnsafeCell, + regs: [VarNode; 10], + } + + impl Cpu { + pub fn new() -> Result { + let config = icicle_vm::cpu::Config { + enable_jit: std::env::var("ICICLE_NO_JIT").map_or(true, |v| v.is_empty()), + enable_shadow_stack: false, + ..icicle_vm::cpu::Config::from_target_triple("x86_64-none") + }; + let vm = icicle_vm::build(&config).map_err(|e| format!("icicle build: {e:?}"))?; + let names = ["RAX", "RBP", "RSP", "RIP", "RDI", "RSI", "RDX", "RCX", "R8", "R9"]; + let regs = names.map(|n| vm.cpu.arch.sleigh.get_varnode(n).expect(n)); + Ok(Cpu { vm: std::cell::UnsafeCell::new(vm), regs }) + } + + /// icicle reads through `&mut` (it caches translations); nothing here holds two at once. + #[allow(clippy::mut_from_ref)] + pub fn vm(&self) -> &mut icicle_vm::Vm { + unsafe { &mut *self.vm.get() } + } + + pub fn reg_read(&self, r: RegisterX86) -> Result { + if let RegisterX86::RIP = r { + return Ok(self.vm().cpu.read_pc()); + } + Ok(self.vm().cpu.read_reg(self.regs[r as usize])) + } + + pub fn reg_write(&mut self, r: RegisterX86, v: u64) -> Result<(), String> { + if let RegisterX86::RIP = r { + self.vm().cpu.write_pc(v); + } else { + self.vm().cpu.write_reg(self.regs[r as usize], v); + } + Ok(()) + } + + pub fn mem_write(&mut self, addr: u64, data: &[u8]) -> Result<(), String> { + self.vm().cpu.mem.write_bytes(addr, data, perm::NONE).map_err(|e| format!("write {addr:#x}: {e:?}")) + } + + pub fn mem_read_as_vec(&self, addr: u64, len: usize) -> Result, String> { + let mut buf = vec![0u8; len]; + self.vm().cpu.mem.read_bytes(addr, &mut buf, perm::NONE) + .map_err(|e| format!("read {addr:#x}: {e:?}"))?; + Ok(buf) + } + + pub fn mem_map(&mut self, addr: u64, len: u64) -> Result<(), String> { + let m = icicle_vm::cpu::mem::Mapping { perm: perm::READ | perm::WRITE | perm::EXEC, value: 0 }; + if self.vm().cpu.mem.map_memory_len(addr, len, m) { Ok(()) } else { Err(format!("map {addr:#x}")) } + } + + pub fn mem_unmap(&mut self, addr: u64, len: u64) -> Result<(), String> { + if self.vm().cpu.mem.unmap_memory_len(addr, len) { Ok(()) } else { Err(format!("unmap {addr:#x}")) } + } + + /// Handlers call this in Unicorn to stop; here the run loop checks `Env::fault` instead. + pub fn emu_stop(&mut self) -> Result<(), ()> { + Ok(()) + } + } +} + +fn e(m: String) -> Error { + Error::Emulation(m) +} + +/// The pristine state right after load and binding, before any call into the library. +struct Snapshot { + segments: Vec<(u64, Vec)>, + cells: Vec, + heap_cur: u64, + obj_cur: u64, + next_url: u64, + next_fd: u64, +} + +pub struct Vm { + uc: Uc, + env: Env, + snapshot: Snapshot, + zeros: Vec, +} + +impl Vm { + pub fn new(image: &[u8]) -> Result { + let macho = MachO::parse(image)?; + let mut uc = Uc::new().map_err(e)?; + let mut env = Env::default(); + + for (a, s) in [ + (RETURN_ADDRESS, PAGE), + (HEAP_ADDRESS, HEAP_SIZE), + (STACK_ADDRESS, STACK_SIZE), + (STUB_ADDRESS, STUB_SIZE), + (DATA_ADDRESS, DATA_SIZE), + (SCRATCH_ADDRESS, SCRATCH_SIZE), + (OBJECT_ADDRESS, OBJECT_SIZE), + ] { + uc.mem_map(a, s).map_err(e)?; + } + for seg in &macho.segments { + let size = (seg.vmsize + PAGE - 1) / PAGE * PAGE; + if size == 0 { + continue; + } + uc.mem_map(seg.vmaddr, size).map_err(e)?; + if seg.filesize != 0 { + let blob = image + .get(seg.fileoff as usize..(seg.fileoff + seg.filesize) as usize) + .ok_or_else(|| Error::MachO("segment outside file".into()))?; + uc.mem_write(seg.vmaddr, blob).map_err(e)?; + } + } + uc.mem_write(STUB_ADDRESS, &vec![0xC3u8; STUB_SIZE as usize]).map_err(e)?; + + let mut stub_addr: HashMap<&str, u64> = HashMap::new(); + let mut data_cell: HashMap<&str, u64> = HashMap::new(); + let mut handlers = HashMap::new(); + let (mut object_of, mut key_by_object) = (HashMap::new(), HashMap::new()); + for (i, sym) in macho.bind_symbols().into_iter().enumerate() { + let i = i as u64; + if DATA_SYMBOLS.contains(&norm(sym)) { + let (cell, obj) = (DATA_ADDRESS + i * SLOT, OBJECT_ADDRESS + i * SLOT); + uc.mem_write(cell, &obj.to_le_bytes()).map_err(e)?; + data_cell.insert(sym, cell); + object_of.insert(norm(sym).to_string(), obj); + key_by_object.insert(obj, sym.to_string()); + } else { + let addr = STUB_ADDRESS + i * SLOT; + stub_addr.insert(sym, addr); + if let Some(h) = handler_for(norm(sym)) { + handlers.insert(addr, h); + } + } + } + for b in macho.binds() { + let target = data_cell.get(b.symbol.as_str()).or_else(|| stub_addr.get(b.symbol.as_str())); + let target = *target.ok_or_else(|| Error::MachO(format!("unbound symbol {}", b.symbol)))?; + uc.mem_write(b.address, &target.wrapping_add(b.addend as u64).to_le_bytes()).map_err(e)?; + } + + for addr in handlers.keys() { + uc.vm().add_breakpoint(*addr); + } + uc.vm().add_breakpoint(RETURN_ADDRESS); + + env.handlers = handlers; + env.object_of = object_of; + env.key_by_object = key_by_object; + env.heap_cur = HEAP_ADDRESS; + env.scratch_cur = SCRATCH_ADDRESS; + env.obj_cur = OBJECT_ADDRESS; + env.next_url = OBJECT_ADDRESS; + env.next_fd = 3; + env.host_uuid = [ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, + ]; + env.dirs = ["/", "/Users", "/Users/Shared", STORE_DIR].iter().map(|s| s.to_string()).collect(); + + env.errno_addr = env.bump_scratch(8); + let mut cells = Vec::new(); + for (k, v) in [("HOME", "/Users/aditest"), ("USER", "aditest"), ("TMPDIR", "/tmp/")] { + let a = env.bump_scratch(v.len() as u64 + 1); + env.getenv_addr.insert(k, a); + cells.push((a, v)); + } + env.scratch_base = env.scratch_cur; + for (a, v) in cells { + uc.mem_write(a, format!("{v}\0").as_bytes()).map_err(e)?; + } + + let mut segments = Vec::new(); + for seg in macho.segments.iter().filter(|s| s.writable && s.vmsize != 0) { + segments.push((seg.vmaddr, uc.mem_read_as_vec(seg.vmaddr, seg.vmsize as usize).map_err(e)?)); + } + let cells = uc.mem_read_as_vec(DATA_ADDRESS, PAGE as usize).map_err(e)?; + let snapshot = Snapshot { + segments, + cells, + heap_cur: env.heap_cur, + obj_cur: env.obj_cur, + next_url: env.next_url, + next_fd: env.next_fd, + }; + Ok(Vm { uc, env, snapshot, zeros: vec![0u8; STACK_SIZE as usize] }) + } + + /// Run `address(args...)` until it returns; the result is `rax`. + pub fn invoke(&mut self, address: u64, args: &[u64]) -> Result { + use icicle_vm::VmExit; + let uc = &mut self.uc; + for (i, v) in args.iter().enumerate().take(6) { + uc.reg_write(reg(i), *v).map_err(e)?; + } + let rsp = STACK_ADDRESS + STACK_SIZE - 0x1000; + w64(uc, rsp, RETURN_ADDRESS); + uc.reg_write(RegisterX86::RSP, rsp).map_err(e)?; + uc.reg_write(RegisterX86::RBP, 0).map_err(e)?; + uc.reg_write(RegisterX86::RIP, address).map_err(e)?; + self.env.fault = None; + loop { + let exit = uc.vm().run(); + let pc = uc.vm().cpu.read_pc(); + match exit { + VmExit::Breakpoint if pc == RETURN_ADDRESS => { + return Ok(uc.reg_read(RegisterX86::RAX).unwrap_or(0)); + } + VmExit::Breakpoint => { + let Some(h) = self.env.handlers.get(&pc).copied() else { + return Err(Error::Emulation(format!("breakpoint at {pc:#x} with no handler"))); + }; + let r = self.env.call(uc, h); + if let Some(msg) = self.env.fault.take() { + return Err(Error::Emulation(msg)); + } + if let Some(v) = r { + uc.reg_write(RegisterX86::RAX, v).map_err(e)?; + } + // The stub's `ret`. + let sp = uc.reg_read(RegisterX86::RSP).unwrap_or(0); + let ret = r64(uc, sp); + uc.reg_write(RegisterX86::RSP, sp + 8).map_err(e)?; + uc.reg_write(RegisterX86::RIP, ret).map_err(e)?; + } + other => { + return Err(Error::Emulation(format!("emulation failed at rip={pc:#x}: {other:?}"))); + } + } + } + } + + pub fn reset_session(&mut self) -> Result<(), Error> { + let uc = &mut self.uc; + for (addr, bytes) in &self.snapshot.segments { + uc.mem_write(*addr, bytes).map_err(e)?; + } + uc.mem_write(DATA_ADDRESS, &self.snapshot.cells).map_err(e)?; + uc.mem_unmap(HEAP_ADDRESS, HEAP_SIZE).map_err(e)?; + uc.mem_map(HEAP_ADDRESS, HEAP_SIZE).map_err(e)?; + uc.mem_write(STACK_ADDRESS, &self.zeros).map_err(e)?; + let env = &mut self.env; + let (base, dirty) = (env.scratch_base, (env.scratch_cur - env.scratch_base) as usize); + env.heap_cur = self.snapshot.heap_cur; + env.obj_cur = self.snapshot.obj_cur; + env.next_url = self.snapshot.next_url; + env.next_fd = self.snapshot.next_fd; + env.scratch_cur = env.scratch_base; + env.fds.clear(); + env.urls.clear(); + env.fault = None; + let errno = env.errno_addr; + uc.mem_write(errno, &[0u8; 8]).map_err(e)?; + uc.mem_write(base, &self.zeros[..dirty.min(self.zeros.len())]).map_err(e)?; + Ok(()) + } + + pub fn scratch(&mut self, size: usize) -> u64 { + self.env.bump_scratch(size as u64) + } + + pub fn scratch_reset(&mut self) { + self.env.scratch_cur = self.env.scratch_base; + } + + pub fn write(&mut self, addr: u64, data: &[u8]) -> Result<(), Error> { + self.uc.mem_write(addr, data).map_err(e) + } + + pub fn read(&self, addr: u64, len: usize) -> Result, Error> { + self.uc.mem_read_as_vec(addr, len).map_err(e) + } + + pub fn read_u32(&self, addr: u64) -> Result { + Ok(u32::from_le_bytes(self.read(addr, 4)?.try_into().unwrap())) + } + + pub fn read_u64(&self, addr: u64) -> Result { + Ok(r64(&self.uc, addr)) + } + + pub fn write_u64(&mut self, addr: u64, v: u64) -> Result<(), Error> { + self.write(addr, &v.to_le_bytes()) + } + + pub fn write_u32(&mut self, addr: u64, v: u32) -> Result<(), Error> { + self.write(addr, &v.to_le_bytes()) + } + + pub fn files(&self) -> &BTreeMap> { + &self.env.files + } + + pub fn files_mut(&mut self) -> &mut BTreeMap> { + &mut self.env.files + } + + pub fn set_host_uuid(&mut self, uuid: [u8; 16]) { + self.env.host_uuid = uuid; + } + + pub fn set_frozen_time(&mut self, secs: Option) { + self.env.frozen_time = secs; + } + + pub fn heap_used(&self) -> u64 { + self.env.heap_cur - HEAP_ADDRESS + } + + /// Guest instructions executed so far. + pub fn icount(&self) -> u64 { + self.uc.vm().cpu.icount() + } +}