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
12 changes: 6 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,10 @@ jobs:
# C stack) or rebuilds openssl-src (the target cache has it), so the full
# toolbox — base-devel, autotools, perl, cmake, nasm, ~835 MiB — is dead
# weight; install only what the warm path uses: gcc + binutils for
# build.rs's cc step and the final link, pkgconf + libusb for the libusb
# probe, and POSIX `patch` (build.rs applies the idevicerestore patches
# with `patch`, not `git apply`). Either cache missing falls back to the
# full set (base-devel already bundles `patch`).
# build.rs's cc step and the final link, pkgconf, and POSIX `patch`
# (build.rs applies the idevicerestore patches with `patch`, not
# `git apply`). Either cache missing falls back to the full set
# (base-devel already bundles `patch`).
- uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
Expand All @@ -255,8 +255,8 @@ jobs:
update: false
install: >-
${{ (steps.c-stack.outputs.cache-hit == 'true' && steps.rust-cache.outputs.cache-hit == 'true')
&& 'git patch mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-libusb'
|| 'base-devel git make autoconf automake libtool autoconf-archive gettext-devel pkgconf perl mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake mingw-w64-x86_64-libusb mingw-w64-x86_64-nasm' }}
&& 'git patch mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf'
|| 'base-devel git make autoconf automake libtool autoconf-archive gettext-devel pkgconf perl mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake mingw-w64-x86_64-nasm' }}

- name: Test (windows-gnu, static C stack under MSYS2)
shell: msys2 {0}
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,15 @@ jobs:
base-devel git make autoconf automake libtool autoconf-archive
gettext-devel pkgconf perl mingw-w64-x86_64-gcc
mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake
mingw-w64-x86_64-libusb mingw-w64-x86_64-nasm
mingw-w64-x86_64-nasm

- name: Put the MSYS2 toolchain on PATH
# tauri-action runs cargo in the default shell, so the C stack's autotools
# (sh, gcc, autoreconf, make) must be reachable on the Windows PATH.
# GITHUB_PATH lines are prepended with the LAST-written line taking
# precedence, so write usr\bin first: mingw64\bin must end up ahead of it
# so `pkg-config` is the MinGW-prefix pkgconf — the one that searches
# /mingw64/lib/pkgconfig (libusb-1.0) and reports native library paths.
# /mingw64/lib/pkgconfig and reports native library paths.
if: runner.os == 'Windows'
shell: pwsh
run: |
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ jobs:
mingw-w64-x86_64-gcc
mingw-w64-x86_64-pkgconf
mingw-w64-x86_64-cmake
mingw-w64-x86_64-libusb
mingw-w64-x86_64-nasm

# GNU host toolchain: build scripts link with ld, not MSVC's link.exe
Expand Down
4 changes: 4 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,7 @@
[submodule "crates/restorekit-sys/vendor/usbmuxd"]
path = crates/restorekit-sys/vendor/usbmuxd
url = https://github.com/libimobiledevice/usbmuxd.git
[submodule "crates/restorekit-sys/vendor/libusb"]
path = crates/restorekit-sys/vendor/libusb
url = https://github.com/libusb/libusb.git
ignore = dirty
2 changes: 1 addition & 1 deletion crates/dongle-lite-fw/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion crates/dongle-lite-fw/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,10 @@ cables are actually USB 2 and won't carry SBU) before moving to M1 schematic.
Besides the human CDC console, the firmware exposes a **vendor-specific USB
interface** (`bInterfaceClass = 0xFF`) that the `restorekit` SDK drives over
`nusb` control transfers — no serial port, no OS driver, works the same on
macOS/Linux/Windows (Windows needs the interface bound to WinUSB). The device
macOS/Linux/Windows. On Windows the MS OS 2.0 descriptors bind WinUSB and give
the interface its device interface GUID (`WINUSB_INTERFACE_GUID` in
`restorekit-dongle-proto`); firmware through 0.1.3 left the GUID out, so Windows
never exposed the interface, and `restorekit setup-driver` adds it for those. The device
also enumerates with a **unique USB serial** derived from the RP2350 chip ID
(e.g. `DL-1A2B3C4D`), so multiple dongles are individually addressable.

