From 3537ad704d5d4798cfd170c88ac0285579e51311 Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 09:31:18 -0600 Subject: [PATCH 1/4] Add a provisional loader-owned Patchy service --- .github/workflows/ci.yml | 14 + Cargo.lock | 316 ++++++++++++++- Cargo.toml | 3 +- README.md | 17 + crates/highfleet-mod-api/src/lib.rs | 1 + crates/highfleet-mod-api/src/patching.rs | 85 ++++ src/host_patchy.rs | 494 +++++++++++++++++++++++ src/lib.rs | 19 +- src/loader.rs | 40 +- src/session_registry.rs | 114 ++++++ src/versioning.rs | 35 +- tests/fixtures/patchy-mod/Cargo.toml | 13 + tests/fixtures/patchy-mod/src/lib.rs | 79 ++++ 13 files changed, 1205 insertions(+), 25 deletions(-) create mode 100644 crates/highfleet-mod-api/src/patching.rs create mode 100644 src/host_patchy.rs create mode 100644 src/session_registry.rs create mode 100644 tests/fixtures/patchy-mod/Cargo.toml create mode 100644 tests/fixtures/patchy-mod/src/lib.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dbc1520..ba827f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,6 +59,20 @@ jobs: - name: Test workspace run: cargo test --workspace --locked + - name: Test the Patchy capability with a mod DLL + shell: pwsh + run: | + cargo build -p patchy-test-mod --locked + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $env:PATCHY_TEST_MOD = Join-Path $env:GITHUB_WORKSPACE 'target\x86_64-pc-windows-msvc\debug\patchy_test_mod.dll' + cargo test -p highfleet-loader --lib --locked -- --ignored --exact loader::tests::unknown_build_still_initializes_a_patchy_mod_that_declines_the_version | Tee-Object -Variable output + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + # libtest succeeds when a filter selects nothing, so require the run. + if (-not ($output -match '^test result: ok\. 1 passed')) { + Write-Error 'The Patchy DLL test did not run' + exit 1 + } + - name: Check workspace run: cargo check --workspace --locked diff --git a/Cargo.lock b/Cargo.lock index 5536426..ac71a2e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,6 +26,18 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "block-buffer" version = "0.10.4" @@ -41,6 +53,18 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + [[package]] name = "cc" version = "1.4.4" @@ -68,6 +92,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -103,6 +137,18 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "enum-as-inner" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "find-msvc-tools" version = "0.1.11" @@ -119,7 +165,7 @@ dependencies = [ "log", "nu-ansi-term", "regex", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -156,6 +202,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "highfleet-loader" version = "0.1.0" @@ -165,6 +217,7 @@ dependencies = [ "libc", "libloading", "log", + "patchy-rs", "proxygen-macros", "serde", "serde_json", @@ -177,7 +230,7 @@ name = "highfleet-mod-api" version = "0.1.0" dependencies = [ "log", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -243,12 +296,60 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mmap-rs" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86968d85441db75203c34deefd0c88032f275aaa85cee19a1dcfff6ae9df56da" +dependencies = [ + "bitflags 1.3.2", + "combine", + "libc", + "mach2", + "nix", + "sysctl", + "thiserror 1.0.69", + "widestring", + "windows 0.48.0", +] + +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", + "memoffset", + "pin-utils", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -273,12 +374,36 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "patchy-rs" +version = "0.2.0" +source = "git+https://github.com/logdot/patchy-rs.git?rev=bfcf32516e8d002ca3840564bdfd88d0faff0cf0#bfcf32516e8d002ca3840564bdfd88d0faff0cf0" +dependencies = [ + "log", + "mmap-rs", + "thiserror 1.0.69", + "windows 0.62.2", +] + +[[package]] +name = "patchy-test-mod" +version = "0.0.0" +dependencies = [ + "highfleet-mod-api", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pin-utils" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -341,6 +466,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "serde" version = "1.0.229" @@ -429,13 +563,47 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sysctl" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7dddc5f0fee506baf8b9fdb989e242f17e4b11c61dfbb0635b705217199eea" +dependencies = [ + "bitflags 2.13.2", + "byteorder", + "enum-as-inner", + "libc", + "thiserror 1.0.69", + "walkdir", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -467,6 +635,16 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasm-bindgen" version = "0.2.127" @@ -512,6 +690,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi" version = "0.3.9" @@ -528,12 +712,51 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -547,6 +770,17 @@ dependencies = [ "windows-strings", ] +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -575,6 +809,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -602,6 +846,72 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index d0c4ccb..a9d3d4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" # build = "build.rs" [workspace] -members = ["crates/highfleet-mod-api"] +members = ["crates/highfleet-mod-api", "tests/fixtures/patchy-mod"] resolver = "2" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -16,6 +16,7 @@ libc = "0.2.149" libloading = "0.8" log = "0.4.*" highfleet-mod-api = { path = "crates/highfleet-mod-api" } +patchy = { package = "patchy-rs", git = "https://github.com/logdot/patchy-rs.git", rev = "bfcf32516e8d002ca3840564bdfd88d0faff0cf0" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.10.*" diff --git a/README.md b/README.md index 3b334ea..80f1993 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,23 @@ extern "C" __declspec(dllexport) bool __cdecl init() { For more details, see the [C++ logging SDK documentation](sdk/README.md). +#### Shared Patchy service (provisional) + +The Modloader can provide one Patchy engine to participating mods, so patches +installed through the service share an overlap registry. The experimental +`highfleet_mod_setup_patchy_v1` export receives the separate +[`HfmPatchApiV1`](crates/highfleet-mod-api/src/patching.rs) table after logging +setup and before `version` and `init`. Return `0` to accept it; any other value +declines it and is logged as a warning. A mod without this export still loads +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). + #### `init() -> bool` The modloader calls this function last. If you return false, the modloader assumes that you have failed to initialize. diff --git a/crates/highfleet-mod-api/src/lib.rs b/crates/highfleet-mod-api/src/lib.rs index 540a5bd..47bcc56 100644 --- a/crates/highfleet-mod-api/src/lib.rs +++ b/crates/highfleet-mod-api/src/lib.rs @@ -6,6 +6,7 @@ pub mod ffi; mod logging; +pub mod patching; pub use logging::{install_logger, InstallError}; diff --git a/crates/highfleet-mod-api/src/patching.rs b/crates/highfleet-mod-api/src/patching.rs new file mode 100644 index 0000000..16cac27 --- /dev/null +++ b/crates/highfleet-mod-api/src/patching.rs @@ -0,0 +1,85 @@ +//! Provisional C ABI for the loader-owned Patchy service. +//! +//! A mod exports `highfleet_mod_setup_patchy_v1` to receive the table after +//! logging setup and before `version` and `init`. It is offered regardless of +//! the detected game version or the mod's `version` answer. +//! +//! Setup returns [`HFM_PATCH_OK`] to accept the service; any other value +//! declines it and is logged by the loader. The table is borrowed during +//! setup and a mod can copy it when accepting. The loader, its context, and +//! any mod referenced by an installed patch must stay loaded until process +//! exit. + +use crate::ffi::HfmStr; +use core::ffi::c_void; + +pub const HFM_PATCH_ABI_VERSION_1: u32 = 1; +pub const HFM_PATCH_OK: u32 = 0; +pub const HFM_PATCH_INVALID_ARGUMENT: u32 = 1; +pub const HFM_PATCH_OVERLAP: u32 = 2; +pub const HFM_PATCH_SOURCE_CHANGED: u32 = 3; +/// Failure without a guarantee that no writes occurred. Do not blindly retry. +pub const HFM_PATCH_FAILED: u32 = 4; + +/// A loader-issued session ID. Zero is never issued and IDs are never reused, +/// so a stale, unknown, or another mod's ID is rejected with +/// [`HFM_PATCH_INVALID_ARGUMENT`] without affecting any session. +pub type HfmPatchSessionId = u64; + +pub type HfmPatchSetupV1 = unsafe extern "C" fn(*const HfmPatchApiV1) -> u32; +pub type HfmPatchSessionCreateV1 = + unsafe extern "C" fn(context: *mut c_void, output: *mut HfmPatchSessionId) -> u32; +pub type HfmPatchSessionDiscardV1 = + unsafe extern "C" fn(context: *mut c_void, session: HfmPatchSessionId) -> u32; +pub type HfmPatchSessionOverwriteV1 = unsafe extern "C" fn( + context: *mut c_void, + session: HfmPatchSessionId, + name: HfmStr, + address: usize, + bytes: *const u8, + len: usize, +) -> u32; +pub type HfmPatchSessionInstallV1 = + unsafe extern "C" fn(context: *mut c_void, session: HfmPatchSessionId) -> u32; + +/// A process-lifetime capability bound to the receiving mod. +/// +/// `context` must be the value from this table. Sessions belong to the context +/// that created them. Calls may come from any thread; the loader serializes +/// staging and installation through this service. An install consumes its +/// session before writing. +/// Requests borrow strings and replacement bytes only for the duration of the +/// call. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HfmPatchApiV1 { + pub abi_version: u32, + pub struct_size: u32, + pub context: *mut c_void, + /// On success writes a new nonzero session ID to the caller's output. + pub session_create: Option, + /// Consumes a session without writing its pending patches. + pub session_discard: Option, + /// Stages a write under a nonempty UTF-8 name. The source must remain + /// readable through install and the replacement must be valid at the site. + pub session_overwrite: Option, + /// Consumes a session belonging to this context, even if install fails. + /// No other thread may execute a patch source while it is being written. + pub session_install: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use core::mem::{offset_of, size_of}; + + #[test] + fn patch_table_has_a_versioned_c_prefix() { + let pointer_size = size_of::<*const ()>(); + assert_eq!(offset_of!(HfmPatchApiV1, abi_version), 0); + assert_eq!(offset_of!(HfmPatchApiV1, struct_size), 4); + assert_eq!(offset_of!(HfmPatchApiV1, context), 8); + assert_eq!(offset_of!(HfmPatchApiV1, session_create), 8 + pointer_size); + assert_eq!(size_of::(), 8 + pointer_size * 5); + } +} diff --git a/src/host_patchy.rs b/src/host_patchy.rs new file mode 100644 index 0000000..a8c1d83 --- /dev/null +++ b/src/host_patchy.rs @@ -0,0 +1,494 @@ +//! Loader-owned sessions backed by the single Patchy engine in this process. +//! +//! Mods refer to sessions by loader-issued IDs, so a stale or forged ID is a +//! failed lookup rather than a dangling pointer. The engine gate serializes +//! Patchy's source reads during staging with its writes during installation. +//! Installation does not hold the session registry lock. + +use crate::session_registry::SessionRegistry; +use highfleet_mod_api::{ + ffi::HfmStr, + patching::{ + HfmPatchApiV1, HfmPatchSessionId, HfmPatchSetupV1, HFM_PATCH_ABI_VERSION_1, + HFM_PATCH_FAILED, HFM_PATCH_INVALID_ARGUMENT, HFM_PATCH_OK, HFM_PATCH_OVERLAP, + HFM_PATCH_SOURCE_CHANGED, + }, +}; +use libloading::Library; +use log::{debug, error, warn}; +use patchy::{PatchError, PatchSession}; +use std::{ + ffi::c_void, + mem::size_of, + panic::{catch_unwind, AssertUnwindSafe}, + path::{Path, PathBuf}, + slice, str, + sync::{Mutex, MutexGuard, PoisonError}, +}; + +struct ModContext { + path: PathBuf, +} + +struct Session { + owner: &'static ModContext, + inner: PatchSession, +} + +static SESSIONS: Mutex> = Mutex::new(SessionRegistry::new()); +static SOURCE_ACCESS: Mutex<()> = Mutex::new(()); + +fn sessions() -> MutexGuard<'static, SessionRegistry> { + SESSIONS.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn source_access() -> MutexGuard<'static, ()> { + SOURCE_ACCESS.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Sessions are owned by the address of the context they were created with; +/// the address is compared, never dereferenced. +fn owner_key(context: *mut c_void) -> usize { + context as usize +} + +/// Offers the capability to opt-in mods. An absent export is normal. +/// +/// # Safety +/// The mod library must remain loaded for as long as a patch can refer to it. +pub unsafe fn setup_mod_patching(library: &Library, path: &Path) { + let Ok(setup) = (unsafe { library.get::(b"highfleet_mod_setup_patchy_v1") }) + else { + return; + }; + + let status = unsafe { offer_patchy(path, *setup) }; + if status != HFM_PATCH_OK { + warn!( + "Mod {} declined the Patchy service (status {status})", + path.display() + ); + } +} + +/// # Safety +/// The setup callback must accept the v1 table and must not unwind. +pub(crate) unsafe fn offer_patchy(path: &Path, setup: HfmPatchSetupV1) -> u32 { + unsafe { setup(&patch_api(path)) } +} + +/// Creates the table for one mod. Its context lives for the process because +/// the mod may keep the table. +fn patch_api(path: &Path) -> HfmPatchApiV1 { + let context = Box::leak(Box::new(ModContext { path: path.into() })); + HfmPatchApiV1 { + abi_version: HFM_PATCH_ABI_VERSION_1, + struct_size: size_of::() as u32, + context: (context as *mut ModContext).cast(), + session_create: Some(session_create), + session_discard: Some(session_discard), + session_overwrite: Some(session_overwrite), + session_install: Some(session_install), + } +} + +fn run_ffi(operation: impl FnOnce() -> Result<(), u32>) -> u32 { + match catch_unwind(AssertUnwindSafe(operation)) { + Ok(Ok(())) => HFM_PATCH_OK, + Ok(Err(status)) => status, + Err(_) => HFM_PATCH_FAILED, + } +} + +fn patch_status(owner: &ModContext, operation: &str, err: PatchError) -> u32 { + error!("Mod {}: {operation}: {err}", owner.path.display()); + match err { + PatchError::OverlappingPatch { .. } => HFM_PATCH_OVERLAP, + PatchError::SourceChanged { .. } => HFM_PATCH_SOURCE_CHANGED, + _ => HFM_PATCH_FAILED, + } +} + +/// Removes a session so it is consumed whatever happens next. Another +/// context's ID is not found and therefore not consumed. +fn take_session(context: *mut c_void, id: HfmPatchSessionId) -> Result { + sessions() + .take(owner_key(context), id) + .ok_or(HFM_PATCH_INVALID_ARGUMENT) +} + +unsafe extern "C" fn session_create(context: *mut c_void, output: *mut HfmPatchSessionId) -> u32 { + run_ffi(|| { + if output.is_null() { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + // The table contract requires `context` to be the one it supplied. + let owner = + unsafe { context.cast::().as_ref() }.ok_or(HFM_PATCH_INVALID_ARGUMENT)?; + let session = Session { + owner, + inner: PatchSession::new(), + }; + let Some(id) = sessions().insert(owner_key(context), session) else { + error!( + "Mod {}: Patchy session IDs are exhausted", + owner.path.display() + ); + return Err(HFM_PATCH_FAILED); + }; + unsafe { output.write(id) }; + Ok(()) + }) +} + +unsafe extern "C" fn session_discard(context: *mut c_void, session: HfmPatchSessionId) -> u32 { + run_ffi(|| take_session(context, session).map(drop)) +} + +unsafe fn request_bytes<'a>(bytes: *const u8, len: usize) -> Result<&'a [u8], u32> { + if bytes.is_null() || len == 0 || len > isize::MAX as usize { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + Ok(unsafe { slice::from_raw_parts(bytes, len) }) +} + +unsafe extern "C" fn session_overwrite( + context: *mut c_void, + session: HfmPatchSessionId, + name: HfmStr, + address: usize, + bytes: *const u8, + len: usize, +) -> u32 { + run_ffi(|| { + let name = str::from_utf8(unsafe { request_bytes(name.ptr, name.len)? }) + .map_err(|_| HFM_PATCH_INVALID_ARGUMENT)?; + let replacement = unsafe { request_bytes(bytes, len)? }; + if address == 0 || address.checked_add(len).is_none() { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + + let (owner, staged) = { + // Both staging and installation touch live process memory. Lock + // source access before the registry if both are needed. + let _source = source_access(); + let mut sessions = sessions(); + let session = sessions + .get_mut(owner_key(context), session) + .ok_or(HFM_PATCH_INVALID_ARGUMENT)?; + (session.owner, unsafe { + session.inner.overwrite(address, replacement) + }) + }; + staged.map_err(|err| patch_status(owner, name, err))?; + debug!( + "Mod {} prepared {name} at {address:#x}", + owner.path.display() + ); + Ok(()) + }) +} + +unsafe extern "C" fn session_install(context: *mut c_void, session: HfmPatchSessionId) -> u32 { + run_ffi(|| { + let Session { owner, inner } = take_session(context, session)?; + let installed = { + let _source = source_access(); + unsafe { inner.install_permanently() } + }; + installed.map_err(|err| patch_status(owner, "install", err)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ptr; + + const ORIGINAL: u8 = 7; + const REPLACEMENT: u8 = 42; + + /// The table one mod would receive during setup. + struct ModService(HfmPatchApiV1); + + impl ModService { + fn new() -> Self { + Self(patch_api(Path::new("test-mod.dll"))) + } + + fn create(&self) -> HfmPatchSessionId { + let mut session = 0; + // SAFETY: The table came from this service and the output is live. + let status = unsafe { self.0.session_create.unwrap()(self.0.context, &mut session) }; + assert_eq!(status, HFM_PATCH_OK); + session + } + + fn overwrite( + &self, + session: HfmPatchSessionId, + name: HfmStr, + address: usize, + bytes: *const u8, + len: usize, + ) -> u32 { + // SAFETY: Every test address is either rejected before use or is + // readable and writable memory leaked for the process lifetime. + unsafe { + self.0.session_overwrite.unwrap()( + self.0.context, + session, + name, + address, + bytes, + len, + ) + } + } + + fn overwrite_byte(&self, session: HfmPatchSessionId, target: *mut u8) -> u32 { + self.overwrite( + session, + HfmStr::from("test overwrite"), + target as usize, + &REPLACEMENT, + 1, + ) + } + + fn discard(&self, session: HfmPatchSessionId) -> u32 { + // SAFETY: The table came from this service. + unsafe { self.0.session_discard.unwrap()(self.0.context, session) } + } + + fn install(&self, session: HfmPatchSessionId) -> u32 { + // SAFETY: Test targets are data that no thread executes. + unsafe { self.0.session_install.unwrap()(self.0.context, session) } + } + } + + /// Fresh bytes per test, because installed patches are permanent and + /// process-wide. + fn writable_bytes() -> *mut u8 { + Box::leak(Box::new([ORIGINAL; 4])).as_mut_ptr() + } + + fn read(target: *const u8) -> u8 { + // SAFETY: `writable_bytes` memory is leaked and never freed. + unsafe { target.read_volatile() } + } + + unsafe extern "C" fn accept_patch_service(api: *const HfmPatchApiV1) -> u32 { + // SAFETY: The loader supplies the table for the duration of setup. + let api = unsafe { &*api }; + if api.abi_version != HFM_PATCH_ABI_VERSION_1 { + return u32::MAX; + } + let (Some(create), Some(discard)) = (api.session_create, api.session_discard) else { + return u32::MAX; + }; + let mut session = 0; + let status = unsafe { create(api.context, &mut session) }; + if status != HFM_PATCH_OK { + return status; + } + unsafe { discard(api.context, session) } + } + + #[test] + fn patch_setup_offers_a_usable_session() { + assert_eq!( + // SAFETY: The in-process test export accepts this table. + unsafe { offer_patchy(Path::new("test-mod.dll"), accept_patch_service) }, + HFM_PATCH_OK, + ); + } + + #[test] + fn installing_an_overwrite_writes_the_replacement() { + let service = ModService::new(); + let target = writable_bytes(); + let session = service.create(); + + assert_eq!(service.overwrite_byte(session, target), HFM_PATCH_OK); + assert_eq!(service.install(session), HFM_PATCH_OK); + assert_eq!(read(target), REPLACEMENT); + } + + #[test] + fn issued_session_ids_are_nonzero() { + let service = ModService::new(); + + assert_ne!(service.create(), 0); + } + + #[test] + fn create_rejects_a_null_output() { + let service = ModService::new(); + + // SAFETY: The table came from this service. + let status = + unsafe { service.0.session_create.unwrap()(service.0.context, ptr::null_mut()) }; + + assert_eq!(status, HFM_PATCH_INVALID_ARGUMENT); + } + + #[test] + fn overwrite_rejects_invalid_names() { + let service = ModService::new(); + let target = writable_bytes(); + let session = service.create(); + let invalid_utf8 = [0xff_u8]; + + for name in [ + HfmStr::empty(), + HfmStr { + ptr: ptr::null(), + len: 1, + }, + HfmStr { + ptr: invalid_utf8.as_ptr(), + len: invalid_utf8.len(), + }, + ] { + assert_eq!( + service.overwrite(session, name, target as usize, &REPLACEMENT, 1), + HFM_PATCH_INVALID_ARGUMENT, + ); + } + } + + #[test] + fn overwrite_rejects_invalid_replacement_ranges() { + let service = ModService::new(); + let target = writable_bytes() as usize; + let session = service.create(); + + for (address, bytes, len) in [ + (target, ptr::null(), 1), + (target, &REPLACEMENT as *const u8, 0), + (0, &REPLACEMENT as *const u8, 1), + (usize::MAX, &REPLACEMENT as *const u8, 1), + ] { + assert_eq!( + service.overwrite(session, HfmStr::from("invalid"), address, bytes, len), + HFM_PATCH_INVALID_ARGUMENT, + ); + } + } + + #[test] + fn a_rejected_request_leaves_the_session_usable() { + let service = ModService::new(); + let target = writable_bytes(); + let session = service.create(); + service.overwrite(session, HfmStr::empty(), target as usize, &REPLACEMENT, 1); + + assert_eq!(service.overwrite_byte(session, target), HFM_PATCH_OK); + assert_eq!(service.install(session), HFM_PATCH_OK); + assert_eq!(read(target), REPLACEMENT); + } + + #[test] + fn overlapping_writes_in_one_session_are_rejected() { + let service = ModService::new(); + let target = writable_bytes(); + let session = service.create(); + let replacement = [REPLACEMENT; 2]; + let overwrite_two_bytes_at = |offset: usize| { + service.overwrite( + session, + HfmStr::from("two bytes"), + target as usize + offset, + replacement.as_ptr(), + replacement.len(), + ) + }; + + assert_eq!(overwrite_two_bytes_at(0), HFM_PATCH_OK); + assert_eq!(overwrite_two_bytes_at(1), HFM_PATCH_OVERLAP); + } + + #[test] + fn another_mod_cannot_use_a_session() { + let owner = ModService::new(); + let other = ModService::new(); + let target = writable_bytes(); + let session = owner.create(); + + assert_eq!( + other.overwrite_byte(session, target), + HFM_PATCH_INVALID_ARGUMENT + ); + assert_eq!(other.discard(session), HFM_PATCH_INVALID_ARGUMENT); + assert_eq!(other.install(session), HFM_PATCH_INVALID_ARGUMENT); + assert_eq!(read(target), ORIGINAL); + } + + #[test] + fn another_mods_rejected_calls_do_not_consume_the_session() { + let owner = ModService::new(); + let other = ModService::new(); + let target = writable_bytes(); + let session = owner.create(); + other.discard(session); + other.install(session); + + assert_eq!(owner.overwrite_byte(session, target), HFM_PATCH_OK); + assert_eq!(owner.install(session), HFM_PATCH_OK); + assert_eq!(read(target), REPLACEMENT); + } + + fn assert_unknown(service: &ModService, session: HfmPatchSessionId) { + let target = writable_bytes(); + assert_eq!( + service.overwrite_byte(session, target), + HFM_PATCH_INVALID_ARGUMENT + ); + assert_eq!(service.install(session), HFM_PATCH_INVALID_ARGUMENT); + assert_eq!(service.discard(session), HFM_PATCH_INVALID_ARGUMENT); + assert_eq!(read(target), ORIGINAL); + } + + #[test] + fn never_issued_session_ids_are_rejected() { + let service = ModService::new(); + + for session in [0, HfmPatchSessionId::MAX] { + assert_unknown(&service, session); + } + } + + #[test] + fn discard_consumes_the_session() { + let service = ModService::new(); + let session = service.create(); + + assert_eq!(service.discard(session), HFM_PATCH_OK); + assert_unknown(&service, session); + } + + #[test] + fn install_consumes_the_session() { + let service = ModService::new(); + let session = service.create(); + service.overwrite_byte(session, writable_bytes()); + + assert_eq!(service.install(session), HFM_PATCH_OK); + assert_unknown(&service, session); + } + + #[test] + fn a_failed_install_consumes_the_session() { + let service = ModService::new(); + let target = writable_bytes(); + let installed = service.create(); + service.overwrite_byte(installed, target); + service.install(installed); + let conflicting = service.create(); + service.overwrite_byte(conflicting, target); + + assert_eq!(service.install(conflicting), HFM_PATCH_OVERLAP); + assert_unknown(&service, conflicting); + } +} diff --git a/src/lib.rs b/src/lib.rs index 36c8f79..f93fc39 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,22 +2,24 @@ mod export_indices; mod host_logging; +mod host_patchy; mod intercepted_exports; mod orig_exports; mod proxied_exports; mod loader; +mod session_registry; mod versioning; use flexi_logger::{Duplicate, FileSpec, Logger, WriteMode}; #[allow(unused_imports)] pub use intercepted_exports::*; use loader::{create_folders, load_mods}; -use log::{debug, error, info, warn}; +use log::{debug, error, info}; pub use proxied_exports::*; use export_indices::TOTAL_EXPORTS; use orig_exports::load_dll_funcs; -use versioning::get_version; +use versioning::startup_version; #[cfg(target_arch="x86_64")] use std::arch::x86_64::_mm_pause; #[cfg(target_arch="x86")] @@ -168,18 +170,7 @@ unsafe extern "system" fn init(_: *mut c_void) -> u32 { create_folders(); host_logging::load_config(); - let version = match get_version() { - Ok(string) => { - info!("Highfleet version: {string}"); - string - } - Err(e) => { - warn!("Error fetching version: {e}"); - "Unknown".to_string() - } - }; - - load_mods(&version); + load_mods(&startup_version()); 0 } diff --git a/src/loader.rs b/src/loader.rs index daa0ed7..57c3777 100644 --- a/src/loader.rs +++ b/src/loader.rs @@ -3,7 +3,7 @@ use std::{ffi::CString, fs, os::raw::c_char, path::PathBuf}; use libloading::Library; use log::{debug, error, info, warn}; -use crate::host_logging; +use crate::{host_logging, host_patchy}; const MOD_FOLDER: &str = "./Modloader/mods"; const CONFIG_FOLDER: &str = "./Modloader/config"; @@ -67,15 +67,18 @@ fn load_mod(path: &PathBuf, version: &str) { }; host_logging::setup_mod_logging(&library, path); + host_patchy::setup_mod_patching(&library, path); match library.get:: bool>(b"version") { Ok(version_func) => { let cstr = CString::new(version).unwrap(); if !version_func(cstr.as_ptr()) { - error!("Mod doesn't support game version: {}", path.display()); - error!("This may cause crashes or other issues"); + warn!( + "Mod doesn't support game version {version}: {}. This may cause crashes or other issues", + path.display() + ); } - }, + } Err(e) => { warn!("No version function: {}", e); } @@ -86,7 +89,7 @@ fn load_mod(path: &PathBuf, version: &str) { if !init() { error!("Failed to initialize mod: {}", path.display()); } - }, + } Err(e) => { warn!("No init function: {}", e); } @@ -95,3 +98,30 @@ fn load_mod(path: &PathBuf, version: &str) { std::mem::forget(library); } } + +#[cfg(test)] +mod tests { + use crate::versioning::{startup_version, UNKNOWN_VERSION}; + + #[test] + #[ignore = "requires a built patchy-test-mod DLL; run with PATCHY_TEST_MOD set"] + fn unknown_build_still_initializes_a_patchy_mod_that_declines_the_version() { + let path = std::path::PathBuf::from( + std::env::var_os("PATCHY_TEST_MOD").expect("PATCHY_TEST_MOD must name the fixture DLL"), + ) + .canonicalize() + .unwrap(); + // SAFETY: This test controls the fixture DLL and its export signature. + unsafe { + let library = libloading::Library::new(&path).unwrap(); + let target = library + .get:: u8>(b"patchy_test_target") + .unwrap(); + let version = startup_version(); + assert_eq!(version, UNKNOWN_VERSION, "the test runner is not a known game build"); + assert_eq!(target(), 7); + super::load_mod(&path, &version); + assert_eq!(target(), 42); + } + } +} diff --git a/src/session_registry.rs b/src/session_registry.rs new file mode 100644 index 0000000..d6cf9b4 --- /dev/null +++ b/src/session_registry.rs @@ -0,0 +1,114 @@ +//! Loader-issued session IDs. Kept free of loader dependencies so it can be +//! tested on any host. + +use std::collections::BTreeMap; + +pub(crate) type SessionId = u64; + +pub(crate) struct SessionRegistry { + last_issued: SessionId, + sessions: BTreeMap>, +} + +struct Entry { + owner: usize, + session: S, +} + +impl SessionRegistry { + pub(crate) const fn new() -> Self { + Self { + last_issued: 0, + sessions: BTreeMap::new(), + } + } + + pub(crate) fn insert(&mut self, owner: usize, session: S) -> Option { + let id = self.last_issued.checked_add(1)?; + self.last_issued = id; + self.sessions.insert(id, Entry { owner, session }); + Some(id) + } + + pub(crate) fn get_mut(&mut self, owner: usize, id: SessionId) -> Option<&mut S> { + self.sessions + .get_mut(&id) + .filter(|entry| entry.owner == owner) + .map(|entry| &mut entry.session) + } + + pub(crate) fn take(&mut self, owner: usize, id: SessionId) -> Option { + self.get_mut(owner, id)?; + self.sessions.remove(&id).map(|entry| entry.session) + } + + #[cfg(test)] + fn with_last_issued(last_issued: SessionId) -> Self { + Self { + last_issued, + sessions: BTreeMap::new(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const OWNER: usize = 1; + const OTHER_OWNER: usize = 2; + + #[test] + fn issued_ids_are_nonzero_and_distinct() { + let mut registry = SessionRegistry::new(); + let ids: Vec<_> = (0..3) + .map(|_| registry.insert(OWNER, ()).unwrap()) + .collect(); + + assert!(ids.iter().all(|&id| id != 0)); + assert!(ids[0] != ids[1] && ids[1] != ids[2] && ids[0] != ids[2]); + } + + #[test] + fn exhausted_ids_are_refused_instead_of_wrapping() { + let mut registry = SessionRegistry::with_last_issued(SessionId::MAX - 1); + + assert_eq!(registry.insert(OWNER, ()), Some(SessionId::MAX)); + assert_eq!(registry.insert(OWNER, ()), None); + assert_eq!(registry.insert(OWNER, ()), None); + } + + #[test] + fn another_owner_cannot_reach_or_consume_a_session() { + let mut registry = SessionRegistry::new(); + let id = registry.insert(OWNER, "session").unwrap(); + + assert!(registry.get_mut(OTHER_OWNER, id).is_none()); + assert!(registry.take(OTHER_OWNER, id).is_none()); + assert_eq!(registry.take(OWNER, id), Some("session")); + } + + #[test] + fn never_issued_ids_are_unknown() { + let mut registry = SessionRegistry::new(); + let issued = registry.insert(OWNER, ()).unwrap(); + + for id in [0, issued + 1, SessionId::MAX] { + assert!(registry.get_mut(OWNER, id).is_none()); + assert!(registry.take(OWNER, id).is_none()); + } + } + + #[test] + fn consumed_ids_stay_unknown_after_later_sessions_are_issued() { + let mut registry = SessionRegistry::new(); + let consumed = registry.insert(OWNER, ()).unwrap(); + registry.take(OWNER, consumed).unwrap(); + + let later = registry.insert(OWNER, ()).unwrap(); + + assert_ne!(later, consumed); + assert!(registry.get_mut(OWNER, consumed).is_none()); + assert!(registry.take(OWNER, consumed).is_none()); + } +} diff --git a/src/versioning.rs b/src/versioning.rs index 0d02f5f..2f719ff 100644 --- a/src/versioning.rs +++ b/src/versioning.rs @@ -1,6 +1,10 @@ use std::{error::Error, fs::File, io}; +use log::{info, warn}; use sha2::{Sha256, Digest}; +/// The version passed to mods when the running executable is not recognised. +pub const UNKNOWN_VERSION: &str = "Unknown"; + struct Version { name: &'static str, sha256: &'static str, @@ -23,7 +27,7 @@ const VERSIONS: [Version; 3] = [ fn get_sha256() -> Result> { let mut hasher = Sha256::new(); - let mut file = File::open("./Highfleet.exe")?; + let mut file = File::open(std::env::current_exe()?)?; io::copy(&mut file, &mut hasher)?; let hash_bytes = hasher.finalize(); @@ -41,9 +45,36 @@ fn check_version(sha256: String, versions: &[Version]) -> Result Result> { +fn get_version() -> Result> { let sha256 = get_sha256()?; let version = check_version(sha256, &VERSIONS)?; Ok(version) } + +/// Identifies the running executable for mods' `version` exports. +pub fn startup_version() -> String { + match get_version() { + Ok(version) => { + info!("Highfleet version: {version}"); + version + } + Err(e) => { + warn!("Error fetching version: {e}"); + UNKNOWN_VERSION.to_string() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hashes_the_running_executable_even_when_its_build_is_unknown() { + let executable = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let expected = format!("{:x}", Sha256::digest(executable)); + + assert_eq!(get_sha256().unwrap(), expected); + } +} diff --git a/tests/fixtures/patchy-mod/Cargo.toml b/tests/fixtures/patchy-mod/Cargo.toml new file mode 100644 index 0000000..8379158 --- /dev/null +++ b/tests/fixtures/patchy-mod/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "patchy-test-mod" +version = "0.0.0" +edition = "2021" +publish = false + +[lib] +crate-type = ["cdylib"] +test = false +doctest = false + +[dependencies] +highfleet-mod-api = { path = "../../../crates/highfleet-mod-api" } diff --git a/tests/fixtures/patchy-mod/src/lib.rs b/tests/fixtures/patchy-mod/src/lib.rs new file mode 100644 index 0000000..df503c0 --- /dev/null +++ b/tests/fixtures/patchy-mod/src/lib.rs @@ -0,0 +1,79 @@ +use highfleet_mod_api::{ + ffi::HfmStr, + patching::{HfmPatchApiV1, HFM_PATCH_ABI_VERSION_1, HFM_PATCH_FAILED, HFM_PATCH_OK}, +}; +use std::{ + ffi::{c_char, CStr}, + mem::size_of, + sync::atomic::{AtomicBool, Ordering}, +}; + +static mut API: Option = None; +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(); + 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 +} + +/// Patches only when the loader offered the service, then reported `Unknown`. +#[unsafe(no_mangle)] +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 { + 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; + } + unsafe { install(api.context, session) == HFM_PATCH_OK } +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn patchy_test_target() -> u8 { + unsafe { (&raw const TARGET).read_volatile() } +} From ca8bb46ac7729d655feda34924753f61dfb161c8 Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 09:55:29 -0600 Subject: [PATCH 2/4] Expose hosted Patchy callback detours --- crates/highfleet-mod-api/src/patching.rs | 90 +++++++++++- src/host_patchy.rs | 178 +++++++++++++++++++---- 2 files changed, 233 insertions(+), 35 deletions(-) diff --git a/crates/highfleet-mod-api/src/patching.rs b/crates/highfleet-mod-api/src/patching.rs index 16cac27..ffc90bb 100644 --- a/crates/highfleet-mod-api/src/patching.rs +++ b/crates/highfleet-mod-api/src/patching.rs @@ -42,21 +42,89 @@ pub type HfmPatchSessionOverwriteV1 = unsafe extern "C" fn( pub type HfmPatchSessionInstallV1 = unsafe extern "C" fn(context: *mut c_void, session: HfmPatchSessionId) -> u32; +pub const HFM_PATCH_STACK_ALIGNED_16: u32 = 0; +pub const HFM_PATCH_STACK_OFFSET_8: u32 = 1; +pub const HFM_PATCH_FLAGS_PRESERVE: u32 = 0; +pub const HFM_PATCH_FLAGS_KEEP_PRODUCED: u32 = 1; +pub const HFM_PATCH_RETURN_NEITHER: u32 = 0; +pub const HFM_PATCH_RETURN_RAX: u32 = 1; +pub const HFM_PATCH_RETURN_XMM0: u32 = 2; + +/// An immutable byte range borrowed during a host call. Null is allowed only +/// for an empty range. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HfmPatchBytes { + pub ptr: *const u8, + pub len: usize, +} + +impl HfmPatchBytes { + pub const EMPTY: Self = Self { + ptr: core::ptr::null(), + len: 0, + }; +} + +impl From<&[u8]> for HfmPatchBytes { + fn from(bytes: &[u8]) -> Self { + Self { + ptr: bytes.as_ptr(), + len: bytes.len(), + } + } +} + +/// A Windows x64 callback bridge. The callback must not take stack-passed +/// arguments or unwind out of the bridge, and must remain live through +/// process exit if installed. The direction flag must be clear on entry. +/// +/// `stack_alignment` describes RSP at the patch site. The snippets are +/// verbatim, position-independent, straight-line instructions that must fall +/// through with RSP unchanged without modifying the bridge's saved state. +/// `after_call` runs before register restoration. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HfmCallBridgeV1 { + pub callback: usize, + pub stack_alignment: u32, + pub flags: u32, + pub keep_return: u32, + pub before_call: HfmPatchBytes, + pub after_call: HfmPatchBytes, +} + +/// Stages a callback and a jump to `address + size`, without replaying the +/// replaced instructions. The source span must remain readable through +/// install and contain complete instructions with no incoming branches into +/// its interior. On success, writes the trampoline address to the supplied +/// live, aligned, writable output pointer. Do not use the trampoline address +/// unless and until session installation succeeds. +pub type HfmPatchSessionPatchCallV1 = unsafe extern "C" fn( + context: *mut c_void, + session: HfmPatchSessionId, + name: HfmStr, + address: usize, + size: usize, + bridge: *const HfmCallBridgeV1, + output_trampoline: *mut usize, +) -> u32; + /// A process-lifetime capability bound to the receiving mod. /// /// `context` must be the value from this table. Sessions belong to the context /// that created them. Calls may come from any thread; the loader serializes /// staging and installation through this service. An install consumes its /// session before writing. -/// Requests borrow strings and replacement bytes only for the duration of the -/// call. +/// Requests borrow strings, descriptors, and bytes only for the duration of +/// the call. Keep that memory readable and unchanged until the call returns. #[repr(C)] #[derive(Clone, Copy)] pub struct HfmPatchApiV1 { pub abi_version: u32, pub struct_size: u32, pub context: *mut c_void, - /// On success writes a new nonzero session ID to the caller's output. + /// On success writes a new nonzero session ID to a live, aligned, writable output. pub session_create: Option, /// Consumes a session without writing its pending patches. pub session_discard: Option, @@ -68,6 +136,17 @@ pub struct HfmPatchApiV1 { pub session_install: Option, } +/// The optional callback extension to the v1 overwrite service. +/// +/// Read the extension only if the prefix's `struct_size` is large enough. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HfmPatchApiWithCallV1 { + pub base: HfmPatchApiV1, + /// Stages a call bridge, then resumes after the replaced span. + pub session_patch_call: Option, +} + #[cfg(test)] mod tests { use super::*; @@ -81,5 +160,10 @@ mod tests { assert_eq!(offset_of!(HfmPatchApiV1, context), 8); assert_eq!(offset_of!(HfmPatchApiV1, session_create), 8 + pointer_size); assert_eq!(size_of::(), 8 + pointer_size * 5); + assert_eq!(offset_of!(HfmPatchApiWithCallV1, base), 0); + assert_eq!( + offset_of!(HfmPatchApiWithCallV1, session_patch_call), + size_of::() + ); } } diff --git a/src/host_patchy.rs b/src/host_patchy.rs index a8c1d83..e4068ff 100644 --- a/src/host_patchy.rs +++ b/src/host_patchy.rs @@ -9,14 +9,16 @@ use crate::session_registry::SessionRegistry; use highfleet_mod_api::{ ffi::HfmStr, patching::{ - HfmPatchApiV1, HfmPatchSessionId, HfmPatchSetupV1, 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, HfmPatchBytes, HfmPatchSessionId, + HfmPatchSetupV1, 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 libloading::Library; use log::{debug, error, warn}; -use patchy::{PatchError, PatchSession}; +use patchy::{CallBridge, FlagPolicy, KeepReturn, Patch, PatchError, PatchSession, StackAlignment}; use std::{ ffi::c_void, mem::size_of, @@ -74,21 +76,25 @@ pub unsafe fn setup_mod_patching(library: &Library, path: &Path) { /// # Safety /// The setup callback must accept the v1 table and must not unwind. pub(crate) unsafe fn offer_patchy(path: &Path, setup: HfmPatchSetupV1) -> u32 { - unsafe { setup(&patch_api(path)) } + let api = patch_api(path); + unsafe { setup(std::ptr::from_ref(&api).cast()) } } /// Creates the table for one mod. Its context lives for the process because /// the mod may keep the table. -fn patch_api(path: &Path) -> HfmPatchApiV1 { +fn patch_api(path: &Path) -> HfmPatchApiWithCallV1 { let context = Box::leak(Box::new(ModContext { path: path.into() })); - HfmPatchApiV1 { - abi_version: HFM_PATCH_ABI_VERSION_1, - struct_size: size_of::() as u32, - context: (context as *mut ModContext).cast(), - session_create: Some(session_create), - session_discard: Some(session_discard), - session_overwrite: Some(session_overwrite), - session_install: Some(session_install), + HfmPatchApiWithCallV1 { + base: HfmPatchApiV1 { + abi_version: HFM_PATCH_ABI_VERSION_1, + struct_size: size_of::() as u32, + context: (context as *mut ModContext).cast(), + session_create: Some(session_create), + session_discard: Some(session_discard), + session_overwrite: Some(session_overwrite), + session_install: Some(session_install), + }, + session_patch_call: Some(session_patch_call), } } @@ -105,6 +111,9 @@ fn patch_status(owner: &ModContext, operation: &str, err: PatchError) -> u32 { match err { PatchError::OverlappingPatch { .. } => HFM_PATCH_OVERLAP, PatchError::SourceChanged { .. } => HFM_PATCH_SOURCE_CHANGED, + PatchError::PatchTooSmall { .. } | PatchError::EmptyPatch | PatchError::AddressOverflow => { + HFM_PATCH_INVALID_ARGUMENT + } _ => HFM_PATCH_FAILED, } } @@ -152,6 +161,30 @@ unsafe fn request_bytes<'a>(bytes: *const u8, len: usize) -> Result<&'a [u8], u3 Ok(unsafe { slice::from_raw_parts(bytes, len) }) } +fn stage_patch( + context: *mut c_void, + session: HfmPatchSessionId, + name: &str, + address: usize, + stage: impl FnOnce(&mut PatchSession) -> patchy::Result, +) -> Result { + let (owner, staged) = { + // Lock source access before the registry if both are needed. + let _source = source_access(); + let mut sessions = sessions(); + let session = sessions + .get_mut(owner_key(context), session) + .ok_or(HFM_PATCH_INVALID_ARGUMENT)?; + (session.owner, stage(&mut session.inner)) + }; + let patch = staged.map_err(|err| patch_status(owner, name, err))?; + debug!( + "Mod {} prepared {name} at {address:#x}", + owner.path.display() + ); + Ok(patch) +} + unsafe extern "C" fn session_overwrite( context: *mut c_void, session: HfmPatchSessionId, @@ -168,23 +201,71 @@ unsafe extern "C" fn session_overwrite( return Err(HFM_PATCH_INVALID_ARGUMENT); } - let (owner, staged) = { - // Both staging and installation touch live process memory. Lock - // source access before the registry if both are needed. - let _source = source_access(); - let mut sessions = sessions(); - let session = sessions - .get_mut(owner_key(context), session) - .ok_or(HFM_PATCH_INVALID_ARGUMENT)?; - (session.owner, unsafe { - session.inner.overwrite(address, replacement) - }) - }; - staged.map_err(|err| patch_status(owner, name, err))?; - debug!( - "Mod {} prepared {name} at {address:#x}", - owner.path.display() - ); + stage_patch(context, session, name, address, |inner| unsafe { + inner.overwrite(address, replacement) + })?; + Ok(()) + }) +} + +// The descriptor's nonempty byte ranges must be readable and immutable for +// the lifetime of the borrow. No bytes are retained by Patchy after staging. +unsafe fn decode_bridge(raw: &HfmCallBridgeV1) -> Result, u32> { + unsafe fn snippet<'a>(bytes: &'a HfmPatchBytes) -> Result<&'a [u8], u32> { + if bytes.len == 0 { + Ok(&[]) + } else { + unsafe { request_bytes(bytes.ptr, bytes.len) } + } + } + if raw.callback == 0 { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + Ok(CallBridge { + callback: raw.callback as *const (), + incoming_stack: match raw.stack_alignment { + HFM_PATCH_STACK_ALIGNED_16 => StackAlignment::Aligned16, + HFM_PATCH_STACK_OFFSET_8 => StackAlignment::Offset8, + _ => return Err(HFM_PATCH_INVALID_ARGUMENT), + }, + flags: match raw.flags { + HFM_PATCH_FLAGS_PRESERVE => FlagPolicy::Preserve, + HFM_PATCH_FLAGS_KEEP_PRODUCED => FlagPolicy::KeepProduced, + _ => return Err(HFM_PATCH_INVALID_ARGUMENT), + }, + keep_return: match raw.keep_return { + HFM_PATCH_RETURN_NEITHER => KeepReturn::Neither, + HFM_PATCH_RETURN_RAX => KeepReturn::Rax, + HFM_PATCH_RETURN_XMM0 => KeepReturn::Xmm0, + _ => return Err(HFM_PATCH_INVALID_ARGUMENT), + }, + before_call: unsafe { snippet(&raw.before_call)? }, + after_call: unsafe { snippet(&raw.after_call)? }, + }) +} + +unsafe extern "C" fn session_patch_call( + context: *mut c_void, + session: HfmPatchSessionId, + name: HfmStr, + address: usize, + size: usize, + bridge: *const HfmCallBridgeV1, + output: *mut usize, +) -> u32 { + run_ffi(|| { + if output.is_null() || address == 0 || address.checked_add(size).is_none() { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + let name = str::from_utf8(unsafe { request_bytes(name.ptr, name.len)? }) + .map_err(|_| HFM_PATCH_INVALID_ARGUMENT)?; + let raw = unsafe { bridge.as_ref() }.ok_or(HFM_PATCH_INVALID_ARGUMENT)?; + let bridge = unsafe { decode_bridge(raw)? }; + let patch = stage_patch(context, session, name, address, |inner| unsafe { + inner.patch_call(address, size, bridge) + })?; + let trampoline = patch.trampoline_address().ok_or(HFM_PATCH_FAILED)?; + unsafe { output.write(trampoline) }; Ok(()) }) } @@ -208,12 +289,45 @@ mod tests { const ORIGINAL: u8 = 7; const REPLACEMENT: u8 = 42; + #[test] + fn patch_call_rejects_an_unknown_stack_alignment() { + extern "C" fn callback() {} + let api = patch_api(Path::new("test-mod.dll")); + let service = ModService(api.base); + let session = service.create(); + let bridge = HfmCallBridgeV1 { + callback: callback as *const () as usize, + stack_alignment: u32::MAX, + flags: HFM_PATCH_FLAGS_PRESERVE, + keep_return: HFM_PATCH_RETURN_NEITHER, + before_call: HfmPatchBytes::EMPTY, + after_call: HfmPatchBytes::EMPTY, + }; + let mut trampoline = 0; + // A readable source keeps the rejection test independent of how + // early the host validates the descriptor. + let source = [0x90u8; 5]; + let status = unsafe { + api.session_patch_call.unwrap()( + service.0.context, + session, + "test callback".into(), + source.as_ptr() as usize, + source.len(), + &bridge, + &mut trampoline, + ) + }; + assert_eq!(status, HFM_PATCH_INVALID_ARGUMENT); + assert_eq!(service.discard(session), HFM_PATCH_OK); + } + /// The table one mod would receive during setup. struct ModService(HfmPatchApiV1); impl ModService { fn new() -> Self { - Self(patch_api(Path::new("test-mod.dll"))) + Self(patch_api(Path::new("test-mod.dll")).base) } fn create(&self) -> HfmPatchSessionId { From 384f6af1cdda6d3f993841fc5f2e5bab4210ec60 Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 10:37:24 -0600 Subject: [PATCH 3/4] Accept custom trampoline plans through the host ABI --- Cargo.lock | 12 +- Cargo.toml | 2 +- crates/highfleet-mod-api/src/patching.rs | 72 +++++++++ src/host_patchy.rs | 195 ++++++++++++++++++++--- 4 files changed, 257 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ac71a2e..21a0823 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -374,14 +374,22 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "patchy-code" +version = "0.2.0" +source = "git+https://github.com/logdot/patchy-rs.git?rev=64d2eac7b33f81c4a60f18ae834d9daba96b92cf#64d2eac7b33f81c4a60f18ae834d9daba96b92cf" +dependencies = [ + "thiserror 1.0.69", +] + [[package]] name = "patchy-rs" version = "0.2.0" -source = "git+https://github.com/logdot/patchy-rs.git?rev=bfcf32516e8d002ca3840564bdfd88d0faff0cf0#bfcf32516e8d002ca3840564bdfd88d0faff0cf0" +source = "git+https://github.com/logdot/patchy-rs.git?rev=64d2eac7b33f81c4a60f18ae834d9daba96b92cf#64d2eac7b33f81c4a60f18ae834d9daba96b92cf" dependencies = [ "log", "mmap-rs", - "thiserror 1.0.69", + "patchy-code", "windows 0.62.2", ] diff --git a/Cargo.toml b/Cargo.toml index a9d3d4f..a1cf7b6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ libc = "0.2.149" libloading = "0.8" log = "0.4.*" highfleet-mod-api = { path = "crates/highfleet-mod-api" } -patchy = { package = "patchy-rs", git = "https://github.com/logdot/patchy-rs.git", rev = "bfcf32516e8d002ca3840564bdfd88d0faff0cf0" } +patchy = { package = "patchy-rs", git = "https://github.com/logdot/patchy-rs.git", rev = "64d2eac7b33f81c4a60f18ae834d9daba96b92cf" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.10.*" diff --git a/crates/highfleet-mod-api/src/patching.rs b/crates/highfleet-mod-api/src/patching.rs index ffc90bb..ce11254 100644 --- a/crates/highfleet-mod-api/src/patching.rs +++ b/crates/highfleet-mod-api/src/patching.rs @@ -147,6 +147,56 @@ pub struct HfmPatchApiWithCallV1 { pub session_patch_call: Option, } +pub const HFM_PATCH_FIXUP_REPLAY: u32 = 1; +pub const HFM_PATCH_FIXUP_RELATIVE: u32 = 2; +pub const HFM_PATCH_FIXUP_RESUME: u32 = 3; + +/// A fixup in a machine code template. `offset` is the start of a replay slot +/// or of a four-byte displacement field at the end of an instruction. +/// `argument` is the replay slot length, the relative target address, or zero +/// for resume, respectively. `reserved` must be zero. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HfmTrampolineFixupV1 { + pub kind: u32, + pub reserved: u32, + pub offset: usize, + pub argument: usize, +} + +/// A borrowed trampoline plan with internal labels already resolved. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HfmTrampolinePlanV1 { + /// Nonempty machine code template, at most one executable page. + pub template: HfmPatchBytes, + /// A live, aligned array of `fixup_count` records. Ignored when empty. + pub fixups: *const HfmTrampolineFixupV1, + pub fixup_count: usize, +} + +/// Stages a custom detour. The patch span and output follow the +/// [`HfmPatchSessionPatchCallV1`] contract. Every exit must leave valid machine +/// state. Replay copies whole instructions verbatim and must be valid where +/// placed. Referenced code and data must stay live for any installed patch. +pub type HfmPatchSessionDetourV1 = unsafe extern "C" fn( + context: *mut c_void, + session: HfmPatchSessionId, + name: HfmStr, + address: usize, + size: usize, + plan: *const HfmTrampolinePlanV1, + output_trampoline: *mut usize, +) -> u32; + +/// Optional custom detour extension. The earlier prefixes are unchanged. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HfmPatchApiWithDetourV1 { + pub base: HfmPatchApiWithCallV1, + pub session_detour: Option, +} + #[cfg(test)] mod tests { use super::*; @@ -165,5 +215,27 @@ mod tests { offset_of!(HfmPatchApiWithCallV1, session_patch_call), size_of::() ); + assert_eq!(offset_of!(HfmPatchApiWithDetourV1, base), 0); + assert_eq!( + offset_of!(HfmPatchApiWithDetourV1, session_detour), + size_of::() + ); + } + + #[test] + fn trampoline_records_have_the_expected_c_layout() { + let pointer_size = size_of::(); + assert_eq!(offset_of!(HfmTrampolineFixupV1, kind), 0); + assert_eq!(offset_of!(HfmTrampolineFixupV1, reserved), 4); + assert_eq!(offset_of!(HfmTrampolineFixupV1, offset), 8); + assert_eq!(offset_of!(HfmTrampolineFixupV1, argument), 8 + pointer_size); + assert_eq!(size_of::(), 8 + 2 * pointer_size); + assert_eq!(offset_of!(HfmTrampolinePlanV1, template), 0); + assert_eq!(offset_of!(HfmTrampolinePlanV1, fixups), 2 * pointer_size); + assert_eq!( + offset_of!(HfmTrampolinePlanV1, fixup_count), + 3 * pointer_size + ); + assert_eq!(size_of::(), 4 * pointer_size); } } diff --git a/src/host_patchy.rs b/src/host_patchy.rs index e4068ff..3a5111d 100644 --- a/src/host_patchy.rs +++ b/src/host_patchy.rs @@ -9,8 +9,10 @@ use crate::session_registry::SessionRegistry; use highfleet_mod_api::{ ffi::HfmStr, patching::{ - HfmCallBridgeV1, HfmPatchApiV1, HfmPatchApiWithCallV1, HfmPatchBytes, HfmPatchSessionId, - HfmPatchSetupV1, HFM_PATCH_ABI_VERSION_1, HFM_PATCH_FAILED, HFM_PATCH_FLAGS_KEEP_PRODUCED, + HfmCallBridgeV1, HfmPatchApiV1, HfmPatchApiWithCallV1, HfmPatchApiWithDetourV1, + HfmPatchBytes, HfmPatchSessionId, HfmPatchSetupV1, 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, @@ -18,7 +20,10 @@ use highfleet_mod_api::{ }; use libloading::Library; use log::{debug, error, warn}; -use patchy::{CallBridge, FlagPolicy, KeepReturn, Patch, PatchError, PatchSession, StackAlignment}; +use patchy::{ + CallBridge, FlagPolicy, KeepReturn, Patch, PatchError, PatchSession, StackAlignment, + TrampolineFixup, TrampolinePlan, +}; use std::{ ffi::c_void, mem::size_of, @@ -82,19 +87,22 @@ pub(crate) unsafe fn offer_patchy(path: &Path, setup: HfmPatchSetupV1) -> u32 { /// Creates the table for one mod. Its context lives for the process because /// the mod may keep the table. -fn patch_api(path: &Path) -> HfmPatchApiWithCallV1 { +fn patch_api(path: &Path) -> HfmPatchApiWithDetourV1 { let context = Box::leak(Box::new(ModContext { path: path.into() })); - HfmPatchApiWithCallV1 { - base: HfmPatchApiV1 { - abi_version: HFM_PATCH_ABI_VERSION_1, - struct_size: size_of::() as u32, - context: (context as *mut ModContext).cast(), - session_create: Some(session_create), - session_discard: Some(session_discard), - session_overwrite: Some(session_overwrite), - session_install: Some(session_install), + HfmPatchApiWithDetourV1 { + base: HfmPatchApiWithCallV1 { + base: HfmPatchApiV1 { + abi_version: HFM_PATCH_ABI_VERSION_1, + struct_size: size_of::() as u32, + context: (context as *mut ModContext).cast(), + session_create: Some(session_create), + session_discard: Some(session_discard), + session_overwrite: Some(session_overwrite), + session_install: Some(session_install), + }, + session_patch_call: Some(session_patch_call), }, - session_patch_call: Some(session_patch_call), + session_detour: Some(session_detour), } } @@ -111,9 +119,12 @@ fn patch_status(owner: &ModContext, operation: &str, err: PatchError) -> u32 { match err { PatchError::OverlappingPatch { .. } => HFM_PATCH_OVERLAP, PatchError::SourceChanged { .. } => HFM_PATCH_SOURCE_CHANGED, - PatchError::PatchTooSmall { .. } | PatchError::EmptyPatch | PatchError::AddressOverflow => { - HFM_PATCH_INVALID_ARGUMENT - } + PatchError::PatchTooSmall { .. } + | PatchError::EmptyPatch + | PatchError::EmptyTrampoline + | PatchError::ReplaySizeMismatch { .. } + | PatchError::TrampolineTooLarge { .. } + | PatchError::AddressOverflow => HFM_PATCH_INVALID_ARGUMENT, _ => HFM_PATCH_FAILED, } } @@ -254,7 +265,12 @@ unsafe extern "C" fn session_patch_call( output: *mut usize, ) -> u32 { run_ffi(|| { - if output.is_null() || address == 0 || address.checked_add(size).is_none() { + if output.is_null() + || !output.is_aligned() + || !bridge.is_aligned() + || address == 0 + || address.checked_add(size).is_none() + { return Err(HFM_PATCH_INVALID_ARGUMENT); } let name = str::from_utf8(unsafe { request_bytes(name.ptr, name.len)? }) @@ -270,6 +286,81 @@ unsafe extern "C" fn session_patch_call( }) } +// The template and fixup array must be live and immutable during decoding. +unsafe fn decode_plan(raw: &HfmTrampolinePlanV1) -> Result { + let template = unsafe { request_bytes(raw.template.ptr, raw.template.len)? }; + let count = raw.fixup_count; + if count > template.len() + || count > isize::MAX as usize / size_of::() + || (count != 0 && (raw.fixups.is_null() || !raw.fixups.is_aligned())) + { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + let records = if count == 0 { + &[] + } else { + unsafe { slice::from_raw_parts(raw.fixups, count) } + }; + let fixups = records + .iter() + .map(|record| { + let HfmTrampolineFixupV1 { + kind, + reserved, + offset, + argument, + } = *record; + if reserved != 0 { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + match kind { + HFM_PATCH_FIXUP_REPLAY => Ok(TrampolineFixup::Replay { + offset, + size: argument, + }), + HFM_PATCH_FIXUP_RELATIVE => Ok(TrampolineFixup::Relative { + offset, + destination: argument, + }), + HFM_PATCH_FIXUP_RESUME if argument == 0 => Ok(TrampolineFixup::Resume { offset }), + _ => Err(HFM_PATCH_INVALID_ARGUMENT), + } + }) + .collect::, _>>()?; + TrampolinePlan::new(template.to_vec(), fixups).map_err(|_| HFM_PATCH_INVALID_ARGUMENT) +} + +unsafe extern "C" fn session_detour( + context: *mut c_void, + session: HfmPatchSessionId, + name: HfmStr, + address: usize, + size: usize, + plan: *const HfmTrampolinePlanV1, + output: *mut usize, +) -> u32 { + run_ffi(|| { + if output.is_null() + || !output.is_aligned() + || !plan.is_aligned() + || address == 0 + || address.checked_add(size).is_none() + { + return Err(HFM_PATCH_INVALID_ARGUMENT); + } + let name = str::from_utf8(unsafe { request_bytes(name.ptr, name.len)? }) + .map_err(|_| HFM_PATCH_INVALID_ARGUMENT)?; + let raw = unsafe { plan.as_ref() }.ok_or(HFM_PATCH_INVALID_ARGUMENT)?; + let plan = unsafe { decode_plan(raw)? }; + let patch = stage_patch(context, session, name, address, |inner| unsafe { + inner.detour_plan(address, size, plan) + })?; + let trampoline = patch.trampoline_address().ok_or(HFM_PATCH_FAILED)?; + unsafe { output.write(trampoline) }; + Ok(()) + }) +} + unsafe extern "C" fn session_install(context: *mut c_void, session: HfmPatchSessionId) -> u32 { run_ffi(|| { let Session { owner, inner } = take_session(context, session)?; @@ -289,11 +380,73 @@ mod tests { const ORIGINAL: u8 = 7; const REPLACEMENT: u8 = 42; + #[test] + fn relative_fixup_preserves_its_destination_during_decoding() { + let template = [0xe9, 0, 0, 0, 0]; + let fixup = HfmTrampolineFixupV1 { + kind: HFM_PATCH_FIXUP_RELATIVE, + reserved: 0, + offset: 1, + argument: 0x2000, + }; + let request = HfmTrampolinePlanV1 { + template: template.as_slice().into(), + fixups: &fixup, + fixup_count: 1, + }; + let plan = unsafe { decode_plan(&request) }.unwrap(); + let code = plan.build(0x1000).unwrap(); + assert_eq!(&code[1..], &(0x2000i32 - 0x1005).to_le_bytes()); + } + + #[test] + fn detour_rejects_overlapping_fixups() { + let api = patch_api(Path::new("test-mod.dll")); + let service = ModService(api.base.base); + let session = service.create(); + let source = [0x90u8; 5]; + let template = [0u8; 8]; + let fixups = [ + HfmTrampolineFixupV1 { + kind: HFM_PATCH_FIXUP_REPLAY, + reserved: 0, + offset: 0, + argument: 5, + }, + HfmTrampolineFixupV1 { + kind: HFM_PATCH_FIXUP_RESUME, + reserved: 0, + offset: 4, + argument: 0, + }, + ]; + let request = HfmTrampolinePlanV1 { + template: template.as_slice().into(), + fixups: fixups.as_ptr(), + fixup_count: fixups.len(), + }; + let mut output = 0; + let status = unsafe { + api.session_detour.unwrap()( + service.0.context, + session, + "invalid plan".into(), + source.as_ptr() as usize, + source.len(), + &request, + &mut output, + ) + }; + assert_eq!(status, HFM_PATCH_INVALID_ARGUMENT); + assert_eq!(output, 0); + assert_eq!(service.discard(session), HFM_PATCH_OK); + } + #[test] fn patch_call_rejects_an_unknown_stack_alignment() { extern "C" fn callback() {} let api = patch_api(Path::new("test-mod.dll")); - let service = ModService(api.base); + let service = ModService(api.base.base); let session = service.create(); let bridge = HfmCallBridgeV1 { callback: callback as *const () as usize, @@ -308,7 +461,7 @@ mod tests { // early the host validates the descriptor. let source = [0x90u8; 5]; let status = unsafe { - api.session_patch_call.unwrap()( + api.base.session_patch_call.unwrap()( service.0.context, session, "test callback".into(), @@ -327,7 +480,7 @@ mod tests { impl ModService { fn new() -> Self { - Self(patch_api(Path::new("test-mod.dll")).base) + Self(patch_api(Path::new("test-mod.dll")).base.base) } fn create(&self) -> HfmPatchSessionId { From 02d21fbb06da895b39cc70f4ad521e6c19bb5a4d Mon Sep 17 00:00:00 2001 From: Timoteo Rider Date: Thu, 26 Nov 2026 11:45:31 -0600 Subject: [PATCH 4/4] Use one plan-based Patchy host ABI --- crates/highfleet-mod-api/src/patching.rs | 97 ++----------- src/host_patchy.rs | 168 ++++++----------------- 2 files changed, 56 insertions(+), 209 deletions(-) diff --git a/crates/highfleet-mod-api/src/patching.rs b/crates/highfleet-mod-api/src/patching.rs index ce11254..296ccb6 100644 --- a/crates/highfleet-mod-api/src/patching.rs +++ b/crates/highfleet-mod-api/src/patching.rs @@ -42,14 +42,6 @@ pub type HfmPatchSessionOverwriteV1 = unsafe extern "C" fn( pub type HfmPatchSessionInstallV1 = unsafe extern "C" fn(context: *mut c_void, session: HfmPatchSessionId) -> u32; -pub const HFM_PATCH_STACK_ALIGNED_16: u32 = 0; -pub const HFM_PATCH_STACK_OFFSET_8: u32 = 1; -pub const HFM_PATCH_FLAGS_PRESERVE: u32 = 0; -pub const HFM_PATCH_FLAGS_KEEP_PRODUCED: u32 = 1; -pub const HFM_PATCH_RETURN_NEITHER: u32 = 0; -pub const HFM_PATCH_RETURN_RAX: u32 = 1; -pub const HFM_PATCH_RETURN_XMM0: u32 = 2; - /// An immutable byte range borrowed during a host call. Null is allowed only /// for an empty range. #[repr(C)] @@ -59,13 +51,6 @@ pub struct HfmPatchBytes { pub len: usize, } -impl HfmPatchBytes { - pub const EMPTY: Self = Self { - ptr: core::ptr::null(), - len: 0, - }; -} - impl From<&[u8]> for HfmPatchBytes { fn from(bytes: &[u8]) -> Self { Self { @@ -75,41 +60,6 @@ impl From<&[u8]> for HfmPatchBytes { } } -/// A Windows x64 callback bridge. The callback must not take stack-passed -/// arguments or unwind out of the bridge, and must remain live through -/// process exit if installed. The direction flag must be clear on entry. -/// -/// `stack_alignment` describes RSP at the patch site. The snippets are -/// verbatim, position-independent, straight-line instructions that must fall -/// through with RSP unchanged without modifying the bridge's saved state. -/// `after_call` runs before register restoration. -#[repr(C)] -#[derive(Clone, Copy)] -pub struct HfmCallBridgeV1 { - pub callback: usize, - pub stack_alignment: u32, - pub flags: u32, - pub keep_return: u32, - pub before_call: HfmPatchBytes, - pub after_call: HfmPatchBytes, -} - -/// Stages a callback and a jump to `address + size`, without replaying the -/// replaced instructions. The source span must remain readable through -/// install and contain complete instructions with no incoming branches into -/// its interior. On success, writes the trampoline address to the supplied -/// live, aligned, writable output pointer. Do not use the trampoline address -/// unless and until session installation succeeds. -pub type HfmPatchSessionPatchCallV1 = unsafe extern "C" fn( - context: *mut c_void, - session: HfmPatchSessionId, - name: HfmStr, - address: usize, - size: usize, - bridge: *const HfmCallBridgeV1, - output_trampoline: *mut usize, -) -> u32; - /// A process-lifetime capability bound to the receiving mod. /// /// `context` must be the value from this table. Sessions belong to the context @@ -134,19 +84,12 @@ pub struct HfmPatchApiV1 { /// Consumes a session belonging to this context, even if install fails. /// No other thread may execute a patch source while it is being written. pub session_install: Option, + /// Stages a trampoline and returns its address. + pub session_detour: Option, } -/// The optional callback extension to the v1 overwrite service. -/// -/// Read the extension only if the prefix's `struct_size` is large enough. -#[repr(C)] -#[derive(Clone, Copy)] -pub struct HfmPatchApiWithCallV1 { - pub base: HfmPatchApiV1, - /// Stages a call bridge, then resumes after the replaced span. - pub session_patch_call: Option, -} - +/// Copies the displaced source span verbatim. Relocating instructions would +/// require a different fixup kind, not a change in meaning of this one. pub const HFM_PATCH_FIXUP_REPLAY: u32 = 1; pub const HFM_PATCH_FIXUP_RELATIVE: u32 = 2; pub const HFM_PATCH_FIXUP_RESUME: u32 = 3; @@ -175,10 +118,14 @@ pub struct HfmTrampolinePlanV1 { pub fixup_count: usize, } -/// Stages a custom detour. The patch span and output follow the -/// [`HfmPatchSessionPatchCallV1`] contract. Every exit must leave valid machine -/// state. Replay copies whole instructions verbatim and must be valid where -/// placed. Referenced code and data must stay live for any installed patch. +/// Stages a detour. The source span must stay readable through installation, +/// contain whole instructions, and have no incoming branches into its +/// interior. Every trampoline exit must leave valid machine state. Replay +/// copies whole instructions verbatim and must be valid where placed. +/// Referenced code and data must stay live for any installed patch. +/// +/// On success, writes the trampoline address to a live, aligned, writable +/// output pointer. Do not use that address unless installation succeeds. pub type HfmPatchSessionDetourV1 = unsafe extern "C" fn( context: *mut c_void, session: HfmPatchSessionId, @@ -189,14 +136,6 @@ pub type HfmPatchSessionDetourV1 = unsafe extern "C" fn( output_trampoline: *mut usize, ) -> u32; -/// Optional custom detour extension. The earlier prefixes are unchanged. -#[repr(C)] -#[derive(Clone, Copy)] -pub struct HfmPatchApiWithDetourV1 { - pub base: HfmPatchApiWithCallV1, - pub session_detour: Option, -} - #[cfg(test)] mod tests { use super::*; @@ -209,17 +148,11 @@ mod tests { assert_eq!(offset_of!(HfmPatchApiV1, struct_size), 4); assert_eq!(offset_of!(HfmPatchApiV1, context), 8); assert_eq!(offset_of!(HfmPatchApiV1, session_create), 8 + pointer_size); - assert_eq!(size_of::(), 8 + pointer_size * 5); - assert_eq!(offset_of!(HfmPatchApiWithCallV1, base), 0); - assert_eq!( - offset_of!(HfmPatchApiWithCallV1, session_patch_call), - size_of::() - ); - assert_eq!(offset_of!(HfmPatchApiWithDetourV1, base), 0); assert_eq!( - offset_of!(HfmPatchApiWithDetourV1, session_detour), - size_of::() + offset_of!(HfmPatchApiV1, session_detour), + 8 + pointer_size * 5 ); + assert_eq!(size_of::(), 8 + pointer_size * 6); } #[test] diff --git a/src/host_patchy.rs b/src/host_patchy.rs index 3a5111d..1a334b3 100644 --- a/src/host_patchy.rs +++ b/src/host_patchy.rs @@ -9,21 +9,15 @@ use crate::session_registry::SessionRegistry; use highfleet_mod_api::{ ffi::HfmStr, patching::{ - HfmCallBridgeV1, HfmPatchApiV1, HfmPatchApiWithCallV1, HfmPatchApiWithDetourV1, - HfmPatchBytes, HfmPatchSessionId, HfmPatchSetupV1, HfmTrampolineFixupV1, + HfmPatchApiV1, HfmPatchSessionId, HfmPatchSetupV1, 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, + HFM_PATCH_FIXUP_REPLAY, HFM_PATCH_FIXUP_RESUME, HFM_PATCH_INVALID_ARGUMENT, HFM_PATCH_OK, + HFM_PATCH_OVERLAP, HFM_PATCH_SOURCE_CHANGED, }, }; use libloading::Library; use log::{debug, error, warn}; -use patchy::{ - CallBridge, FlagPolicy, KeepReturn, Patch, PatchError, PatchSession, StackAlignment, - TrampolineFixup, TrampolinePlan, -}; +use patchy::{Patch, PatchError, PatchSession, TrampolineFixup, TrampolinePlan}; use std::{ ffi::c_void, mem::size_of, @@ -82,26 +76,21 @@ pub unsafe fn setup_mod_patching(library: &Library, path: &Path) { /// The setup callback must accept the v1 table and must not unwind. pub(crate) unsafe fn offer_patchy(path: &Path, setup: HfmPatchSetupV1) -> u32 { let api = patch_api(path); - unsafe { setup(std::ptr::from_ref(&api).cast()) } + unsafe { setup(&api) } } /// Creates the table for one mod. Its context lives for the process because /// the mod may keep the table. -fn patch_api(path: &Path) -> HfmPatchApiWithDetourV1 { +fn patch_api(path: &Path) -> HfmPatchApiV1 { let context = Box::leak(Box::new(ModContext { path: path.into() })); - HfmPatchApiWithDetourV1 { - base: HfmPatchApiWithCallV1 { - base: HfmPatchApiV1 { - abi_version: HFM_PATCH_ABI_VERSION_1, - struct_size: size_of::() as u32, - context: (context as *mut ModContext).cast(), - session_create: Some(session_create), - session_discard: Some(session_discard), - session_overwrite: Some(session_overwrite), - session_install: Some(session_install), - }, - session_patch_call: Some(session_patch_call), - }, + HfmPatchApiV1 { + abi_version: HFM_PATCH_ABI_VERSION_1, + struct_size: size_of::() as u32, + context: (context as *mut ModContext).cast(), + session_create: Some(session_create), + session_discard: Some(session_discard), + session_overwrite: Some(session_overwrite), + session_install: Some(session_install), session_detour: Some(session_detour), } } @@ -219,73 +208,6 @@ unsafe extern "C" fn session_overwrite( }) } -// The descriptor's nonempty byte ranges must be readable and immutable for -// the lifetime of the borrow. No bytes are retained by Patchy after staging. -unsafe fn decode_bridge(raw: &HfmCallBridgeV1) -> Result, u32> { - unsafe fn snippet<'a>(bytes: &'a HfmPatchBytes) -> Result<&'a [u8], u32> { - if bytes.len == 0 { - Ok(&[]) - } else { - unsafe { request_bytes(bytes.ptr, bytes.len) } - } - } - if raw.callback == 0 { - return Err(HFM_PATCH_INVALID_ARGUMENT); - } - Ok(CallBridge { - callback: raw.callback as *const (), - incoming_stack: match raw.stack_alignment { - HFM_PATCH_STACK_ALIGNED_16 => StackAlignment::Aligned16, - HFM_PATCH_STACK_OFFSET_8 => StackAlignment::Offset8, - _ => return Err(HFM_PATCH_INVALID_ARGUMENT), - }, - flags: match raw.flags { - HFM_PATCH_FLAGS_PRESERVE => FlagPolicy::Preserve, - HFM_PATCH_FLAGS_KEEP_PRODUCED => FlagPolicy::KeepProduced, - _ => return Err(HFM_PATCH_INVALID_ARGUMENT), - }, - keep_return: match raw.keep_return { - HFM_PATCH_RETURN_NEITHER => KeepReturn::Neither, - HFM_PATCH_RETURN_RAX => KeepReturn::Rax, - HFM_PATCH_RETURN_XMM0 => KeepReturn::Xmm0, - _ => return Err(HFM_PATCH_INVALID_ARGUMENT), - }, - before_call: unsafe { snippet(&raw.before_call)? }, - after_call: unsafe { snippet(&raw.after_call)? }, - }) -} - -unsafe extern "C" fn session_patch_call( - context: *mut c_void, - session: HfmPatchSessionId, - name: HfmStr, - address: usize, - size: usize, - bridge: *const HfmCallBridgeV1, - output: *mut usize, -) -> u32 { - run_ffi(|| { - if output.is_null() - || !output.is_aligned() - || !bridge.is_aligned() - || address == 0 - || address.checked_add(size).is_none() - { - return Err(HFM_PATCH_INVALID_ARGUMENT); - } - let name = str::from_utf8(unsafe { request_bytes(name.ptr, name.len)? }) - .map_err(|_| HFM_PATCH_INVALID_ARGUMENT)?; - let raw = unsafe { bridge.as_ref() }.ok_or(HFM_PATCH_INVALID_ARGUMENT)?; - let bridge = unsafe { decode_bridge(raw)? }; - let patch = stage_patch(context, session, name, address, |inner| unsafe { - inner.patch_call(address, size, bridge) - })?; - let trampoline = patch.trampoline_address().ok_or(HFM_PATCH_FAILED)?; - unsafe { output.write(trampoline) }; - Ok(()) - }) -} - // The template and fixup array must be live and immutable during decoding. unsafe fn decode_plan(raw: &HfmTrampolinePlanV1) -> Result { let template = unsafe { request_bytes(raw.template.ptr, raw.template.len)? }; @@ -402,7 +324,7 @@ mod tests { #[test] fn detour_rejects_overlapping_fixups() { let api = patch_api(Path::new("test-mod.dll")); - let service = ModService(api.base.base); + let service = ModService(api); let session = service.create(); let source = [0x90u8; 5]; let template = [0u8; 8]; @@ -442,45 +364,12 @@ mod tests { assert_eq!(service.discard(session), HFM_PATCH_OK); } - #[test] - fn patch_call_rejects_an_unknown_stack_alignment() { - extern "C" fn callback() {} - let api = patch_api(Path::new("test-mod.dll")); - let service = ModService(api.base.base); - let session = service.create(); - let bridge = HfmCallBridgeV1 { - callback: callback as *const () as usize, - stack_alignment: u32::MAX, - flags: HFM_PATCH_FLAGS_PRESERVE, - keep_return: HFM_PATCH_RETURN_NEITHER, - before_call: HfmPatchBytes::EMPTY, - after_call: HfmPatchBytes::EMPTY, - }; - let mut trampoline = 0; - // A readable source keeps the rejection test independent of how - // early the host validates the descriptor. - let source = [0x90u8; 5]; - let status = unsafe { - api.base.session_patch_call.unwrap()( - service.0.context, - session, - "test callback".into(), - source.as_ptr() as usize, - source.len(), - &bridge, - &mut trampoline, - ) - }; - assert_eq!(status, HFM_PATCH_INVALID_ARGUMENT); - assert_eq!(service.discard(session), HFM_PATCH_OK); - } - /// The table one mod would receive during setup. struct ModService(HfmPatchApiV1); impl ModService { fn new() -> Self { - Self(patch_api(Path::new("test-mod.dll")).base.base) + Self(patch_api(Path::new("test-mod.dll"))) } fn create(&self) -> HfmPatchSessionId { @@ -758,4 +647,29 @@ mod tests { assert_eq!(service.install(conflicting), HFM_PATCH_OVERLAP); assert_unknown(&service, conflicting); } + + #[test] + fn another_mod_cannot_overwrite_an_installed_patch() { + let first = ModService::new(); + let second = ModService::new(); + let target = writable_bytes(); + + let installed = first.create(); + assert_eq!(first.overwrite_byte(installed, target), HFM_PATCH_OK); + assert_eq!(first.install(installed), HFM_PATCH_OK); + + let conflicting = second.create(); + assert_eq!( + second.overwrite( + conflicting, + "conflicting overwrite".into(), + target as usize, + &ORIGINAL, + 1, + ), + HFM_PATCH_OK + ); + assert_eq!(second.install(conflicting), HFM_PATCH_OVERLAP); + assert_eq!(read(target), REPLACEMENT); + } }