Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ python -m venv .venv && .venv/bin/pip install "FindMy==<pinned version>"
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
Expand Down
12 changes: 12 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down
87 changes: 87 additions & 0 deletions docs/emulated-mac-emulator-choice.md
Original file line number Diff line number Diff line change
@@ -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.
71 changes: 71 additions & 0 deletions scripts/adi-emulator-diff/adi-diff.rs
Original file line number Diff line number Diff line change
@@ -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<u8> = (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());
}
94 changes: 94 additions & 0 deletions scripts/adi-emulator-diff/run.sh
Original file line number Diff line number Diff line change
@@ -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 <path to the x86_64 CoreADI> [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 <CoreADI.x86_64> [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
Loading
Loading