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
10 changes: 5 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ jobs:
~/.cargo/registry/cache
~/.cargo/git/db
target
key: rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}-${{ hashFiles('Cargo.lock') }}
key: rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}-${{ hashFiles('Cargo.lock') }}
restore-keys: |
rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}-
rust-ci-${{ matrix.os }}-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}-

- name: Format
run: cargo fmt --all --check
Expand Down Expand Up @@ -218,9 +218,9 @@ jobs:
~/.cargo/registry/cache
~/.cargo/git/db
target
key: rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}-${{ hashFiles('Cargo.lock') }}
key: rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}-${{ hashFiles('Cargo.lock') }}
restore-keys: |
rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs') }}-
rust-ci-windows-gnu-${{ steps.toolchain.outputs.version }}-${{ steps.pins.outputs.hash }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**') }}-

# The target cache above carries the staging prefix too, but it's
# multi-GB and first in line for LRU eviction under the repo's 10 GB
Expand All @@ -235,7 +235,7 @@ jobs:
uses: actions/cache@v4
with:
path: target/x86_64-pc-windows-gnu/debug/build/restorekit-sys-*/out/staging
key: windows-c-stack-${{ steps.pins.outputs.hash }}-${{ steps.toolchain.outputs.version }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'Cargo.lock') }}
key: windows-c-stack-${{ steps.pins.outputs.hash }}-${{ steps.toolchain.outputs.version }}-${{ hashFiles('crates/restorekit-sys/build.rs', 'crates/restorekit-sys/patches/**', 'Cargo.lock') }}

