[pr-fix] loader: a patch writes only bytes it checked, inside the image #412

Open
qnjk wants to merge 1 commit from qnjk/Darner:callhook-patch-bounds into main
First-time contributor

Contributor role (optional)

  • Fluxer ID:

What it changes

  • The problem on main: patch_bytes reads expected.len() bytes at at, compares them, then writes new.len() bytes at the same address:

    pub unsafe fn patch_bytes(at: usize, expected: &[u8], new: &[u8]) -> Result<()> {
        let found = unsafe { std::slice::from_raw_parts(at as *const u8, expected.len()) };
        if found != expected { bail!(...) }
        unsafe { write_code(at, new) }
    }
    

    (crates/darner-loader/src/callhook.rs:186). Two things are unchecked: a longer new overwrites title instructions the guard never compared (the shape hook_entry avoids at callhook.rs:176 with jump.resize(prologue.len(), 0x90)), a shorter one leaves a checked instruction half replaced, and neither length is bounded by the title image, so the write can leave it.

  • This change makes the image window a parameter — patch_bytes(base, size, at, expected, new), as frame_rate::apply and heap_sites::apply already take it — and refuses, before reading anything, when new.len() != expected.len() or when at.checked_sub(base).and_then(|o| o.checked_add(new.len())) leaves [base, base + size) (the arithmetic heap_sites.rs:1349 uses). A bare absolute address cannot tell whether at is title code or one of our thunk pages, which is why the window is passed in rather than guessed; our thunk pages are written by place when they are made, never through here, and the doc now says so.

  • Note for review: patch_bytes has no caller in this tree today (grep patch_bytes finds the definition only). So this is hardening of a pub unsafe API that a fork can call, not a fix for a live path — if you would rather see it deleted, that is a fine answer and this change makes that decision easier to take instead of harder.

How it was tested

  • Tested revision: 67fbdd4 (one commit on f3840d7).
  • Commands and results:
    • cargo test --locked -p darner-loader --lib — 94 passed, 0 failed.
    • Two new tests, both bare-runner and using a stack buffer of our own (no title, no adapter, no VirtualAlloc, so they add no allocator churn to the exception-handler tests in the same process):
      • callhook::tests::a_patch_that_leaves_the_image_is_refused — a range wholly before the image and one straddling its end are refused with the bytes unchanged, and a range inside is written.
      • callhook::tests::a_patch_of_another_length_is_refused — a 7-byte and a 3-byte new over the same 5 checked bytes are refused with the bytes unchanged.
    • Fail-before, with only the two guards disabled (if false && …) and the tests kept:
      a_patch_of_another_length_is_refused panicked at callhook.rs:410:
        assertion failed: patch_bytes(image as usize, 16, image as usize, &expected, &[0x90; 7]).is_err()
      a_patch_that_leaves_the_image_is_refused panicked at callhook.rs:379:
        assertion failed: patch_bytes(image as usize, size, before as usize, &expected, &new).is_err()
      test result: FAILED. 0 passed; 2 failed
      
      i.e. the old code returned Ok and wrote the bytes.
    • cargo clippy --locked -p darner-loader --all-targets -- -D warnings passes.
  • Changes a default: no. There is no caller, so nothing observable changes; the API now refuses inputs it used to accept.
  • A/B result, for a change of a default (on for everyone) or a speed claim: not applicable — no default changes and no speed claim.
  • Gates run on that revision:
    • Gate 1, cargo clippy --workspace --all-targets --locked -- -D warnings: passes.
    • Gate 2, cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: passes.
    • Gate 3, cargo test --workspace --locked: not green on this machine, and not because of this change. Three pre-existing failures, each covered by an open pull request: darner-gpu stands still in parallel on the test deadlock #224 describes, and serially finishes 1772 passed and 1 failed (pipeline::make::tests::a_capped_draw_waits_once_then_drops, which passes on its own) beside the order-dependent flakes of #150; darner-shader fails emit::waterfall_tests::sampled_marks_restore_early_depth_only_when_safe_in_pixel_shaders, whose fixture #227 fixes. darner-loader's own suite is green.
  • Gameplay, when relevant: no gameplay run — nothing calls this function, so a run cannot reach it.
  • Shader wave sizes tested, when relevant: not applicable.
  • Hardware dependence: none.
  • Coverage gaps: no caller was added, and none exists; the tests use a stack buffer, not a mapped PE image.

