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..aa2dfc3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,6 +233,16 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "highfleet-patchy-client" +version = "0.1.0" +dependencies = [ + "highfleet-mod-api", + "patchy-code", + "thiserror 2.0.20", + "windows-sys", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -397,7 +407,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..8f0cdbb 100644 --- a/README.md +++ b/README.md @@ -114,10 +114,20 @@ 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 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. +`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. `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 new file mode 100644 index 0000000..d70003f --- /dev/null +++ b/crates/highfleet-patchy-client/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "highfleet-patchy-client" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] +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 new file mode 100644 index 0000000..5b581cc --- /dev/null +++ b/crates/highfleet-patchy-client/src/lib.rs @@ -0,0 +1,398 @@ +//! 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, 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, + 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)] +#[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 did not return a trampoline address for the staged detour")] + MissingTrampoline, + #[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), + #[error(transparent)] + Builder(std::sync::Arc), +} + +impl From for PatchError { + fn from(error: patchy_code::PatchError) -> Self { + Self::Builder(error.into()) + } +} + +#[derive(Clone, Copy)] +struct Host { + context: *mut c_void, + create: HfmPatchSessionCreateV1, + discard: HfmPatchSessionDiscardV1, + overwrite: HfmPatchSessionOverwriteV1, + install: HfmPatchSessionInstallV1, + detour: HfmPatchSessionDetourV1, +} + +// 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"))?, + detour: api + .session_detour + .ok_or(PatchError::MissingCallback("session_detour"))?, + }) + } +} + +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)), + } +} + +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. +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 }) + } + + /// 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 { + 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. + /// + /// # 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, + { + 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); + } + 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 { + (self.host.detour)( + self.host.context, + id, + name.into(), + address, + size, + &request, + &mut output, + ) + })?; + Patch::from_trampoline(output) + } + + /// 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 { + 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. + pub fn trampoline_address(&self) -> Option { + self.trampoline + } +} + +#[cfg(test)] +mod tests; 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()); + } +} diff --git a/crates/highfleet-patchy-client/src/tests.rs b/crates/highfleet-patchy-client/src/tests.rs new file mode 100644 index 0000000..1f39c1c --- /dev/null +++ b/crates/highfleet-patchy-client/src/tests.rs @@ -0,0 +1,274 @@ +use super::*; +use highfleet_mod_api::ffi::HfmStr; +use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; + +#[derive(Default)] +struct Calls { + stage_count: AtomicU32, + detour_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), + session_detour: Some(detour), + } +} + +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) +} + +extern "C" fn callback() {} + +fn mock() -> (&'static Calls, Host) { + let calls = Box::leak(Box::new(Calls::default())); + let host = unsafe { Host::from_table(&table(calls)) }.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 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 + || 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_host_without_a_detour_callback_is_rejected_at_setup() { + let calls = Box::leak(Box::new(Calls::default())); + let api = HfmPatchApiV1 { + session_detour: None, + ..table(calls) + }; + assert!(matches!( + unsafe { Host::from_table(&api) }, + 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] +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 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 { + 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(0x3000)); + assert_eq!(calls.detour_count.load(Relaxed), 1); +} + +#[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/src/loader.rs b/src/loader.rs index 57c3777..993d60f 100644 --- a/src/loader.rs +++ b/src/loader.rs @@ -117,11 +117,26 @@ 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 replay_result = library + .get:: u32>(b"patchy_test_replay_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); + 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/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..939ad51 100644 --- a/tests/fixtures/patchy-mod/src/lib.rs +++ b/tests/fixtures/patchy-mod/src/lib.rs @@ -1,34 +1,89 @@ -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. +#[cfg(all(windows, target_arch = "x86_64"))] +#[unsafe(naked)] #[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; +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(()) +} + +#[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) + })?; } - unsafe { (&raw mut API).write(Some(api.read())) }; - HFM_PATCH_OK + 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 +95,23 @@ 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 { + #[cfg(all(windows, target_arch = "x86_64"))] + if stage_callback(&mut session) + .and_then(|()| stage_conditional_replay(&mut session)) + .is_err() + { 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)]