From d706bd8b9df63f47cdba266eef759f55bc72d0ac Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 09:46:52 -0600 Subject: [PATCH 1/5] Add the hosted Patchy overwrite client --- .github/workflows/ci.yml | 4 +- Cargo.lock | 10 +- Cargo.toml | 2 +- README.md | 14 +- crates/highfleet-patchy-client/Cargo.toml | 9 + crates/highfleet-patchy-client/src/lib.rs | 242 ++++++++++++++++++++ crates/highfleet-patchy-client/src/tests.rs | 158 +++++++++++++ tests/fixtures/patchy-mod/Cargo.toml | 2 +- tests/fixtures/patchy-mod/src/lib.rs | 60 +---- 9 files changed, 444 insertions(+), 57 deletions(-) create mode 100644 crates/highfleet-patchy-client/Cargo.toml create mode 100644 crates/highfleet-patchy-client/src/lib.rs create mode 100644 crates/highfleet-patchy-client/src/tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba827f0..8568b3a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,10 +51,10 @@ jobs: components: clippy, rustfmt - name: Check API formatting - run: cargo fmt -p highfleet-mod-api -- --check + run: cargo fmt -p highfleet-mod-api -p highfleet-patchy-client -p patchy-test-mod -- --check - name: Lint API - run: cargo clippy --locked -p highfleet-mod-api --all-targets -- -D warnings + run: cargo clippy --locked -p highfleet-mod-api -p highfleet-patchy-client -p patchy-test-mod --all-targets -- -D warnings - name: Test workspace run: cargo test --workspace --locked diff --git a/Cargo.lock b/Cargo.lock index 21a0823..bb9283f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,6 +233,14 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "highfleet-patchy-client" +version = "0.1.0" +dependencies = [ + "highfleet-mod-api", + "thiserror 2.0.20", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -397,7 +405,7 @@ dependencies = [ name = "patchy-test-mod" version = "0.0.0" dependencies = [ - "highfleet-mod-api", + "highfleet-patchy-client", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a1cf7b6..0571925 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" # build = "build.rs" [workspace] -members = ["crates/highfleet-mod-api", "tests/fixtures/patchy-mod"] +members = ["crates/highfleet-mod-api", "crates/highfleet-patchy-client", "tests/fixtures/patchy-mod"] resolver = "2" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/README.md b/README.md index 80f1993..ac44416 100644 --- a/README.md +++ b/README.md @@ -114,10 +114,16 @@ normally. Unknown builds and rejected version checks do not disable the service. Sessions are referred to by loader-issued 64-bit IDs. Zero is never issued, IDs are never reused, and an unknown, consumed, or another mod's ID is rejected -without affecting any session. The initial table supports named byte overwrites. Trampoline requests and the -mod-facing Rust `PatchSession` client are not yet available, and the ABI is not -stable. For a minimal end-to-end example, see the -[test mod](tests/fixtures/patchy-mod/src/lib.rs). +without affecting any session. The ABI is provisional and currently supports +byte overwrites only. + +Rust mods can alias the `highfleet-patchy-client` package as `patchy` in their +manifest and call `patchy::export_patchy!()` once at the crate root. +`PatchSession::new()` then returns a loader-owned session or an error if the +service was unavailable or incompatible. `overwrite` and `install_permanently` +use the usual Patchy call shape, and `overwrite_named` supplies a diagnostic +name. There is no local Patchy fallback. Custom trampolines are not supported +yet. See the [test mod](tests/fixtures/patchy-mod/src/lib.rs) for a minimal example. #### `init() -> bool` The modloader calls this function last. diff --git a/crates/highfleet-patchy-client/Cargo.toml b/crates/highfleet-patchy-client/Cargo.toml new file mode 100644 index 0000000..0404be3 --- /dev/null +++ b/crates/highfleet-patchy-client/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "highfleet-patchy-client" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] +highfleet-mod-api = { path = "../highfleet-mod-api" } +thiserror = "2" diff --git a/crates/highfleet-patchy-client/src/lib.rs b/crates/highfleet-patchy-client/src/lib.rs new file mode 100644 index 0000000..c87517e --- /dev/null +++ b/crates/highfleet-patchy-client/src/lib.rs @@ -0,0 +1,242 @@ +//! Rust client for the Modloader's provisional, overwrite-only Patchy service. +//! +//! Alias this package as `patchy` in the mod's manifest and invoke +//! [`export_patchy!`] once. This crate never links the local patch engine. + +use highfleet_mod_api::patching::{ + HfmPatchApiV1, HfmPatchSessionCreateV1, HfmPatchSessionDiscardV1, HfmPatchSessionId, + HfmPatchSessionInstallV1, HfmPatchSessionOverwriteV1, HFM_PATCH_ABI_VERSION_1, + HFM_PATCH_FAILED, HFM_PATCH_INVALID_ARGUMENT, HFM_PATCH_OK, HFM_PATCH_OVERLAP, + HFM_PATCH_SOURCE_CHANGED, +}; +use std::{ffi::c_void, mem::size_of, num::NonZeroU64, sync::OnceLock}; + +pub type Result = std::result::Result; + +#[derive(Clone, Debug, thiserror::Error)] +#[non_exhaustive] +pub enum PatchError { + #[error("the Modloader did not supply the shared Patchy service")] + MissingHost, + #[error("the Modloader supplied a null Patchy table")] + NullTable, + #[error("unsupported Modloader Patchy ABI version {version}")] + UnsupportedAbi { version: u32 }, + #[error("Modloader Patchy table is too small ({size} bytes; need {minimum})")] + TableTooSmall { size: u32, minimum: u32 }, + #[error("the Modloader supplied a null Patchy context")] + MissingContext, + #[error("the Modloader Patchy table is missing {0}")] + MissingCallback(&'static str), + #[error("the Modloader returned an invalid Patchy session ID")] + InvalidSession, + #[error("the Modloader rejected invalid Patchy arguments")] + InvalidArgument, + #[error("a patch overlaps another patch; see the Modloader log")] + Overlap, + #[error("patch source bytes changed after preparation; see the Modloader log")] + SourceChanged, + #[error("the Modloader Patchy operation failed (status {0}); if installing, writes may have occurred")] + HostFailure(u32), +} + +#[derive(Clone, Copy)] +struct Host { + context: *mut c_void, + create: HfmPatchSessionCreateV1, + discard: HfmPatchSessionDiscardV1, + overwrite: HfmPatchSessionOverwriteV1, + install: HfmPatchSessionInstallV1, +} + +// SAFETY: The host ABI keeps the opaque context and callbacks live for the +// process and supports calls from any thread. The client never dereferences it. +unsafe impl Send for Host {} +// SAFETY: As above, sharing the table only shares thread-safe host callbacks. +unsafe impl Sync for Host {} + +impl Host { + /// A non-null pointer must provide two readable, aligned `u32` fields. + /// If they report a supported version and sufficient size, the pointer + /// must be aligned and valid for a full `HfmPatchApiV1`, and its context + /// and callbacks must satisfy the host ABI for process lifetime. + unsafe fn from_table(table: *const HfmPatchApiV1) -> Result { + if table.is_null() { + return Err(PatchError::NullTable); + } + let version = unsafe { (&raw const (*table).abi_version).read() }; + if version != HFM_PATCH_ABI_VERSION_1 { + return Err(PatchError::UnsupportedAbi { version }); + } + let size = unsafe { (&raw const (*table).struct_size).read() }; + let minimum = size_of::() as u32; + if size < minimum { + return Err(PatchError::TableTooSmall { size, minimum }); + } + let api = unsafe { table.read() }; + if api.context.is_null() { + return Err(PatchError::MissingContext); + } + Ok(Self { + context: api.context, + create: api + .session_create + .ok_or(PatchError::MissingCallback("session_create"))?, + discard: api + .session_discard + .ok_or(PatchError::MissingCallback("session_discard"))?, + overwrite: api + .session_overwrite + .ok_or(PatchError::MissingCallback("session_overwrite"))?, + install: api + .session_install + .ok_or(PatchError::MissingCallback("session_install"))?, + }) + } +} + +static HOST: OnceLock> = OnceLock::new(); + +#[doc(hidden)] +pub use highfleet_mod_api::patching::HfmPatchApiV1 as __HostTable; + +/// Exports the shared Patchy setup hook. Invoke once at the mod crate root. +#[macro_export] +macro_rules! export_patchy { + () => { + /// Receives the Modloader's shared Patchy capability. + /// + /// # Safety + /// The pointer and callbacks must satisfy the Modloader's Patchy setup ABI. + #[unsafe(no_mangle)] + pub unsafe extern "C" fn highfleet_mod_setup_patchy_v1( + table: *const $crate::__HostTable, + ) -> u32 { + unsafe { $crate::__setup_patchy(table) } + } + }; +} + +#[doc(hidden)] +/// # Safety +/// The pointer and callbacks must satisfy the Modloader's Patchy setup ABI. +pub unsafe fn __setup_patchy(table: *const HfmPatchApiV1) -> u32 { + register_host(&HOST, table) +} + +// The caller upholds Host::from_table's contract. +unsafe fn register_host(slot: &OnceLock>, table: *const HfmPatchApiV1) -> u32 { + let host = unsafe { Host::from_table(table) }; + let accepted = host.is_ok(); + if slot.set(host).is_ok() && accepted { + HFM_PATCH_OK + } else { + HFM_PATCH_FAILED + } +} + +fn check_status(status: u32) -> Result { + match status { + HFM_PATCH_OK => Ok(()), + HFM_PATCH_INVALID_ARGUMENT => Err(PatchError::InvalidArgument), + HFM_PATCH_OVERLAP => Err(PatchError::Overlap), + HFM_PATCH_SOURCE_CHANGED => Err(PatchError::SourceChanged), + other => Err(PatchError::HostFailure(other)), + } +} + +/// A pending batch, owned by the Modloader. Dropping it discards staged work. +pub struct PatchSession { + host: Host, + id: Option, +} + +impl PatchSession { + /// Creates a session once the loader has called the patch setup export. + /// Returns an error if the host is absent or incompatible. + pub fn new() -> Result { + Self::from_slot(&HOST) + } + + fn from_slot(slot: &OnceLock>) -> Result { + match slot.get() { + Some(Ok(host)) => Self::from_host(*host), + Some(Err(error)) => Err(error.clone()), + None => Err(PatchError::MissingHost), + } + } + + fn from_host(host: Host) -> Result { + let mut id: HfmPatchSessionId = 0; + check_status(unsafe { (host.create)(host.context, &mut id) })?; + let id = NonZeroU64::new(id).ok_or(PatchError::InvalidSession)?; + Ok(Self { host, id: Some(id) }) + } + + /// Stages an in-place overwrite without installing it. + /// + /// # Safety + /// The destination range must be readable through installation and valid + /// to overwrite. If executed, `bytes` must be valid code at that address. + pub unsafe fn overwrite(&mut self, address: usize, bytes: &[u8]) -> Result { + unsafe { self.overwrite_named("overwrite", address, bytes) } + } + + /// Like [`Self::overwrite`], with a name for the loader's diagnostics. + /// + /// # Safety + /// The range and replacement must satisfy [`Self::overwrite`]. + pub unsafe fn overwrite_named( + &mut self, + name: &str, + address: usize, + bytes: &[u8], + ) -> Result { + let id = self.id.expect("live session").get(); + check_status(unsafe { + (self.host.overwrite)( + self.host.context, + id, + name.into(), + address, + bytes.as_ptr(), + bytes.len(), + ) + })?; + Ok(Patch { trampoline: None }) + } + + /// Installs every staged patch. The host consumes the session even on error. + /// + /// # Safety + /// All staged source ranges must remain valid, and no other thread may + /// execute a patch source while it is being written. + pub unsafe fn install_permanently(mut self) -> Result { + let id = self.id.take().expect("live session").get(); + check_status(unsafe { (self.host.install)(self.host.context, id) }) + } +} + +impl Drop for PatchSession { + fn drop(&mut self) { + if let Some(id) = self.id.take() { + // SAFETY: This is a live session issued by the same host. + unsafe { (self.host.discard)(self.host.context, id.get()) }; + } + } +} + +/// Describes a prepared patch without owning the loader's session. +pub struct Patch { + trampoline: Option, +} + +impl Patch { + /// Returns the trampoline address if the patch has one. + pub fn trampoline_address(&self) -> Option { + self.trampoline + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/highfleet-patchy-client/src/tests.rs b/crates/highfleet-patchy-client/src/tests.rs new file mode 100644 index 0000000..ec2f3d0 --- /dev/null +++ b/crates/highfleet-patchy-client/src/tests.rs @@ -0,0 +1,158 @@ +use super::*; +use highfleet_mod_api::ffi::HfmStr; +use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; + +#[derive(Default)] +struct Calls { + stage_count: AtomicU32, + install_count: AtomicU32, + discard_count: AtomicU32, + install_status: AtomicU32, +} + +fn table(calls: &'static Calls) -> HfmPatchApiV1 { + HfmPatchApiV1 { + abi_version: HFM_PATCH_ABI_VERSION_1, + struct_size: size_of::() as u32, + context: std::ptr::from_ref(calls).cast_mut().cast(), + session_create: Some(create), + session_discard: Some(discard), + session_overwrite: Some(overwrite), + session_install: Some(install), + } +} + +unsafe extern "C" fn create(_: *mut c_void, output: *mut HfmPatchSessionId) -> u32 { + unsafe { output.write(12) }; + HFM_PATCH_OK +} + +unsafe extern "C" fn discard(context: *mut c_void, id: HfmPatchSessionId) -> u32 { + if id != 12 { + return HFM_PATCH_INVALID_ARGUMENT; + } + unsafe { &*context.cast::() } + .discard_count + .fetch_add(1, Relaxed); + HFM_PATCH_OK +} + +unsafe extern "C" fn overwrite( + context: *mut c_void, + id: HfmPatchSessionId, + name: HfmStr, + address: usize, + bytes: *const u8, + len: usize, +) -> u32 { + if id != 12 + || address != 0x1000 + || unsafe { std::slice::from_raw_parts(name.ptr, name.len) } != b"overwrite" + || unsafe { std::slice::from_raw_parts(bytes, len) } != [42] + { + return HFM_PATCH_INVALID_ARGUMENT; + } + unsafe { &*context.cast::() } + .stage_count + .fetch_add(1, Relaxed); + HFM_PATCH_OK +} + +unsafe extern "C" fn install(context: *mut c_void, id: HfmPatchSessionId) -> u32 { + if id != 12 { + return HFM_PATCH_INVALID_ARGUMENT; + } + let calls = unsafe { &*context.cast::() }; + calls.install_count.fetch_add(1, Relaxed); + calls.install_status.load(Relaxed) +} + +fn mock() -> (&'static Calls, Host) { + let calls = Box::leak(Box::new(Calls::default())); + let host = unsafe { Host::from_table(&table(calls)) }.unwrap(); + (calls, host) +} + +#[test] +fn new_without_setup_reports_the_missing_service() { + assert!(matches!(PatchSession::new(), Err(PatchError::MissingHost))); +} + +#[test] +fn an_incompatible_table_version_is_rejected() { + let mut api = table(Box::leak(Box::new(Calls::default()))); + api.abi_version += 1; + let slot = OnceLock::new(); + assert_eq!(unsafe { register_host(&slot, &api) }, HFM_PATCH_FAILED); + assert!(matches!( + PatchSession::from_slot(&slot), + Err(PatchError::UnsupportedAbi { .. }) + )); +} + +#[test] +fn setup_keeps_a_copy_of_the_host_table() { + let calls = Box::leak(Box::new(Calls::default())); + let slot = OnceLock::new(); + let mut api = table(calls); + assert_eq!(unsafe { register_host(&slot, &api) }, HFM_PATCH_OK); + api.session_create = None; + let session = PatchSession::from_slot(&slot).unwrap(); + unsafe { session.install_permanently() }.unwrap(); + assert!(api.session_create.is_none()); + assert_eq!(calls.install_count.load(Relaxed), 1); + assert_eq!(calls.discard_count.load(Relaxed), 0); +} + +#[test] +fn a_header_only_table_is_rejected_as_too_small() { + #[repr(C, align(8))] + struct Header([u32; 2]); + let header = Header([HFM_PATCH_ABI_VERSION_1, 8]); + assert!(matches!( + unsafe { Host::from_table(std::ptr::from_ref(&header).cast()) }, + Err(PatchError::TableTooSmall { .. }) + )); +} + +#[test] +fn a_missing_callback_is_rejected() { + let mut api = table(Box::leak(Box::new(Calls::default()))); + api.session_install = None; + assert!(matches!( + unsafe { Host::from_table(&api) }, + Err(PatchError::MissingCallback("session_install")) + )); +} + +#[test] +fn overwrite_forwards_the_request_to_its_host() { + let (calls, host) = mock(); + let mut session = PatchSession::from_host(host).unwrap(); + + let patch = unsafe { session.overwrite(0x1000, &[42]) }.unwrap(); + + assert_eq!(calls.stage_count.load(Relaxed), 1); + assert_eq!(patch.trampoline_address(), None); +} + +#[test] +fn dropping_a_pending_session_discards_it_without_installing() { + let (calls, host) = mock(); + drop(PatchSession::from_host(host).unwrap()); + assert_eq!(calls.discard_count.load(Relaxed), 1); + assert_eq!(calls.install_count.load(Relaxed), 0); +} + +#[test] +fn installation_failure_does_not_discard_the_consumed_handle_again() { + let (calls, host) = mock(); + calls.install_status.store(HFM_PATCH_OVERLAP, Relaxed); + let session = PatchSession::from_host(host).unwrap(); + assert!(matches!( + unsafe { session.install_permanently() }, + Err(PatchError::Overlap) + )); + assert_eq!(calls.install_count.load(Relaxed), 1); + assert_eq!(calls.discard_count.load(Relaxed), 0); +} diff --git a/tests/fixtures/patchy-mod/Cargo.toml b/tests/fixtures/patchy-mod/Cargo.toml index 8379158..1cf001a 100644 --- a/tests/fixtures/patchy-mod/Cargo.toml +++ b/tests/fixtures/patchy-mod/Cargo.toml @@ -10,4 +10,4 @@ test = false doctest = false [dependencies] -highfleet-mod-api = { path = "../../../crates/highfleet-mod-api" } +patchy = { package = "highfleet-patchy-client", path = "../../../crates/highfleet-patchy-client" } diff --git a/tests/fixtures/patchy-mod/src/lib.rs b/tests/fixtures/patchy-mod/src/lib.rs index df503c0..59fa20a 100644 --- a/tests/fixtures/patchy-mod/src/lib.rs +++ b/tests/fixtures/patchy-mod/src/lib.rs @@ -1,34 +1,19 @@ -use highfleet_mod_api::{ - ffi::HfmStr, - patching::{HfmPatchApiV1, HFM_PATCH_ABI_VERSION_1, HFM_PATCH_FAILED, HFM_PATCH_OK}, -}; +use patchy::PatchSession; use std::{ ffi::{c_char, CStr}, - mem::size_of, sync::atomic::{AtomicBool, Ordering}, }; -static mut API: Option = None; +patchy::export_patchy!(); + static mut TARGET: u8 = 7; static SAW_UNKNOWN_AFTER_SETUP: AtomicBool = AtomicBool::new(false); -// The fixture uses these exports sequentially on a single loader thread. -#[unsafe(no_mangle)] -unsafe extern "C" fn highfleet_mod_setup_patchy_v1(api: *const HfmPatchApiV1) -> u32 { - if api.is_null() - || unsafe { (*api).abi_version } != HFM_PATCH_ABI_VERSION_1 - || unsafe { (*api).struct_size } < size_of::() as u32 - { - return HFM_PATCH_FAILED; - } - unsafe { (&raw mut API).write(Some(api.read())) }; - HFM_PATCH_OK -} - /// Declines every version to show that a rejected version keeps the service. #[unsafe(no_mangle)] unsafe extern "C" fn version(version: *const c_char) -> bool { - let set_up = unsafe { (&raw const API).read() }.is_some(); + // Opening and dropping an empty session proves setup already ran. + let set_up = PatchSession::new().is_ok(); let unknown = !version.is_null() && unsafe { CStr::from_ptr(version) }.to_bytes() == b"Unknown"; SAW_UNKNOWN_AFTER_SETUP.store(set_up && unknown, Ordering::Relaxed); false @@ -40,37 +25,16 @@ unsafe extern "C" fn init() -> bool { if !SAW_UNKNOWN_AFTER_SETUP.load(Ordering::Relaxed) { return false; } - let Some(api) = (unsafe { (&raw const API).read() }) else { + let Ok(mut session) = PatchSession::new() else { return false; }; - let (Some(create), Some(discard), Some(overwrite), Some(install)) = ( - api.session_create, - api.session_discard, - api.session_overwrite, - api.session_install, - ) else { - return false; - }; - let mut session = 0; - if unsafe { create(api.context, &mut session) } != HFM_PATCH_OK { - return false; - } - let replacement = 42u8; - let status = unsafe { - overwrite( - api.context, - session, - HfmStr::from("fixture overwrite"), - (&raw mut TARGET) as usize, - &replacement, - 1, - ) - }; - if status != HFM_PATCH_OK { - unsafe { discard(api.context, session) }; - return false; + // SAFETY: TARGET stays live and only this fixture touches it during init. + unsafe { + session + .overwrite_named("fixture overwrite", (&raw mut TARGET) as usize, &[42]) + .and_then(|_| session.install_permanently()) + .is_ok() } - unsafe { install(api.context, session) == HFM_PATCH_OK } } #[unsafe(no_mangle)] From 64a261e82fafe02dbfe0c45afb73e6ce16067657 Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 09:55:33 -0600 Subject: [PATCH 2/5] Add patch_call to the hosted Rust client --- README.md | 11 +- crates/highfleet-patchy-client/src/lib.rs | 134 +++++++++++++++++++- crates/highfleet-patchy-client/src/tests.rs | 76 ++++++++++- src/loader.rs | 10 +- tests/fixtures/patchy-mod/src/lib.rs | 40 ++++++ 5 files changed, 258 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index ac44416..6178313 100644 --- a/README.md +++ b/README.md @@ -115,15 +115,16 @@ normally. Unknown builds and rejected version checks do not disable the service. Sessions are referred to by loader-issued 64-bit IDs. Zero is never issued, IDs are never reused, and an unknown, consumed, or another mod's ID is rejected without affecting any session. The ABI is provisional and currently supports -byte overwrites only. +byte overwrites and callback-only detours. Rust mods can alias the `highfleet-patchy-client` package as `patchy` in their manifest and call `patchy::export_patchy!()` once at the crate root. `PatchSession::new()` then returns a loader-owned session or an error if the -service was unavailable or incompatible. `overwrite` and `install_permanently` -use the usual Patchy call shape, and `overwrite_named` supplies a diagnostic -name. There is no local Patchy fallback. Custom trampolines are not supported -yet. See the [test mod](tests/fixtures/patchy-mod/src/lib.rs) for a minimal example. +service was unavailable or incompatible. `overwrite`, `patch_call`, and +`install_permanently` use the usual Patchy call shape. `overwrite_named` +supplies a diagnostic name. There is no local Patchy fallback. Custom +trampolines and replay are not supported yet. See the +[test mod](tests/fixtures/patchy-mod/src/lib.rs) for a minimal example. #### `init() -> bool` The modloader calls this function last. diff --git a/crates/highfleet-patchy-client/src/lib.rs b/crates/highfleet-patchy-client/src/lib.rs index c87517e..e863d62 100644 --- a/crates/highfleet-patchy-client/src/lib.rs +++ b/crates/highfleet-patchy-client/src/lib.rs @@ -1,13 +1,16 @@ -//! Rust client for the Modloader's provisional, overwrite-only Patchy service. +//! Rust client for the Modloader's provisional shared Patchy service. //! //! Alias this package as `patchy` in the mod's manifest and invoke //! [`export_patchy!`] once. This crate never links the local patch engine. use highfleet_mod_api::patching::{ - HfmPatchApiV1, HfmPatchSessionCreateV1, HfmPatchSessionDiscardV1, HfmPatchSessionId, - HfmPatchSessionInstallV1, HfmPatchSessionOverwriteV1, HFM_PATCH_ABI_VERSION_1, - HFM_PATCH_FAILED, HFM_PATCH_INVALID_ARGUMENT, HFM_PATCH_OK, HFM_PATCH_OVERLAP, - HFM_PATCH_SOURCE_CHANGED, + HfmCallBridgeV1, HfmPatchApiV1, HfmPatchApiWithCallV1, HfmPatchSessionCreateV1, + HfmPatchSessionDiscardV1, HfmPatchSessionId, HfmPatchSessionInstallV1, + HfmPatchSessionOverwriteV1, HfmPatchSessionPatchCallV1, HFM_PATCH_ABI_VERSION_1, + HFM_PATCH_FAILED, HFM_PATCH_FLAGS_KEEP_PRODUCED, HFM_PATCH_FLAGS_PRESERVE, + HFM_PATCH_INVALID_ARGUMENT, HFM_PATCH_OK, HFM_PATCH_OVERLAP, HFM_PATCH_RETURN_NEITHER, + HFM_PATCH_RETURN_RAX, HFM_PATCH_RETURN_XMM0, HFM_PATCH_SOURCE_CHANGED, + HFM_PATCH_STACK_ALIGNED_16, HFM_PATCH_STACK_OFFSET_8, }; use std::{ffi::c_void, mem::size_of, num::NonZeroU64, sync::OnceLock}; @@ -30,6 +33,8 @@ pub enum PatchError { MissingCallback(&'static str), #[error("the Modloader returned an invalid Patchy session ID")] InvalidSession, + #[error("the Modloader did not return a trampoline address for the staged callback")] + MissingTrampoline, #[error("the Modloader rejected invalid Patchy arguments")] InvalidArgument, #[error("a patch overlaps another patch; see the Modloader log")] @@ -47,6 +52,7 @@ struct Host { discard: HfmPatchSessionDiscardV1, overwrite: HfmPatchSessionOverwriteV1, install: HfmPatchSessionInstallV1, + patch_call: Option, } // SAFETY: The host ABI keeps the opaque context and callbacks live for the @@ -59,7 +65,8 @@ impl Host { /// A non-null pointer must provide two readable, aligned `u32` fields. /// If they report a supported version and sufficient size, the pointer /// must be aligned and valid for a full `HfmPatchApiV1`, and its context - /// and callbacks must satisfy the host ABI for process lifetime. + /// and callbacks must satisfy the host ABI for process lifetime. A table + /// advertising the callback extension must also be valid for that prefix. unsafe fn from_table(table: *const HfmPatchApiV1) -> Result { if table.is_null() { return Err(PatchError::NullTable); @@ -77,6 +84,12 @@ impl Host { if api.context.is_null() { return Err(PatchError::MissingContext); } + let patch_call = if size >= size_of::() as u32 { + let extended = table.cast::(); + unsafe { (&raw const (*extended).session_patch_call).read() } + } else { + None + }; Ok(Self { context: api.context, create: api @@ -91,6 +104,7 @@ impl Host { install: api .session_install .ok_or(PatchError::MissingCallback("session_install"))?, + patch_call, }) } } @@ -145,6 +159,69 @@ fn check_status(status: u32) -> Result { } } +/// Stack alignment when execution enters the call bridge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StackAlignment { + /// `RSP % 16 == 0`. + Aligned16, + /// `RSP % 16 == 8`. + Offset8, +} + +/// Which flags the bridge leaves after the call. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FlagPolicy { + /// Restore the incoming flags. + Preserve, + /// Leave the flags produced by the callback or `after_call`. + KeepProduced, +} + +/// Which callback return register the bridge leaves unrestored. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeepReturn { + /// Restore both RAX and XMM0. + Neither, + /// Keep the callback's result in RAX. + Rax, + /// Keep the callback's result in XMM0. + Xmm0, +} + +/// Describes a callback invocation. The loader emits the actual bridge. +#[derive(Clone, Copy, Debug)] +pub struct CallBridge<'a> { + pub callback: *const (), + pub incoming_stack: StackAlignment, + pub flags: FlagPolicy, + pub keep_return: KeepReturn, + pub before_call: &'a [u8], + pub after_call: &'a [u8], +} + +impl CallBridge<'_> { + fn request(&self) -> HfmCallBridgeV1 { + HfmCallBridgeV1 { + callback: self.callback as usize, + stack_alignment: match self.incoming_stack { + StackAlignment::Aligned16 => HFM_PATCH_STACK_ALIGNED_16, + StackAlignment::Offset8 => HFM_PATCH_STACK_OFFSET_8, + }, + flags: match self.flags { + FlagPolicy::Preserve => HFM_PATCH_FLAGS_PRESERVE, + FlagPolicy::KeepProduced => HFM_PATCH_FLAGS_KEEP_PRODUCED, + }, + keep_return: match self.keep_return { + KeepReturn::Neither => HFM_PATCH_RETURN_NEITHER, + KeepReturn::Rax => HFM_PATCH_RETURN_RAX, + KeepReturn::Xmm0 => HFM_PATCH_RETURN_XMM0, + }, + before_call: self.before_call.into(), + after_call: self.after_call.into(), + } + } +} + /// A pending batch, owned by the Modloader. Dropping it discards staged work. pub struct PatchSession { host: Host, @@ -206,6 +283,49 @@ impl PatchSession { Ok(Patch { trampoline: None }) } + /// Stages a callback followed by a jump to `address + size`, without + /// replaying the replaced instructions. + /// + /// # Safety + /// The span must stay readable through install, contain whole instructions, + /// and have no incoming jumps into its interior. The callback must use the + /// Windows x64 ABI without stack-passed arguments, must not unwind out of + /// the bridge, and must stay live for the process if installed. The + /// declared alignment must match RSP at the site, and the direction flag + /// must be clear. Both snippets must be position-independent, straight-line + /// code that falls through without changing RSP or the bridge's saved + /// state and is valid for the machine state in which it runs. + pub unsafe fn patch_call( + &mut self, + address: usize, + size: usize, + bridge: CallBridge<'_>, + ) -> Result { + let patch_call = self + .host + .patch_call + .ok_or(PatchError::MissingCallback("session_patch_call"))?; + let id = self.id.expect("live session").get(); + let mut output = 0; + check_status(unsafe { + patch_call( + self.host.context, + id, + "patch_call".into(), + address, + size, + &bridge.request(), + &mut output, + ) + })?; + let trampoline = (output != 0) + .then_some(output) + .ok_or(PatchError::MissingTrampoline)?; + Ok(Patch { + trampoline: Some(trampoline), + }) + } + /// Installs every staged patch. The host consumes the session even on error. /// /// # Safety @@ -233,6 +353,8 @@ pub struct Patch { impl Patch { /// Returns the trampoline address if the patch has one. + /// + /// Do not use the address unless and until session installation succeeds. pub fn trampoline_address(&self) -> Option { self.trampoline } diff --git a/crates/highfleet-patchy-client/src/tests.rs b/crates/highfleet-patchy-client/src/tests.rs index ec2f3d0..a40dfe3 100644 --- a/crates/highfleet-patchy-client/src/tests.rs +++ b/crates/highfleet-patchy-client/src/tests.rs @@ -5,6 +5,7 @@ use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; #[derive(Default)] struct Calls { stage_count: AtomicU32, + patch_call_count: AtomicU32, install_count: AtomicU32, discard_count: AtomicU32, install_status: AtomicU32, @@ -67,9 +68,49 @@ unsafe extern "C" fn install(context: *mut c_void, id: HfmPatchSessionId) -> u32 calls.install_status.load(Relaxed) } +extern "C" fn callback() {} + +unsafe extern "C" fn patch_call( + context: *mut c_void, + id: HfmPatchSessionId, + name: HfmStr, + address: usize, + size: usize, + bridge: *const HfmCallBridgeV1, + output: *mut usize, +) -> u32 { + let bridge = unsafe { &*bridge }; + if id != 12 + || address != 0x1000 + || size != 5 + || unsafe { std::slice::from_raw_parts(name.ptr, name.len) } != b"patch_call" + || bridge.callback != callback as *const () as usize + || bridge.stack_alignment != HFM_PATCH_STACK_OFFSET_8 + || bridge.flags != HFM_PATCH_FLAGS_KEEP_PRODUCED + || bridge.keep_return != HFM_PATCH_RETURN_RAX + || bridge.before_call.len != 1 + || unsafe { bridge.before_call.ptr.read() } != 0x90 + || bridge.after_call.len != 0 + { + return HFM_PATCH_INVALID_ARGUMENT; + } + unsafe { &*context.cast::() } + .patch_call_count + .fetch_add(1, Relaxed); + unsafe { output.write(0x2000) }; + HFM_PATCH_OK +} + fn mock() -> (&'static Calls, Host) { let calls = Box::leak(Box::new(Calls::default())); - let host = unsafe { Host::from_table(&table(calls)) }.unwrap(); + let api = HfmPatchApiWithCallV1 { + base: HfmPatchApiV1 { + struct_size: size_of::() as u32, + ..table(calls) + }, + session_patch_call: Some(patch_call), + }; + let host = unsafe { Host::from_table(std::ptr::from_ref(&api).cast()) }.unwrap(); (calls, host) } @@ -136,6 +177,39 @@ fn overwrite_forwards_the_request_to_its_host() { assert_eq!(patch.trampoline_address(), None); } +#[test] +fn patch_call_forwards_bridge_options_and_returns_the_trampoline_address() { + let (calls, host) = mock(); + let mut session = PatchSession::from_host(host).unwrap(); + let patch = unsafe { + session.patch_call( + 0x1000, + 5, + CallBridge { + callback: callback as *const (), + incoming_stack: StackAlignment::Offset8, + flags: FlagPolicy::KeepProduced, + keep_return: KeepReturn::Rax, + before_call: &[0x90], + after_call: &[], + }, + ) + } + .unwrap(); + assert_eq!(patch.trampoline_address(), Some(0x2000)); + assert_eq!(calls.patch_call_count.load(Relaxed), 1); +} + +#[test] +fn an_overwrite_only_table_can_still_create_a_session() { + let calls = Box::leak(Box::new(Calls::default())); + let host = unsafe { Host::from_table(&table(calls)) }.unwrap(); + let session = PatchSession::from_host(host).unwrap(); + assert!(session.host.patch_call.is_none()); + drop(session); + assert_eq!(calls.discard_count.load(Relaxed), 1); +} + #[test] fn dropping_a_pending_session_discards_it_without_installing() { let (calls, host) = mock(); diff --git a/src/loader.rs b/src/loader.rs index 57c3777..91d75c8 100644 --- a/src/loader.rs +++ b/src/loader.rs @@ -117,11 +117,19 @@ mod tests { let target = library .get:: u8>(b"patchy_test_target") .unwrap(); + let callback_result = library + .get:: u32>(b"patchy_test_callback_result") + .unwrap(); let version = startup_version(); - assert_eq!(version, UNKNOWN_VERSION, "the test runner is not a known game build"); + assert_eq!( + version, UNKNOWN_VERSION, + "the test runner is not a known game build" + ); assert_eq!(target(), 7); + assert_eq!(callback_result(), 8); super::load_mod(&path, &version); assert_eq!(target(), 42); + assert_eq!(callback_result(), 41); } } } diff --git a/tests/fixtures/patchy-mod/src/lib.rs b/tests/fixtures/patchy-mod/src/lib.rs index 59fa20a..cec8648 100644 --- a/tests/fixtures/patchy-mod/src/lib.rs +++ b/tests/fixtures/patchy-mod/src/lib.rs @@ -9,6 +9,42 @@ patchy::export_patchy!(); static mut TARGET: u8 = 7; static SAW_UNKNOWN_AFTER_SETUP: AtomicBool = AtomicBool::new(false); +#[cfg(all(windows, target_arch = "x86_64"))] +#[unsafe(naked)] +#[unsafe(no_mangle)] +pub extern "C" fn patchy_test_callback_result() -> u32 { + // First instruction: MOV EAX, 7 (five bytes). Continuation: ADD EAX, 1. + core::arch::naked_asm!(".byte 0xb8, 7, 0, 0, 0", "add eax, 1", "ret"); +} + +#[cfg(all(windows, target_arch = "x86_64"))] +fn stage_callback(session: &mut PatchSession) -> patchy::Result { + use patchy::{CallBridge, FlagPolicy, KeepReturn, StackAlignment}; + + extern "C" fn replacement() -> u32 { + 40 + } + + // SAFETY: The fixture owns the naked function, whose entry has RSP % 16 + // == 8. Its first instruction is exactly five bytes and the callback + // supplies the EAX value required by the continuation. + unsafe { + session.patch_call( + patchy_test_callback_result as *const () as usize, + 5, + CallBridge { + callback: replacement as *const (), + incoming_stack: StackAlignment::Offset8, + flags: FlagPolicy::Preserve, + keep_return: KeepReturn::Rax, + before_call: &[], + after_call: &[], + }, + )?; + } + Ok(()) +} + /// Declines every version to show that a rejected version keeps the service. #[unsafe(no_mangle)] unsafe extern "C" fn version(version: *const c_char) -> bool { @@ -28,6 +64,10 @@ unsafe extern "C" fn init() -> bool { let Ok(mut session) = PatchSession::new() else { return false; }; + #[cfg(all(windows, target_arch = "x86_64"))] + if stage_callback(&mut session).is_err() { + return false; + } // SAFETY: TARGET stays live and only this fixture touches it during init. unsafe { session From bcbdcfdc56db51702de34666de9d9707b9675da6 Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 10:37:31 -0600 Subject: [PATCH 3/5] Expose custom trampolines in the hosted Rust client --- Cargo.lock | 1 + README.md | 12 +- crates/highfleet-patchy-client/Cargo.toml | 1 + crates/highfleet-patchy-client/src/lib.rs | 219 +++++++++++++------- crates/highfleet-patchy-client/src/tests.rs | 92 +++++++- src/loader.rs | 7 + tests/fixtures/patchy-mod/src/lib.rs | 39 +++- 7 files changed, 289 insertions(+), 82 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bb9283f..c7ab564 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -238,6 +238,7 @@ name = "highfleet-patchy-client" version = "0.1.0" dependencies = [ "highfleet-mod-api", + "patchy-code", "thiserror 2.0.20", ] diff --git a/README.md b/README.md index 6178313..202c2a0 100644 --- a/README.md +++ b/README.md @@ -114,17 +114,19 @@ normally. Unknown builds and rejected version checks do not disable the service. Sessions are referred to by loader-issued 64-bit IDs. Zero is never issued, IDs are never reused, and an unknown, consumed, or another mod's ID is rejected -without affecting any session. The ABI is provisional and currently supports -byte overwrites and callback-only detours. +without affecting any session. The ABI is provisional and supports byte +overwrites, callback detours, and custom trampoline plans. Rust mods can alias the `highfleet-patchy-client` package as `patchy` in their manifest and call `patchy::export_patchy!()` once at the crate root. `PatchSession::new()` then returns a loader-owned session or an error if the service was unavailable or incompatible. `overwrite`, `patch_call`, and `install_permanently` use the usual Patchy call shape. `overwrite_named` -supplies a diagnostic name. There is no local Patchy fallback. Custom -trampolines and replay are not supported yet. See the -[test mod](tests/fixtures/patchy-mod/src/lib.rs) for a minimal example. +supplies a diagnostic name. `detour_trampoline_with` uses the shared Patchy +builder on the mod side, while the loader resolves placement, replay, and +resume. Replay is verbatim; it does not relocate displaced instructions. +There is no local Patchy fallback. See the +[test mod](tests/fixtures/patchy-mod/src/lib.rs) for examples. #### `init() -> bool` The modloader calls this function last. diff --git a/crates/highfleet-patchy-client/Cargo.toml b/crates/highfleet-patchy-client/Cargo.toml index 0404be3..e8d0870 100644 --- a/crates/highfleet-patchy-client/Cargo.toml +++ b/crates/highfleet-patchy-client/Cargo.toml @@ -6,4 +6,5 @@ publish = false [dependencies] highfleet-mod-api = { path = "../highfleet-mod-api" } +patchy-code = { git = "https://github.com/logdot/patchy-rs.git", rev = "64d2eac7b33f81c4a60f18ae834d9daba96b92cf" } thiserror = "2" diff --git a/crates/highfleet-patchy-client/src/lib.rs b/crates/highfleet-patchy-client/src/lib.rs index e863d62..5abbd63 100644 --- a/crates/highfleet-patchy-client/src/lib.rs +++ b/crates/highfleet-patchy-client/src/lib.rs @@ -4,14 +4,20 @@ //! [`export_patchy!`] once. This crate never links the local patch engine. use highfleet_mod_api::patching::{ - HfmCallBridgeV1, HfmPatchApiV1, HfmPatchApiWithCallV1, HfmPatchSessionCreateV1, - HfmPatchSessionDiscardV1, HfmPatchSessionId, HfmPatchSessionInstallV1, - HfmPatchSessionOverwriteV1, HfmPatchSessionPatchCallV1, HFM_PATCH_ABI_VERSION_1, - HFM_PATCH_FAILED, HFM_PATCH_FLAGS_KEEP_PRODUCED, HFM_PATCH_FLAGS_PRESERVE, - HFM_PATCH_INVALID_ARGUMENT, HFM_PATCH_OK, HFM_PATCH_OVERLAP, HFM_PATCH_RETURN_NEITHER, - HFM_PATCH_RETURN_RAX, HFM_PATCH_RETURN_XMM0, HFM_PATCH_SOURCE_CHANGED, - HFM_PATCH_STACK_ALIGNED_16, HFM_PATCH_STACK_OFFSET_8, + HfmCallBridgeV1, HfmPatchApiV1, HfmPatchApiWithCallV1, HfmPatchApiWithDetourV1, + HfmPatchSessionCreateV1, HfmPatchSessionDetourV1, HfmPatchSessionDiscardV1, HfmPatchSessionId, + HfmPatchSessionInstallV1, HfmPatchSessionOverwriteV1, HfmPatchSessionPatchCallV1, + HfmTrampolineFixupV1, HfmTrampolinePlanV1, HFM_PATCH_ABI_VERSION_1, HFM_PATCH_FAILED, + HFM_PATCH_FIXUP_RELATIVE, HFM_PATCH_FIXUP_REPLAY, HFM_PATCH_FIXUP_RESUME, + HFM_PATCH_FLAGS_KEEP_PRODUCED, HFM_PATCH_FLAGS_PRESERVE, HFM_PATCH_INVALID_ARGUMENT, + HFM_PATCH_OK, HFM_PATCH_OVERLAP, HFM_PATCH_RETURN_NEITHER, HFM_PATCH_RETURN_RAX, + HFM_PATCH_RETURN_XMM0, HFM_PATCH_SOURCE_CHANGED, HFM_PATCH_STACK_ALIGNED_16, + HFM_PATCH_STACK_OFFSET_8, }; +pub use patchy_code::{ + CallBridge, Condition, DetourSite, FlagPolicy, KeepReturn, Label, StackAlignment, Trampoline, +}; +use patchy_code::{TrampolineFixup, TrampolinePlan}; use std::{ffi::c_void, mem::size_of, num::NonZeroU64, sync::OnceLock}; pub type Result = std::result::Result; @@ -33,7 +39,7 @@ pub enum PatchError { MissingCallback(&'static str), #[error("the Modloader returned an invalid Patchy session ID")] InvalidSession, - #[error("the Modloader did not return a trampoline address for the staged callback")] + #[error("the Modloader did not return a trampoline address for the staged detour")] MissingTrampoline, #[error("the Modloader rejected invalid Patchy arguments")] InvalidArgument, @@ -43,6 +49,14 @@ pub enum PatchError { SourceChanged, #[error("the Modloader Patchy operation failed (status {0}); if installing, writes may have occurred")] HostFailure(u32), + #[error(transparent)] + Builder(std::sync::Arc), +} + +impl From for PatchError { + fn from(error: patchy_code::PatchError) -> Self { + Self::Builder(error.into()) + } } #[derive(Clone, Copy)] @@ -53,6 +67,7 @@ struct Host { overwrite: HfmPatchSessionOverwriteV1, install: HfmPatchSessionInstallV1, patch_call: Option, + detour: Option, } // SAFETY: The host ABI keeps the opaque context and callbacks live for the @@ -66,7 +81,7 @@ impl Host { /// If they report a supported version and sufficient size, the pointer /// must be aligned and valid for a full `HfmPatchApiV1`, and its context /// and callbacks must satisfy the host ABI for process lifetime. A table - /// advertising the callback extension must also be valid for that prefix. + /// advertising an extension must also be valid for that prefix. unsafe fn from_table(table: *const HfmPatchApiV1) -> Result { if table.is_null() { return Err(PatchError::NullTable); @@ -90,6 +105,12 @@ impl Host { } else { None }; + let detour = if size >= size_of::() as u32 { + let extended = table.cast::(); + unsafe { (&raw const (*extended).session_detour).read() } + } else { + None + }; Ok(Self { context: api.context, create: api @@ -105,6 +126,7 @@ impl Host { .session_install .ok_or(PatchError::MissingCallback("session_install"))?, patch_call, + detour, }) } } @@ -159,67 +181,48 @@ fn check_status(status: u32) -> Result { } } -/// Stack alignment when execution enters the call bridge. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum StackAlignment { - /// `RSP % 16 == 0`. - Aligned16, - /// `RSP % 16 == 8`. - Offset8, -} - -/// Which flags the bridge leaves after the call. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FlagPolicy { - /// Restore the incoming flags. - Preserve, - /// Leave the flags produced by the callback or `after_call`. - KeepProduced, -} - -/// Which callback return register the bridge leaves unrestored. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum KeepReturn { - /// Restore both RAX and XMM0. - Neither, - /// Keep the callback's result in RAX. - Rax, - /// Keep the callback's result in XMM0. - Xmm0, -} - -/// Describes a callback invocation. The loader emits the actual bridge. -#[derive(Clone, Copy, Debug)] -pub struct CallBridge<'a> { - pub callback: *const (), - pub incoming_stack: StackAlignment, - pub flags: FlagPolicy, - pub keep_return: KeepReturn, - pub before_call: &'a [u8], - pub after_call: &'a [u8], +fn bridge_request(bridge: CallBridge<'_>) -> HfmCallBridgeV1 { + HfmCallBridgeV1 { + callback: bridge.callback as usize, + stack_alignment: match bridge.incoming_stack { + StackAlignment::Aligned16 => HFM_PATCH_STACK_ALIGNED_16, + StackAlignment::Offset8 => HFM_PATCH_STACK_OFFSET_8, + }, + flags: match bridge.flags { + FlagPolicy::Preserve => HFM_PATCH_FLAGS_PRESERVE, + FlagPolicy::KeepProduced => HFM_PATCH_FLAGS_KEEP_PRODUCED, + }, + keep_return: match bridge.keep_return { + KeepReturn::Neither => HFM_PATCH_RETURN_NEITHER, + KeepReturn::Rax => HFM_PATCH_RETURN_RAX, + KeepReturn::Xmm0 => HFM_PATCH_RETURN_XMM0, + }, + before_call: bridge.before_call.into(), + after_call: bridge.after_call.into(), + } } -impl CallBridge<'_> { - fn request(&self) -> HfmCallBridgeV1 { - HfmCallBridgeV1 { - callback: self.callback as usize, - stack_alignment: match self.incoming_stack { - StackAlignment::Aligned16 => HFM_PATCH_STACK_ALIGNED_16, - StackAlignment::Offset8 => HFM_PATCH_STACK_OFFSET_8, - }, - flags: match self.flags { - FlagPolicy::Preserve => HFM_PATCH_FLAGS_PRESERVE, - FlagPolicy::KeepProduced => HFM_PATCH_FLAGS_KEEP_PRODUCED, - }, - keep_return: match self.keep_return { - KeepReturn::Neither => HFM_PATCH_RETURN_NEITHER, - KeepReturn::Rax => HFM_PATCH_RETURN_RAX, - KeepReturn::Xmm0 => HFM_PATCH_RETURN_XMM0, - }, - before_call: self.before_call.into(), - after_call: self.after_call.into(), - } - } +fn encode_fixups(plan: &TrampolinePlan) -> Vec { + plan.parts() + .1 + .iter() + .map(|&fixup| { + let (kind, offset, argument) = match fixup { + TrampolineFixup::Replay { offset, size } => (HFM_PATCH_FIXUP_REPLAY, offset, size), + TrampolineFixup::Relative { + offset, + destination, + } => (HFM_PATCH_FIXUP_RELATIVE, offset, destination), + TrampolineFixup::Resume { offset } => (HFM_PATCH_FIXUP_RESUME, offset, 0), + }; + HfmTrampolineFixupV1 { + kind, + reserved: 0, + offset, + argument, + } + }) + .collect() } /// A pending batch, owned by the Modloader. Dropping it discards staged work. @@ -314,16 +317,73 @@ impl PatchSession { "patch_call".into(), address, size, - &bridge.request(), + &bridge_request(bridge), &mut output, ) })?; - let trampoline = (output != 0) - .then_some(output) - .ok_or(PatchError::MissingTrampoline)?; - Ok(Patch { - trampoline: Some(trampoline), - }) + Patch::from_trampoline(output) + } + + /// Stages an already built custom trampoline. + /// + /// # Safety + /// The site and trampoline must satisfy [`Self::detour_trampoline_with`]. + pub unsafe fn detour_trampoline( + &mut self, + address: usize, + size: usize, + trampoline: Trampoline, + ) -> Result { + unsafe { self.detour_trampoline_with(address, size, |_| Ok(trampoline)) } + } + + /// Builds a custom trampoline locally, then sends the compiled plan to + /// the loader. The host captures the source bytes and resolves placement. + /// No closure crosses the ABI. + /// + /// # Safety + /// The source span must remain readable through installation, consist of + /// whole instructions, and have no incoming branches into its interior. + /// The generated code must leave valid machine state on every exit. + /// Any replay must satisfy [`DetourSite::replay_verbatim`], and referenced + /// callbacks and data must stay live through process exit if installed. + pub unsafe fn detour_trampoline_with( + &mut self, + address: usize, + size: usize, + build: F, + ) -> Result + where + F: FnOnce(DetourSite) -> Result, + { + let detour = self + .host + .detour + .ok_or(PatchError::MissingCallback("session_detour"))?; + if address == 0 || size < 5 || address.checked_add(size).is_none() { + return Err(PatchError::InvalidArgument); + } + let plan = build(DetourSite::new(size))?.into_plan()?; + let fixups = encode_fixups(&plan); + let request = HfmTrampolinePlanV1 { + template: plan.parts().0.into(), + fixups: fixups.as_ptr(), + fixup_count: fixups.len(), + }; + let id = self.id.expect("live session").get(); + let mut output = 0; + check_status(unsafe { + detour( + self.host.context, + id, + "detour".into(), + address, + size, + &request, + &mut output, + ) + })?; + Patch::from_trampoline(output) } /// Installs every staged patch. The host consumes the session even on error. @@ -352,6 +412,15 @@ pub struct Patch { } impl Patch { + fn from_trampoline(address: usize) -> Result { + let trampoline = (address != 0) + .then_some(address) + .ok_or(PatchError::MissingTrampoline)?; + Ok(Self { + trampoline: Some(trampoline), + }) + } + /// Returns the trampoline address if the patch has one. /// /// Do not use the address unless and until session installation succeeds. diff --git a/crates/highfleet-patchy-client/src/tests.rs b/crates/highfleet-patchy-client/src/tests.rs index a40dfe3..6008fba 100644 --- a/crates/highfleet-patchy-client/src/tests.rs +++ b/crates/highfleet-patchy-client/src/tests.rs @@ -6,6 +6,7 @@ use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; struct Calls { stage_count: AtomicU32, patch_call_count: AtomicU32, + detour_count: AtomicU32, install_count: AtomicU32, discard_count: AtomicU32, install_status: AtomicU32, @@ -102,6 +103,75 @@ unsafe extern "C" fn patch_call( } fn mock() -> (&'static Calls, Host) { + let calls = Box::leak(Box::new(Calls::default())); + let api = HfmPatchApiWithDetourV1 { + base: HfmPatchApiWithCallV1 { + base: HfmPatchApiV1 { + struct_size: size_of::() as u32, + ..table(calls) + }, + session_patch_call: Some(patch_call), + }, + session_detour: Some(detour), + }; + let host = unsafe { Host::from_table(std::ptr::from_ref(&api).cast()) }.unwrap(); + (calls, host) +} + +unsafe extern "C" fn detour( + context: *mut c_void, + id: HfmPatchSessionId, + _name: HfmStr, + address: usize, + size: usize, + request: *const HfmTrampolinePlanV1, + output: *mut usize, +) -> u32 { + let request = unsafe { &*request }; + let template = + unsafe { std::slice::from_raw_parts(request.template.ptr, request.template.len) }; + let fixups = unsafe { std::slice::from_raw_parts(request.fixups, request.fixup_count) }; + let expected = [ + (HFM_PATCH_FIXUP_REPLAY, 0, 5), + (HFM_PATCH_FIXUP_RESUME, 6, 0), + ]; + if id != 12 + || address != 0x1000 + || size != 5 + || template != [0, 0, 0, 0, 0, 0xe9, 0, 0, 0, 0] + || fixups.len() != expected.len() + || fixups.iter().zip(expected).any(|(record, expected)| { + record.reserved != 0 || (record.kind, record.offset, record.argument) != expected + }) + { + return HFM_PATCH_INVALID_ARGUMENT; + } + unsafe { &*context.cast::() } + .detour_count + .fetch_add(1, Relaxed); + unsafe { output.write(0x3000) }; + HFM_PATCH_OK +} + +#[test] +fn custom_detour_sends_replay_and_resume_as_fixups() { + let (calls, host) = mock(); + let mut session = PatchSession::from_host(host).unwrap(); + let patch = unsafe { + session.detour_trampoline_with(0x1000, 5, |site| { + let mut code = Trampoline::new(); + site.replay_verbatim(&mut code); + site.resume(&mut code); + Ok(code) + }) + } + .unwrap(); + assert_eq!(patch.trampoline_address(), Some(0x3000)); + assert_eq!(calls.detour_count.load(Relaxed), 1); +} + +#[test] +fn a_callback_only_host_rejects_custom_detours_before_running_the_builder() { let calls = Box::leak(Box::new(Calls::default())); let api = HfmPatchApiWithCallV1 { base: HfmPatchApiV1 { @@ -111,7 +181,27 @@ fn mock() -> (&'static Calls, Host) { session_patch_call: Some(patch_call), }; let host = unsafe { Host::from_table(std::ptr::from_ref(&api).cast()) }.unwrap(); - (calls, host) + let mut session = PatchSession::from_host(host).unwrap(); + let result = unsafe { + session.detour_trampoline_with(0x1000, 5, |_| panic!("unsupported host ran the builder")) + }; + assert!(matches!( + result, + Err(PatchError::MissingCallback("session_detour")) + )); +} + +#[test] +fn a_relative_jump_encodes_the_absolute_target_in_its_fixup() { + let mut code = Trampoline::new(); + code.relative_jump(0x3000); + let plan = code.into_plan().unwrap(); + let fixups = encode_fixups(&plan); + assert_eq!(fixups.len(), 1); + let fixup = &fixups[0]; + assert_eq!(fixup.kind, HFM_PATCH_FIXUP_RELATIVE); + assert_eq!(fixup.offset, 1); + assert_eq!(fixup.argument, 0x3000); } #[test] diff --git a/src/loader.rs b/src/loader.rs index 91d75c8..993d60f 100644 --- a/src/loader.rs +++ b/src/loader.rs @@ -120,6 +120,9 @@ mod tests { let callback_result = library .get:: u32>(b"patchy_test_callback_result") .unwrap(); + let replay_result = library + .get:: u32>(b"patchy_test_replay_result") + .unwrap(); let version = startup_version(); assert_eq!( version, UNKNOWN_VERSION, @@ -127,9 +130,13 @@ mod tests { ); assert_eq!(target(), 7); assert_eq!(callback_result(), 8); + assert_eq!(replay_result(0), 3); + assert_eq!(replay_result(7), 10); super::load_mod(&path, &version); assert_eq!(target(), 42); assert_eq!(callback_result(), 41); + assert_eq!(replay_result(0), 3); + assert_eq!(replay_result(7), 8); } } } diff --git a/tests/fixtures/patchy-mod/src/lib.rs b/tests/fixtures/patchy-mod/src/lib.rs index cec8648..939ad51 100644 --- a/tests/fixtures/patchy-mod/src/lib.rs +++ b/tests/fixtures/patchy-mod/src/lib.rs @@ -45,6 +45,40 @@ fn stage_callback(session: &mut PatchSession) -> patchy::Result { Ok(()) } +#[cfg(all(windows, target_arch = "x86_64"))] +#[unsafe(naked)] +#[unsafe(no_mangle)] +pub extern "C" fn patchy_test_replay_result(_value: u32) -> u32 { + core::arch::naked_asm!( + ".byte 0x89, 0xc8", // MOV EAX, ECX + ".byte 0x83, 0xc0, 0x02, 0x66, 0x90", // ADD EAX, 2; NOP (five-byte site) + "add eax, 1", + "ret", + ); +} + +#[cfg(all(windows, target_arch = "x86_64"))] +fn stage_conditional_replay(session: &mut PatchSession) -> patchy::Result { + use patchy::{Condition, Trampoline}; + + let address = patchy_test_replay_result as *const () as usize + 2; + // SAFETY: The fixture owns the source and only calls it before or after + // installation. The displaced instructions can be replayed verbatim. + unsafe { + session.detour_trampoline_with(address, 5, |site| { + let mut code = Trampoline::new(); + let skip = code.new_label(); + code.bytes(&[0x85, 0xc9]); // TEST ECX, ECX + code.jump_if(Condition::NotEqual, skip); + site.replay_verbatim(&mut code); + code.bind(skip)?; + site.resume(&mut code); + Ok(code) + })?; + } + Ok(()) +} + /// Declines every version to show that a rejected version keeps the service. #[unsafe(no_mangle)] unsafe extern "C" fn version(version: *const c_char) -> bool { @@ -65,7 +99,10 @@ unsafe extern "C" fn init() -> bool { return false; }; #[cfg(all(windows, target_arch = "x86_64"))] - if stage_callback(&mut session).is_err() { + if stage_callback(&mut session) + .and_then(|()| stage_conditional_replay(&mut session)) + .is_err() + { return false; } // SAFETY: TARGET stays live and only this fixture touches it during init. From 9e61bb7f728986fb6e3d471c2725367eed9d88d2 Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 10:51:12 -0600 Subject: [PATCH 4/5] Expose module lookup and legacy call options to hosted mods --- Cargo.lock | 1 + crates/highfleet-patchy-client/Cargo.toml | 3 + crates/highfleet-patchy-client/src/lib.rs | 6 +- .../src/process_module.rs | 61 +++++++++++++++++++ 4 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 crates/highfleet-patchy-client/src/process_module.rs diff --git a/Cargo.lock b/Cargo.lock index c7ab564..aa2dfc3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -240,6 +240,7 @@ dependencies = [ "highfleet-mod-api", "patchy-code", "thiserror 2.0.20", + "windows-sys", ] [[package]] diff --git a/crates/highfleet-patchy-client/Cargo.toml b/crates/highfleet-patchy-client/Cargo.toml index e8d0870..d70003f 100644 --- a/crates/highfleet-patchy-client/Cargo.toml +++ b/crates/highfleet-patchy-client/Cargo.toml @@ -8,3 +8,6 @@ publish = false highfleet-mod-api = { path = "../highfleet-mod-api" } patchy-code = { git = "https://github.com/logdot/patchy-rs.git", rev = "64d2eac7b33f81c4a60f18ae834d9daba96b92cf" } thiserror = "2" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_System_LibraryLoader"] } diff --git a/crates/highfleet-patchy-client/src/lib.rs b/crates/highfleet-patchy-client/src/lib.rs index 5abbd63..b5c07e3 100644 --- a/crates/highfleet-patchy-client/src/lib.rs +++ b/crates/highfleet-patchy-client/src/lib.rs @@ -15,11 +15,15 @@ use highfleet_mod_api::patching::{ HFM_PATCH_STACK_OFFSET_8, }; pub use patchy_code::{ - CallBridge, Condition, DetourSite, FlagPolicy, KeepReturn, Label, StackAlignment, Trampoline, + CallBridge, Condition, DetourSite, FlagPolicy, KeepReturn, Label, ReturnType, StackAlignment, + Trampoline, }; use patchy_code::{TrampolineFixup, TrampolinePlan}; use std::{ffi::c_void, mem::size_of, num::NonZeroU64, sync::OnceLock}; +mod process_module; +pub use process_module::ProcessModule; + pub type Result = std::result::Result; #[derive(Clone, Debug, thiserror::Error)] diff --git a/crates/highfleet-patchy-client/src/process_module.rs b/crates/highfleet-patchy-client/src/process_module.rs new file mode 100644 index 0000000..6519a5f --- /dev/null +++ b/crates/highfleet-patchy-client/src/process_module.rs @@ -0,0 +1,61 @@ +use crate::Result; + +/// A loaded module in the current process. +/// +/// Module lookup and address arithmetic don't need a patch session or access +/// to the loader's patch engine. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProcessModule { + base: usize, +} + +impl ProcessModule { + /// Finds the main executable of the current Windows process. + #[cfg(windows)] + pub fn main() -> Result { + use patchy_code::PatchError; + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + + // SAFETY: A null name requests the current executable. + let module = unsafe { GetModuleHandleW(std::ptr::null()) }; + if module.is_null() { + let error = std::io::Error::last_os_error(); + return Err(PatchError::ModuleLookup(error.to_string()).into()); + } + Ok(Self::from_base(module as usize)) + } + + /// Creates a descriptor without checking that a module is loaded there. + pub const fn from_base(base: usize) -> Self { + Self { base } + } + + /// Returns the module's runtime base address. + pub const fn base_address(self) -> usize { + self.base + } + + /// Resolves an RVA against this module, rejecting address overflow. + pub fn resolve_rva(self, rva: usize) -> Result { + self.base + .checked_add(rva) + .ok_or_else(|| patchy_code::PatchError::AddressOverflow.into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_rvas_against_the_supplied_base() { + let module = ProcessModule::from_base(0x140000000); + assert_eq!(module.base_address(), 0x140000000); + assert_eq!(module.resolve_rva(0x36bb5).unwrap(), 0x140036bb5); + } + + #[test] + fn rejects_an_rva_that_would_wrap_the_address() { + assert!(ProcessModule::from_base(usize::MAX).resolve_rva(1).is_err()); + } +} From ae0d55f390fad752e38930983fd208997316f2e0 Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 11:45:31 -0600 Subject: [PATCH 5/5] Route hosted callbacks through trampoline plans --- README.md | 5 +- crates/highfleet-patchy-client/src/lib.rs | 105 ++++++-------------- crates/highfleet-patchy-client/src/tests.rs | 102 +++++-------------- 3 files changed, 63 insertions(+), 149 deletions(-) diff --git a/README.md b/README.md index 202c2a0..8f0cdbb 100644 --- a/README.md +++ b/README.md @@ -114,8 +114,9 @@ normally. Unknown builds and rejected version checks do not disable the service. Sessions are referred to by loader-issued 64-bit IDs. Zero is never issued, IDs are never reused, and an unknown, consumed, or another mod's ID is rejected -without affecting any session. The ABI is provisional and supports byte -overwrites, callback detours, and custom trampoline plans. +without affecting any session. The ABI is provisional and accepts either a +byte overwrite or a trampoline plan. It is separate from Patchy's standalone +C ABI; mods using the standalone library do not share the loader's registry. Rust mods can alias the `highfleet-patchy-client` package as `patchy` in their manifest and call `patchy::export_patchy!()` once at the crate root. diff --git a/crates/highfleet-patchy-client/src/lib.rs b/crates/highfleet-patchy-client/src/lib.rs index b5c07e3..5b581cc 100644 --- a/crates/highfleet-patchy-client/src/lib.rs +++ b/crates/highfleet-patchy-client/src/lib.rs @@ -4,15 +4,11 @@ //! [`export_patchy!`] once. This crate never links the local patch engine. use highfleet_mod_api::patching::{ - HfmCallBridgeV1, HfmPatchApiV1, HfmPatchApiWithCallV1, HfmPatchApiWithDetourV1, - HfmPatchSessionCreateV1, HfmPatchSessionDetourV1, HfmPatchSessionDiscardV1, HfmPatchSessionId, - HfmPatchSessionInstallV1, HfmPatchSessionOverwriteV1, HfmPatchSessionPatchCallV1, - HfmTrampolineFixupV1, HfmTrampolinePlanV1, HFM_PATCH_ABI_VERSION_1, HFM_PATCH_FAILED, - HFM_PATCH_FIXUP_RELATIVE, HFM_PATCH_FIXUP_REPLAY, HFM_PATCH_FIXUP_RESUME, - HFM_PATCH_FLAGS_KEEP_PRODUCED, HFM_PATCH_FLAGS_PRESERVE, HFM_PATCH_INVALID_ARGUMENT, - HFM_PATCH_OK, HFM_PATCH_OVERLAP, HFM_PATCH_RETURN_NEITHER, HFM_PATCH_RETURN_RAX, - HFM_PATCH_RETURN_XMM0, HFM_PATCH_SOURCE_CHANGED, HFM_PATCH_STACK_ALIGNED_16, - HFM_PATCH_STACK_OFFSET_8, + HfmPatchApiV1, HfmPatchSessionCreateV1, HfmPatchSessionDetourV1, HfmPatchSessionDiscardV1, + HfmPatchSessionId, HfmPatchSessionInstallV1, HfmPatchSessionOverwriteV1, HfmTrampolineFixupV1, + HfmTrampolinePlanV1, HFM_PATCH_ABI_VERSION_1, HFM_PATCH_FAILED, HFM_PATCH_FIXUP_RELATIVE, + HFM_PATCH_FIXUP_REPLAY, HFM_PATCH_FIXUP_RESUME, HFM_PATCH_INVALID_ARGUMENT, HFM_PATCH_OK, + HFM_PATCH_OVERLAP, HFM_PATCH_SOURCE_CHANGED, }; pub use patchy_code::{ CallBridge, Condition, DetourSite, FlagPolicy, KeepReturn, Label, ReturnType, StackAlignment, @@ -70,8 +66,7 @@ struct Host { discard: HfmPatchSessionDiscardV1, overwrite: HfmPatchSessionOverwriteV1, install: HfmPatchSessionInstallV1, - patch_call: Option, - detour: Option, + detour: HfmPatchSessionDetourV1, } // SAFETY: The host ABI keeps the opaque context and callbacks live for the @@ -84,8 +79,7 @@ impl Host { /// A non-null pointer must provide two readable, aligned `u32` fields. /// If they report a supported version and sufficient size, the pointer /// must be aligned and valid for a full `HfmPatchApiV1`, and its context - /// and callbacks must satisfy the host ABI for process lifetime. A table - /// advertising an extension must also be valid for that prefix. + /// and callbacks must satisfy the host ABI for process lifetime. unsafe fn from_table(table: *const HfmPatchApiV1) -> Result { if table.is_null() { return Err(PatchError::NullTable); @@ -103,18 +97,6 @@ impl Host { if api.context.is_null() { return Err(PatchError::MissingContext); } - let patch_call = if size >= size_of::() as u32 { - let extended = table.cast::(); - unsafe { (&raw const (*extended).session_patch_call).read() } - } else { - None - }; - let detour = if size >= size_of::() as u32 { - let extended = table.cast::(); - unsafe { (&raw const (*extended).session_detour).read() } - } else { - None - }; Ok(Self { context: api.context, create: api @@ -129,8 +111,9 @@ impl Host { install: api .session_install .ok_or(PatchError::MissingCallback("session_install"))?, - patch_call, - detour, + detour: api + .session_detour + .ok_or(PatchError::MissingCallback("session_detour"))?, }) } } @@ -185,27 +168,6 @@ fn check_status(status: u32) -> Result { } } -fn bridge_request(bridge: CallBridge<'_>) -> HfmCallBridgeV1 { - HfmCallBridgeV1 { - callback: bridge.callback as usize, - stack_alignment: match bridge.incoming_stack { - StackAlignment::Aligned16 => HFM_PATCH_STACK_ALIGNED_16, - StackAlignment::Offset8 => HFM_PATCH_STACK_OFFSET_8, - }, - flags: match bridge.flags { - FlagPolicy::Preserve => HFM_PATCH_FLAGS_PRESERVE, - FlagPolicy::KeepProduced => HFM_PATCH_FLAGS_KEEP_PRODUCED, - }, - keep_return: match bridge.keep_return { - KeepReturn::Neither => HFM_PATCH_RETURN_NEITHER, - KeepReturn::Rax => HFM_PATCH_RETURN_RAX, - KeepReturn::Xmm0 => HFM_PATCH_RETURN_XMM0, - }, - before_call: bridge.before_call.into(), - after_call: bridge.after_call.into(), - } -} - fn encode_fixups(plan: &TrampolinePlan) -> Vec { plan.parts() .1 @@ -308,24 +270,17 @@ impl PatchSession { size: usize, bridge: CallBridge<'_>, ) -> Result { - let patch_call = self - .host - .patch_call - .ok_or(PatchError::MissingCallback("session_patch_call"))?; - let id = self.id.expect("live session").get(); - let mut output = 0; - check_status(unsafe { - patch_call( - self.host.context, - id, - "patch_call".into(), - address, - size, - &bridge_request(bridge), - &mut output, - ) - })?; - Patch::from_trampoline(output) + if bridge.callback.is_null() { + return Err(PatchError::InvalidArgument); + } + unsafe { + self.stage_detour("patch_call", address, size, |site| { + let mut code = Trampoline::new(); + code.call(bridge); + site.resume(&mut code); + Ok(code) + }) + } } /// Stages an already built custom trampoline. @@ -360,10 +315,16 @@ impl PatchSession { where F: FnOnce(DetourSite) -> Result, { - let detour = self - .host - .detour - .ok_or(PatchError::MissingCallback("session_detour"))?; + unsafe { self.stage_detour("detour", address, size, build) } + } + + unsafe fn stage_detour( + &mut self, + name: &str, + address: usize, + size: usize, + build: impl FnOnce(DetourSite) -> Result, + ) -> Result { if address == 0 || size < 5 || address.checked_add(size).is_none() { return Err(PatchError::InvalidArgument); } @@ -377,10 +338,10 @@ impl PatchSession { let id = self.id.expect("live session").get(); let mut output = 0; check_status(unsafe { - detour( + (self.host.detour)( self.host.context, id, - "detour".into(), + name.into(), address, size, &request, diff --git a/crates/highfleet-patchy-client/src/tests.rs b/crates/highfleet-patchy-client/src/tests.rs index 6008fba..1f39c1c 100644 --- a/crates/highfleet-patchy-client/src/tests.rs +++ b/crates/highfleet-patchy-client/src/tests.rs @@ -5,7 +5,6 @@ use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; #[derive(Default)] struct Calls { stage_count: AtomicU32, - patch_call_count: AtomicU32, detour_count: AtomicU32, install_count: AtomicU32, discard_count: AtomicU32, @@ -21,6 +20,7 @@ fn table(calls: &'static Calls) -> HfmPatchApiV1 { session_discard: Some(discard), session_overwrite: Some(overwrite), session_install: Some(install), + session_detour: Some(detour), } } @@ -71,57 +71,16 @@ unsafe extern "C" fn install(context: *mut c_void, id: HfmPatchSessionId) -> u32 extern "C" fn callback() {} -unsafe extern "C" fn patch_call( - context: *mut c_void, - id: HfmPatchSessionId, - name: HfmStr, - address: usize, - size: usize, - bridge: *const HfmCallBridgeV1, - output: *mut usize, -) -> u32 { - let bridge = unsafe { &*bridge }; - if id != 12 - || address != 0x1000 - || size != 5 - || unsafe { std::slice::from_raw_parts(name.ptr, name.len) } != b"patch_call" - || bridge.callback != callback as *const () as usize - || bridge.stack_alignment != HFM_PATCH_STACK_OFFSET_8 - || bridge.flags != HFM_PATCH_FLAGS_KEEP_PRODUCED - || bridge.keep_return != HFM_PATCH_RETURN_RAX - || bridge.before_call.len != 1 - || unsafe { bridge.before_call.ptr.read() } != 0x90 - || bridge.after_call.len != 0 - { - return HFM_PATCH_INVALID_ARGUMENT; - } - unsafe { &*context.cast::() } - .patch_call_count - .fetch_add(1, Relaxed); - unsafe { output.write(0x2000) }; - HFM_PATCH_OK -} - fn mock() -> (&'static Calls, Host) { let calls = Box::leak(Box::new(Calls::default())); - let api = HfmPatchApiWithDetourV1 { - base: HfmPatchApiWithCallV1 { - base: HfmPatchApiV1 { - struct_size: size_of::() as u32, - ..table(calls) - }, - session_patch_call: Some(patch_call), - }, - session_detour: Some(detour), - }; - let host = unsafe { Host::from_table(std::ptr::from_ref(&api).cast()) }.unwrap(); + let host = unsafe { Host::from_table(&table(calls)) }.unwrap(); (calls, host) } unsafe extern "C" fn detour( context: *mut c_void, id: HfmPatchSessionId, - _name: HfmStr, + name: HfmStr, address: usize, size: usize, request: *const HfmTrampolinePlanV1, @@ -131,14 +90,25 @@ unsafe extern "C" fn detour( let template = unsafe { std::slice::from_raw_parts(request.template.ptr, request.template.len) }; let fixups = unsafe { std::slice::from_raw_parts(request.fixups, request.fixup_count) }; - let expected = [ - (HFM_PATCH_FIXUP_REPLAY, 0, 5), - (HFM_PATCH_FIXUP_RESUME, 6, 0), - ]; + let name = unsafe { std::slice::from_raw_parts(name.ptr, name.len) }; + let expected = match name { + b"patch_call" + if template.ends_with(&[0xe9, 0, 0, 0, 0]) + && template + .windows(8) + .any(|bytes| bytes == (callback as *const () as usize).to_le_bytes()) => + { + vec![(HFM_PATCH_FIXUP_RESUME, template.len() - 4, 0)] + } + b"detour" if template == [0, 0, 0, 0, 0, 0xe9, 0, 0, 0, 0] => vec![ + (HFM_PATCH_FIXUP_REPLAY, 0, 5), + (HFM_PATCH_FIXUP_RESUME, 6, 0), + ], + _ => return HFM_PATCH_INVALID_ARGUMENT, + }; if id != 12 || address != 0x1000 || size != 5 - || template != [0, 0, 0, 0, 0, 0xe9, 0, 0, 0, 0] || fixups.len() != expected.len() || fixups.iter().zip(expected).any(|(record, expected)| { record.reserved != 0 || (record.kind, record.offset, record.argument) != expected @@ -171,22 +141,14 @@ fn custom_detour_sends_replay_and_resume_as_fixups() { } #[test] -fn a_callback_only_host_rejects_custom_detours_before_running_the_builder() { +fn a_host_without_a_detour_callback_is_rejected_at_setup() { let calls = Box::leak(Box::new(Calls::default())); - let api = HfmPatchApiWithCallV1 { - base: HfmPatchApiV1 { - struct_size: size_of::() as u32, - ..table(calls) - }, - session_patch_call: Some(patch_call), - }; - let host = unsafe { Host::from_table(std::ptr::from_ref(&api).cast()) }.unwrap(); - let mut session = PatchSession::from_host(host).unwrap(); - let result = unsafe { - session.detour_trampoline_with(0x1000, 5, |_| panic!("unsupported host ran the builder")) + let api = HfmPatchApiV1 { + session_detour: None, + ..table(calls) }; assert!(matches!( - result, + unsafe { Host::from_table(&api) }, Err(PatchError::MissingCallback("session_detour")) )); } @@ -268,7 +230,7 @@ fn overwrite_forwards_the_request_to_its_host() { } #[test] -fn patch_call_forwards_bridge_options_and_returns_the_trampoline_address() { +fn patch_call_sends_a_bridge_and_resume_through_the_detour_callback() { let (calls, host) = mock(); let mut session = PatchSession::from_host(host).unwrap(); let patch = unsafe { @@ -286,18 +248,8 @@ fn patch_call_forwards_bridge_options_and_returns_the_trampoline_address() { ) } .unwrap(); - assert_eq!(patch.trampoline_address(), Some(0x2000)); - assert_eq!(calls.patch_call_count.load(Relaxed), 1); -} - -#[test] -fn an_overwrite_only_table_can_still_create_a_session() { - let calls = Box::leak(Box::new(Calls::default())); - let host = unsafe { Host::from_table(&table(calls)) }.unwrap(); - let session = PatchSession::from_host(host).unwrap(); - assert!(session.host.patch_call.is_none()); - drop(session); - assert_eq!(calls.discard_count.load(Relaxed), 1); + assert_eq!(patch.trampoline_address(), Some(0x3000)); + assert_eq!(calls.detour_count.load(Relaxed), 1); } #[test]