Checklist

  • I ran this change in the game, or say below why it can't be (docs, tests only).
    • Not applicable: nothing calls patch_bytes, so it cannot run during a game session. The evidence is the two tests, which fail on main.
  • This PR contains one change based on main.
  • The diff follows docs/asset-policy.md. (cargo xtask policy: 555 files ok.)
  • I recorded this PR's dependencies below.
    • Depends on: none

Checked for overlap

  • I searched the open pull requests for the same issue and for the files this touches.
  • Related PRs: #314 touches crates/darner-loader/src/callhook.rs (it adds the six missing // SAFETY: comments, this file's tests among them), so a small conflict in the test module is possible; that is why it is listed. Open PR #9 names darner_hle::viewhook::install as a caller of patch_bytes; that caller is not on main and does not exist in this tree, so if #9 lands after this one it must pass the new base, size arguments. No open or closed issue or pull request mentions patch_bytes otherwise.
  • Replaces or overlaps: none found
## Contributor role (optional) - Fluxer ID: ## What it changes - The problem on main: `patch_bytes` reads `expected.len()` bytes at `at`, compares them, then writes `new.len()` bytes at the same address: ```rust pub unsafe fn patch_bytes(at: usize, expected: &[u8], new: &[u8]) -> Result<()> { let found = unsafe { std::slice::from_raw_parts(at as *const u8, expected.len()) }; if found != expected { bail!(...) } unsafe { write_code(at, new) } } ``` (`crates/darner-loader/src/callhook.rs:186`). Two things are unchecked: a longer `new` overwrites title instructions the guard never compared (the shape `hook_entry` avoids at `callhook.rs:176` with `jump.resize(prologue.len(), 0x90)`), a shorter one leaves a checked instruction half replaced, and neither length is bounded by the title image, so the write can leave it. - This change makes the image window a parameter — `patch_bytes(base, size, at, expected, new)`, as `frame_rate::apply` and `heap_sites::apply` already take it — and refuses, before reading anything, when `new.len() != expected.len()` or when `at.checked_sub(base).and_then(|o| o.checked_add(new.len()))` leaves `[base, base + size)` (the arithmetic `heap_sites.rs:1349` uses). A bare absolute address cannot tell whether `at` is title code or one of our thunk pages, which is why the window is passed in rather than guessed; our thunk pages are written by `place` when they are made, never through here, and the doc now says so. - Note for review: `patch_bytes` has **no caller in this tree today** (`grep patch_bytes` finds the definition only). So this is hardening of a `pub unsafe` API that a fork can call, not a fix for a live path — if you would rather see it deleted, that is a fine answer and this change makes that decision easier to take instead of harder. ## How it was tested - Tested revision: `67fbdd4` (one commit on `f3840d7`). - Commands and results: - `cargo test --locked -p darner-loader --lib` — 94 passed, 0 failed. - Two new tests, both bare-runner and using a stack buffer of our own (no title, no adapter, no `VirtualAlloc`, so they add no allocator churn to the exception-handler tests in the same process): - `callhook::tests::a_patch_that_leaves_the_image_is_refused` — a range wholly before the image and one straddling its end are refused with the bytes unchanged, and a range inside is written. - `callhook::tests::a_patch_of_another_length_is_refused` — a 7-byte and a 3-byte `new` over the same 5 checked bytes are refused with the bytes unchanged. - Fail-before, with only the two guards disabled (`if false && …`) and the tests kept: ``` a_patch_of_another_length_is_refused panicked at callhook.rs:410: assertion failed: patch_bytes(image as usize, 16, image as usize, &expected, &[0x90; 7]).is_err() a_patch_that_leaves_the_image_is_refused panicked at callhook.rs:379: assertion failed: patch_bytes(image as usize, size, before as usize, &expected, &new).is_err() test result: FAILED. 0 passed; 2 failed ``` i.e. the old code returned `Ok` and wrote the bytes. - `cargo clippy --locked -p darner-loader --all-targets -- -D warnings` passes. - Changes a default: no. There is no caller, so nothing observable changes; the API now refuses inputs it used to accept. - A/B result, for a change of a default (on for everyone) or a speed claim: not applicable — no default changes and no speed claim. - Gates run on that revision: - Gate 1, `cargo clippy --workspace --all-targets --locked -- -D warnings`: passes. - Gate 2, `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings`: passes. - Gate 3, `cargo test --workspace --locked`: **not green on this machine, and not because of this change.** Three pre-existing failures, each covered by an open pull request: `darner-gpu` stands still in parallel on the test deadlock #224 describes, and serially finishes 1772 passed and 1 failed (`pipeline::make::tests::a_capped_draw_waits_once_then_drops`, which passes on its own) beside the order-dependent flakes of #150; `darner-shader` fails `emit::waterfall_tests::sampled_marks_restore_early_depth_only_when_safe_in_pixel_shaders`, whose fixture #227 fixes. `darner-loader`'s own suite is green. - Gameplay, when relevant: no gameplay run — nothing calls this function, so a run cannot reach it. - Shader wave sizes tested, when relevant: not applicable. - Hardware dependence: none. - Coverage gaps: no caller was added, and none exists; the tests use a stack buffer, not a mapped PE image. ## Checklist - [x] I ran this change in the game, or say below why it can't be (docs, tests only). - Not applicable: nothing calls `patch_bytes`, so it cannot run during a game session. The evidence is the two tests, which fail on `main`. - [x] This PR contains one change based on `main`. - [x] The diff follows `docs/asset-policy.md`. (`cargo xtask policy`: 555 files ok.) - [x] I recorded this PR's dependencies below. - Depends on: none ## Checked for overlap - [x] I searched the open pull requests for the same issue and for the files this touches. - Related PRs: #314 touches `crates/darner-loader/src/callhook.rs` (it adds the six missing `// SAFETY:` comments, this file's tests among them), so a small conflict in the test module is possible; that is why it is listed. **Open PR #9 names `darner_hle::viewhook::install` as a caller of `patch_bytes`**; that caller is not on `main` and does not exist in this tree, so if #9 lands after this one it must pass the new `base, size` arguments. No open or closed issue or pull request mentions `patch_bytes` otherwise. - Replaces or overlaps: none found
`patch_bytes` read `expected.len()` bytes at `at`, compared them, and then
wrote `new.len()` bytes at the same place: a longer `new` overwrote title
instructions the guard never compared, and a shorter one left a checked
instruction half replaced. Nothing said the write stayed inside the image
either, though the function is for the title's code and its doc promised
everything written was verified.