Expand Down
10 changes: 9 additions & 1 deletion crates/dongle-lite-fw/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,10 +492,18 @@ async fn main(_spawner: Spawner) {
static VHANDLER: StaticCell<VendorHandler> = StaticCell::new();
let vendor_iface = {
let mut func = builder.function(0xFF, 0x00, 0x00);
// Tell Windows this function speaks WinUSB.
// Tell Windows this function speaks WinUSB, and give it an interface
// GUID: without one Windows never exposes the interface of a composite
// device to apps, so the SDK can't open it.
func.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", ""));
func.msos_feature(msos::RegistryPropertyFeatureDescriptor::new(
"DeviceInterfaceGUIDs",
msos::PropertyData::RegMultiSz(&[proto::WINUSB_INTERFACE_GUID]),
));
let mut iface = func.interface();
let n = iface.interface_number();
// The host's Windows driver setup binds this interface by number.
assert_eq!(u8::from(n), proto::VENDOR_IFACE);
let _alt = iface.alt_setting(0xFF, 0x00, 0x00, None);
n
};
Expand Down
8 changes: 6 additions & 2 deletions crates/restorekit-cli/src/commands/dfu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,8 +379,12 @@ pub(crate) fn ensure_present(
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) {
// can't help, except on Windows with a dongle, which puts it back into
// DFU so Windows' driver picks it up.
if device::list()?.iter().any(Device::kis_unreadable)
&& !(cfg!(target_os = "windows")
&& restorekit::dongle::list().is_ok_and(|d| d.len() == 1))
{
return Err(Error::KisUnreadable);
}
// Name a target visible in another mode so the user knows the trigger
Expand Down
11 changes: 7 additions & 4 deletions crates/restorekit-cli/src/commands/restore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,11 +190,14 @@ fn restore_device(device: &Device, opts: Opts) -> Result<()> {
say(json, "Starting restore. Do not disconnect the target.");
// The restore-mode USB interface needs our WinUSB forced onto it, which is
// done by an elevated watcher the restore spawns — warn about the UAC prompt.
// Apple's usbmuxd, when running, handles restore mode itself.
#[cfg(target_os = "windows")]
say(
json,
" A Windows (UAC) prompt will appear to set up restore-mode USB access — approve it.",
);
if matches!(restorekit::restore::windows_mux_check(), Ok(false)) {
say(
json,
" A Windows (UAC) prompt will appear to set up restore-mode USB access — approve it.",
);
}
// In verbose mode idevicerestore's log streams to the terminal, so hide the
// progress bar to avoid interleaving with it.
let bar = if json || opts.verbose {
Expand Down
2 changes: 1 addition & 1 deletion crates/restorekit-cli/src/commands/setup_driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fn install(json: bool) -> Result<usize> {
if json {
render::emit_json(&e);
} else if let Event::DriverBound { name } = &e {
println!(" bound WinUSB to {name}");
println!(" USB access ready for {name}");
}
};
driver::install_winusb(&mut on_event)
Expand Down
9 changes: 9 additions & 0 deletions crates/restorekit-dongle-proto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ pub const SERIAL_PREFIX_PRO: &str = "DP-";
/// Class of the vendor-specific interface the SDK drives.
pub const VENDOR_CLASS: u8 = 0xFF;

/// Interface number of the vendor interface (after the two CDC ACM functions).
pub const VENDOR_IFACE: u8 = 4;

/// WinUSB device interface GUID for the vendor interface. Windows only exposes a
/// WinUSB interface of a composite device to apps (nusb, libusb) when it has one,
/// so the firmware hands it out in its MS OS 2.0 descriptors and the host's
/// driver setup writes it for dongles whose firmware predates that.
pub const WINUSB_INTERFACE_GUID: &str = "{82A7EB70-6C66-43B6-BDCB-D957FCC49307}";

// bRequest values on the vendor interface (vendor type, interface recipient).
/// Control OUT: execute a command; wValue = `VCMD_*`.
pub const VREQ_CMD: u8 = 0x01;
Expand Down
59 changes: 26 additions & 33 deletions crates/restorekit-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ fn main() {
("libtatsu", "1.0.5"),
("libimobiledevice", "1.4.0"),
] {
let src = if lib == "libirecovery" {
patch_libirecovery_sources(&manifest, &vendor.join(lib), &out, &deps)
let src = if manifest.join("patches").join(lib).is_dir() {
patch_autotools_sources(&manifest, lib, &vendor.join(lib), &out, &deps)
} else {
vendor.join(lib)
};
Expand All @@ -75,6 +75,13 @@ fn main() {
// idevicerestore talks to for the restore-mode phase.
let target_os = env::var("CARGO_CFG_TARGET_OS");
if matches!(target_os.as_deref(), Ok("linux") | Ok("windows")) {
// Linux links the system libusb. MSYS2 no longer packages libusb for
// MINGW64, so on Windows build it from the vendored source; only the
// embedded usbmuxd uses it there (libirecovery talks to Windows
// directly), so it goes after the libimobiledevice family.
if deps.windows {
build_autotools(&vendor.join("libusb"), "libusb", "1.0.30", &deps);
}
compile_usbmuxd(&vendor.join("usbmuxd"), &deps);
}

Expand Down Expand Up @@ -426,20 +433,21 @@ 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.
/// Copy an autotools library into OUT_DIR and apply `patches/<name>/` to it,
/// for the same reason as [`patch_idevicerestore_sources`]. 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(
fn patch_autotools_sources(
manifest: &Path,
name: &str,
vendor_src: &Path,
out: &Path,
deps: &Deps,
) -> PathBuf {
use std::hash::{Hash, Hasher};

let patch_dir = manifest.join("patches/libirecovery");
let patch_dir = manifest.join("patches").join(name);
println!("cargo:rerun-if-changed={}", patch_dir.display());
let mut patches: Vec<PathBuf> = std::fs::read_dir(&patch_dir)
.unwrap()
Expand All @@ -455,9 +463,9 @@ fn patch_libirecovery_sources(
}
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");
let root = out.join(format!("{name}-patched"));
let stamp_file = deps.prefix.join(format!(".{name}-patches"));
let marker = deps.prefix.join(format!(".built-{name}"));
if marker.exists() && std::fs::read_to_string(&stamp_file).is_ok_and(|s| s == stamp) {
return root;
}
Expand All @@ -478,7 +486,7 @@ fn patch_libirecovery_sources(
}
// 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"));
let _ = std::fs::remove_dir_all(deps.prefix.parent().unwrap().join("build").join(name));
std::fs::write(&stamp_file, stamp).unwrap();
root
}
Expand Down Expand Up @@ -661,8 +669,11 @@ fn compile_usbmuxd(src: &Path, deps: &Deps) {
.define("HAVE_LOCALTIME_R", None);
}

// libusb-1.0 headers (usbmuxd includes <libusb.h> directly).
if let Ok(output) = std::process::Command::new("pkg-config")
// libusb-1.0 headers (usbmuxd includes <libusb.h> directly): our own build
// on Windows, the system's elsewhere.
if deps.windows {
build.include(deps.prefix.join("include/libusb-1.0"));
} else if let Ok(output) = std::process::Command::new("pkg-config")
.args(["--cflags-only-I", "libusb-1.0"])
.output()
{
Expand Down Expand Up @@ -725,12 +736,8 @@ fn emit_link_directives(prefix: &Path) {
println!("cargo:rustc-link-lib=framework={fw}");
}
} else if target_os.as_deref() == Ok("windows") {
// libusb (static, from MSYS2) plus the Win32 libraries it, libcurl, and
// OpenSSL pull in. libusb-1.0.a lives in the MinGW prefix, not our
// staging dir, so point rustc's linker at that libdir (via pkg-config).
if let Some(libdir) = mingw_libusb_libdir() {
println!("cargo:rustc-link-search=native={libdir}");
}
// libusb (static, built into our staging prefix) plus the Win32
// libraries it, libcurl, and OpenSSL pull in.
println!("cargo:rustc-link-lib=static=usb-1.0");
for lib in [
"setupapi", "ole32", "ws2_32", "crypt32", "secur32", "bcrypt", "iphlpapi", "userenv",
Expand All @@ -744,20 +751,6 @@ fn emit_link_directives(prefix: &Path) {
}
}

/// Ask pkg-config where MSYS2's static libusb (`libusb-1.0.a`) lives, so the
/// final rustc link can find it. Returns a native path rustc's linker accepts.
fn mingw_libusb_libdir() -> Option<String> {
let out = Command::new("pkg-config")
.args(["--variable=libdir", "libusb-1.0"])
.output()
.ok()?;
if !out.status.success() {
return None;
}
let dir = String::from_utf8_lossy(&out.stdout).trim().to_string();
(!dir.is_empty()).then_some(dir)
}

/// A Command that runs `script` — directly on Unix, or via MSYS2's `sh` on
/// Windows (where Rust's `Command` can't exec a shell script itself).
fn shell(windows: bool, script: &str) -> Command {
Expand Down
17 changes: 17 additions & 0 deletions crates/restorekit-sys/patches/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@ compiles the patched copy.
0x1332 ("failed to copy response for AppleTCON") while the restore carries
on. When `ResponseTags` is missing, send the firmware like before, falling
back to the ticket-only reply if it can't be extracted.
- `0009-wait-longer-for-ibec-to-boot.patch` — after iBEC is sent from DFU,
`dfu_enter_recovery` gave the Mac 10 seconds to drop off the bus and another
10 to come back in recovery. An M4 mac mini whose earlier restore was cut
short took about 30 seconds to boot iBEC, so every retry failed with "Device
did not disconnect. Possibly invalid iBEC". Wait up to 60 seconds each, like
the same step in `idevicerestore.c` already does.

## libimobiledevice-glue

- `0001-real-condition-variables-on-windows.patch` — on Windows `cond_t` was a
semaphore: a signal with no waiter was counted instead of dropped, so a later
wait returned at once, and a wait never re-took the mutex, so callers then
released it twice. idevicerestore's device waits are written for pthreads, so
one stray device event made the next "wait for the device to disconnect"
return immediately and fail the restore. Use a `CONDITION_VARIABLE` with the
`CRITICAL_SECTION` mutex, which behaves like pthreads. Built with autotools
from a patched copy, like libirecovery.

## libirecovery

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
--- a/src/dfu.c
+++ b/src/dfu.c
@@ -671,7 +671,7 @@ int dfu_enter_recovery(struct idevicerestore_client_t* client, plist_t build_ide
}

logger(LL_DEBUG, "Waiting for device to disconnect...\n");
- cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000);
if (client->mode != MODE_UNKNOWN || (client->flags & FLAG_QUIT)) {
mutex_unlock(&client->device_event_mutex);
if (!(client->flags & FLAG_QUIT)) {
@@ -680,7 +680,7 @@ int dfu_enter_recovery(struct idevicerestore_client_t* client, plist_t build_ide
return -1;
}
logger(LL_DEBUG, "Waiting for device to reconnect in recovery mode...\n");
- cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000);
if (client->mode != MODE_RECOVERY || (client->flags & FLAG_QUIT)) {
mutex_unlock(&client->device_event_mutex);
if (!(client->flags & FLAG_QUIT)) {
Loading
Loading