# With both caches hot, nothing runs autotools (staging markers skip the
# C stack) or rebuilds openssl-src (the target cache has it), so the full
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const DONGLE_DFU_TIMEOUT: Duration = Duration::from_secs(60);
/// string so the backend can re-derive the exact ECID without a float round-trip.
#[derive(Serialize)]
pub struct DeviceView {
/// "dfu" | "port-dfu" | "recovery" | "wtf" | "restore" | "booted" |
/// "dfu" | "port-dfu" | "kis" | "recovery" | "wtf" | "restore" | "booted" |
/// "billboard" | "other"
pub mode: String,
pub name: String,
Expand Down
16 changes: 16 additions & 0 deletions apps/desktop/src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,9 @@
// or manual instructions.
function deviceMode(d: Device): "restore" | "usb" | "dfu" | "manual" {
if (d.restorable) return d.driver_ready ? "restore" : "usb";
// Already in DFU over Debug USB, just unreadable here:
// re-triggering can't help.
if (d.mode === "kis") return d.driver_ready ? "manual" : "usb";
// A Mac behind a dongle can be put into DFU over the dongle from any host,
// even when this host can't trigger electronically.
return canTrigger || d.via_dongle ? "dfu" : "manual";
Expand Down Expand Up @@ -233,6 +236,7 @@
const MODE_TAG: Record<Mode, string> = {
dfu: "DFU",
"port-dfu": "Port DFU",
kis: "Debug USB DFU",
recovery: "Recovery",
restore: "Restore",
wtf: "WTF",
Expand All @@ -243,6 +247,7 @@
const MODE_COLOR: Record<Mode, string> = {
dfu: "var(--acc)",
"port-dfu": "var(--acc)",
kis: "var(--acc)",
recovery: "var(--alt)",
restore: "var(--ok)",
wtf: "var(--danger)",
Expand Down Expand Up @@ -1287,6 +1292,17 @@
<button class="btn" onclick={rebootTarget} disabled={!!busy}>Reboot</button>
</div>
</div>
{:else if selected.mode === "kis"}
<div class="block">
{#if isMac}
<p class="lede">This Mac is in DFU over Debug USB, but restorekit couldn't read its identity. Usually another app has the device open (Chrome, Apple Configurator). Quit it, then reboot the Mac and put it back into DFU.</p>
{:else}
<p class="lede">This Mac is in DFU over Debug USB, but restorekit couldn't read its identity. Check USB access, then reboot the Mac and put it back into DFU.</p>
{/if}
<div class="actions">
<button class="btn" onclick={rebootTarget} disabled={!!busy}>Reboot</button>
</div>
</div>
{:else}
<div class="block">
<p class="lede">This host can't trigger DFU. Put the target into DFU by hand:</p>
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { downloadDir, join } from "@tauri-apps/api/path";
import { open, save } from "@tauri-apps/plugin-dialog";

export type Mode = "dfu" | "port-dfu" | "recovery" | "wtf" | "restore" | "booted" | "billboard" | "other";
export type Mode = "dfu" | "port-dfu" | "kis" | "recovery" | "wtf" | "restore" | "booted" | "billboard" | "other";

/** The host USB-C port a device is cabled to (macOS only). */
export interface Port {
Expand Down Expand Up @@ -339,6 +339,7 @@ export function gib(bytes: number): string {
export const MODES: Record<Mode, { label: string; hint: string }> = {
dfu: { label: "DFU", hint: "ready to restore" },
"port-dfu": { label: "Port DFU", hint: "ready to update the port and restore" },
kis: { label: "Debug USB DFU", hint: "DFU over Apple's Debug USB interface" },
recovery: { label: "Recovery", hint: "put in DFU to restore" },
restore: { label: "Restore", hint: "restore in progress" },
wtf: { label: "WTF", hint: "low-level mode" },
Expand Down
46 changes: 46 additions & 0 deletions crates/restorekit-cli/src/commands/dfu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ pub fn enter(
Ok(DfuOutcome::Entered(device)) => {
if json {
emit_stage(true, Event::DeviceDetected { device });
} else if device.kis_unreadable() {
println!("\nTarget is now in DFU mode over Debug USB (05ac:1881).");
println!(" Note: {}", Error::KisUnreadable);
} else {
println!("\nTarget is now in DFU mode: {}", device.display_name());
println!(" ECID: {}", device.ecid_hex().unwrap_or_default());
Expand Down Expand Up @@ -305,6 +308,43 @@ pub fn probe_ports(json: bool) -> Result<()> {
Ok(())
}

/// `restorekit vdm` — send one raw VDM and dump the reply register.
pub fn raw_vdm(json: bool, words: &[u32], port: Option<i32>) -> Result<()> {
let target = port
.map(restorekit::dfu::DfuTarget::Port)
.unwrap_or_default();
let reply = restorekit::dfu::raw_vdm(&target, words, &mut |e| emit_stage(json, e))?;
let status = reply[0];
let count = (status & 0x07) as usize;
let all: Vec<u32> = reply[1..61]
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes(*c))
.collect();
if json {
println!(
"{}",
serde_json::json!({ "event": "vdm_reply", "status": status, "words": all })
);
return Ok(());
}
let kind = match all[0] & 0xc0 {
0x40 => "ACK",
0x80 => "NAK",
0xc0 => "BUSY",
_ => "REQ",
};
println!("status 0x{status:02x}, header 0x{:08x} ({kind})", all[0]);
for (i, w) in all.iter().enumerate().skip(1) {
let mark = if i < count { "" } else { " (past count)" };
if i < count || *w != 0 {
println!(" [{i}] 0x{w:08x}{mark}");
}
}
Ok(())
}

/// Ensure a Mac is in DFU mode: return it if already there (with the interactive
/// picker when several are present and no ECID pins one), otherwise trigger
/// entry via a dongle or the host and wait. Shared by `restore`.
Expand Down Expand Up @@ -338,6 +378,11 @@ pub(crate) fn ensure_present(
if !present.is_empty() {
return select_from(present, json);
}
// Already in DFU over Debug USB but unreadable here: triggering again
// can't help.
if device::list()?.iter().any(Device::kis_unreadable) {
return Err(Error::KisUnreadable);
}
// Name a target visible in another mode so the user knows the trigger
// has something to act on.
if !json {
Expand All @@ -361,6 +406,7 @@ pub(crate) fn ensure_present(
/// cabled here, or a wait for a manual DFU entry when nothing can trigger.
fn finish_trigger(json: bool, via: DfuVia, timeout: Duration, ecid: Option<u64>) -> Result<Device> {
match restorekit::trigger_dfu(via, timeout, &mut |e| emit_stage(json, e)) {
Ok(DfuOutcome::Entered(dev)) if dev.kis_unreadable() => Err(Error::KisUnreadable),
Ok(DfuOutcome::Entered(dev)) => Ok(dev),
Ok(DfuOutcome::Sent) => Err(Error::Dongle(
"triggered via dongle, but the target's USB data isn't cabled to this host; \
Expand Down
13 changes: 12 additions & 1 deletion crates/restorekit-cli/src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,18 @@ fn run_once(json: bool) -> Result<()> {
print_ports();
print_dongles();

if !devices.iter().any(|d| d.restorable()) {
if devices.iter().any(|d| d.kis_unreadable()) {
println!(
"Can't restore the Mac in DFU over Debug USB: {}",
restorekit::Error::KisUnreadable
);
} else if !devices.iter().any(|d| d.restorable()) {
if devices.iter().any(|d| d.debug_usb_not_in_dfu()) {
println!(
"Debug USB is on, but the device behind it isn't in DFU, so there's no identity \
to read."
);
}
println!("None are in DFU mode; only a Mac in DFU mode can be restored.");
if restorekit::host_can_trigger_dfu() {
println!("Run `restorekit dfu` to put the cabled target into DFU mode.");
Expand Down
26 changes: 26 additions & 0 deletions crates/restorekit-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,22 @@ enum Command {
/// Diagnostic — sends no DFU action. Hidden.
#[command(hide = true)]
ProbePorts,
/// Dump what restorekit reads from Debug USB (KIS, 05ac:1881) devices: the
/// raw GET_INFO reply and, on macOS, what deviceinterfaced reports.
/// Diagnostic. Hidden.
#[command(hide = true)]
KisProbe,
/// Send one raw USB-PD VDM to the partner on a host DFU port and print the
/// reply (Apple Silicon macOS, root). Diagnostic. Hidden.
#[command(hide = true)]
Vdm {
/// VDM words in hex, header first (e.g. 0x05ac8010).
#[arg(required = true, value_parser = parse_hex_u32)]
words: Vec<u32>,
/// Host DFU-capable port RID (defaults to the DFU port).
#[arg(long)]
port: Option<i32>,
},
/// Resolve and download firmware for the detected (or specified) Mac.
Download {
/// Model identifier (e.g. MacBookPro17,1). Defaults to the DFU device.
Expand Down Expand Up @@ -240,6 +256,11 @@ struct ReviveArgs {
}

/// Parse an ECID: `0x`-prefixed or bare hex, or decimal.
fn parse_hex_u32(s: &str) -> Result<u32, String> {
let hex = s.trim().trim_start_matches("0x").trim_start_matches("0X");
u32::from_str_radix(hex, 16).map_err(|e| format!("invalid hex word {s:?}: {e}"))
}

fn parse_ecid(s: &str) -> Result<u64, String> {
let s = s.trim();
let parsed = if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
Expand Down Expand Up @@ -307,6 +328,11 @@ fn main() {
Command::Reboot(t) => commands::dfu::reboot(cli.json, t.dongle, t.ecid, t.port),
Command::Serial(t) => commands::dfu::serial(cli.json, t.dongle, t.ecid, t.port),
Command::ProbePorts => commands::dfu::probe_ports(cli.json),
Command::KisProbe => {
print!("{}", restorekit::kis::probe());
Ok(())
}
Command::Vdm { words, port } => commands::dfu::raw_vdm(cli.json, &words, port),
Command::Download {
identifier,
os_version,
Expand Down
107 changes: 104 additions & 3 deletions crates/restorekit-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@ fn main() {
("libtatsu", "1.0.5"),
("libimobiledevice", "1.4.0"),
] {
build_autotools(&vendor.join(lib), lib, version, &deps);
let src = if lib == "libirecovery" {
patch_libirecovery_sources(&manifest, &vendor.join(lib), &out, &deps)
} else {
vendor.join(lib)
};
build_autotools(&src, lib, version, &deps);
}

// idevicerestore: compile its sources directly (no library upstream),
Expand Down Expand Up @@ -276,7 +281,8 @@ fn build_autotools(src: &Path, name: &str, version: &str, deps: &Deps) {
// adds -lsetupapi for host_os mingw32*, but under the MSYS2 shell the
// host detects as msys, so irecovery.exe fails to link SetupDi*). The
// static libraries we ultimately link are archives and unaffected.
configure.env("LIBS", "-lws2_32 -liphlpapi -lole32 -lsetupapi");
// winusb: libirecovery's KIS-over-WinUSB patch (irecovery.exe links it).
configure.env("LIBS", "-lws2_32 -liphlpapi -lole32 -lsetupapi -lwinusb");
}
run(&mut configure, &format!("{name} configure"));
if deps.windows {
Expand Down Expand Up @@ -420,6 +426,101 @@ fn patch_idevicerestore_sources(manifest: &Path, vendor_src: &Path, out: &Path)
root
}

/// Copy libirecovery into OUT_DIR and apply `patches/libirecovery/` to it, for
/// the same reason as [`patch_idevicerestore_sources`]. libirecovery is built
/// with autotools, so it's only re-copied and rebuilt when the patches change.
/// The stamp lives in the staging prefix next to build_autotools' marker, so a
/// CI cache that restores only the prefix still skips the rebuild.
fn patch_libirecovery_sources(
manifest: &Path,
vendor_src: &Path,
out: &Path,
deps: &Deps,
) -> PathBuf {
use std::hash::{Hash, Hasher};

let patch_dir = manifest.join("patches/libirecovery");
println!("cargo:rerun-if-changed={}", patch_dir.display());
let mut patches: Vec<PathBuf> = std::fs::read_dir(&patch_dir)
.unwrap()
.map(|e| e.unwrap().path())
.filter(|p| p.extension().and_then(|e| e.to_str()) == Some("patch"))
.collect();
patches.sort();

let mut hasher = std::collections::hash_map::DefaultHasher::new();
for patch in &patches {
println!("cargo:rerun-if-changed={}", patch.display());
std::fs::read(patch).unwrap().hash(&mut hasher);
}
let stamp = format!("{:016x}", hasher.finish());

let root = out.join("libirecovery-patched");
let stamp_file = deps.prefix.join(".libirecovery-patches");
let marker = deps.prefix.join(".built-libirecovery");
if marker.exists() && std::fs::read_to_string(&stamp_file).is_ok_and(|s| s == stamp) {
return root;
}

if root.exists() {
std::fs::remove_dir_all(&root).unwrap();
}
copy_tree(vendor_src, &root);
for patch in &patches {
// POSIX `patch`, not `git apply`; see patch_idevicerestore_sources.
run(
Command::new("patch")
.args(["-p1", "--no-backup-if-mismatch", "-i"])
.arg(patch)
.current_dir(&root),
&format!("apply {}", patch.file_name().unwrap().to_string_lossy()),
);
}
// Force a fresh configure + build of the patched sources.
let _ = std::fs::remove_file(&marker);
let _ = std::fs::remove_dir_all(deps.prefix.parent().unwrap().join("build/libirecovery"));
std::fs::write(&stamp_file, stamp).unwrap();
root
}

/// Recursively copy `src` to `dst`, skipping `.git` (a submodule's `.git` is a
/// file pointing back into the superproject, which a copy can't follow) and
/// autotools output left by an earlier in-tree autogen. A copy gets fresh
/// mtimes, so stale generated files could look out of date and make `make`
/// re-run automake; leaving them out makes build_autotools regenerate them.
/// Symlinks are skipped too: the upstream trees track none, but autogen on
/// macOS links its aux files (`ltmain.sh`, `config.guess`, …) into Homebrew.
fn copy_tree(src: &Path, dst: &Path) {
std::fs::create_dir_all(dst).unwrap();
for entry in std::fs::read_dir(src).unwrap() {
let entry = entry.unwrap();
let name = entry.file_name();
if matches!(
name.to_str(),
Some(
".git"
| "autom4te.cache"
| "configure"
| "aclocal.m4"
| "Makefile.in"
| "config.h.in"
)
) {
continue;
}
let path = entry.path();
let kind = entry.file_type().unwrap();
if kind.is_symlink() {
continue;
}
if kind.is_dir() {
copy_tree(&path, &dst.join(&name));
} else {
std::fs::copy(&path, dst.join(&name)).unwrap();
}
}
}

/// Compile idevicerestore's own C sources into a static archive and link it.
fn compile_idevicerestore(src: &Path, deps: &Deps) {
let src_dir = src.join("src");
Expand Down Expand Up @@ -633,7 +734,7 @@ fn emit_link_directives(prefix: &Path) {
println!("cargo:rustc-link-lib=static=usb-1.0");
for lib in [
"setupapi", "ole32", "ws2_32", "crypt32", "secur32", "bcrypt", "iphlpapi", "userenv",
"advapi32",
"advapi32", "winusb",
] {
println!("cargo:rustc-link-lib=dylib={lib}");
}
Expand Down
Loading
Loading