The image window is now a parameter (`base`, `size`, as `frame_rate::apply`
and `heap_sites::apply` take it): `at` and the whole write must lie in it,
checked with `checked_sub`/`checked_add` before anything is read, and `new`
must be exactly as long as `expected`, so every byte written is a byte that
was compared first. Our own thunk pages are not in the image; they are
written when they are made (`place`), never here.

Tests: `a_patch_that_leaves_the_image_is_refused` (a range wholly before the
image and one straddling its end are refused, the bytes unchanged; a range
inside is written) and `a_patch_of_another_length_is_refused`. Memory of our
own, no title or adapter.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u 'callhook-patch-bounds:qnjk-callhook-patch-bounds'
git switch 'qnjk-callhook-patch-bounds'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'qnjk-callhook-patch-bounds'
git switch 'qnjk-callhook-patch-bounds'
git rebase 'main'
git switch 'main'
git merge --ff-only 'qnjk-callhook-patch-bounds'
git switch 'qnjk-callhook-patch-bounds'
git rebase 'main'
git switch 'main'
git merge --no-ff 'qnjk-callhook-patch-bounds'
git switch 'main'
git merge --squash 'qnjk-callhook-patch-bounds'
git switch 'main'
git merge --ff-only 'qnjk-callhook-patch-bounds'
git switch 'main'
git merge 'qnjk-callhook-patch-bounds'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
TrustNo1/Darner!412
No description provided.