fix(elfpatcher): reject an entry-stub rel32 distance that only fits after a 64-bit wrap #12554

Merged
dkdhanda8 merged 2 commits from upstream-pr/12554 into main 2026-10-30 09:51:51 +00:00
dkdhanda8 commented 2026-10-28 19:26:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by dkdhanda8 on 2026-10-28T19:26:01Z.


What

BuildEntryStub (the stub every target's patcher calls before the guest's real entry point) computed its rel32 call displacement as static_cast<std::int64_t>(realEntryVaddr - callNextVaddr) — an unsigned difference cast to signed — and range-checked the result. Two addresses more than 2^63 apart wrap into a small in-range value (entry = 0xFFFFFFFFFFFFF000, callNext = 0x1015 wraps to -0x2015), so the rel32 check passed and the stub called an address ~2^64 away from the entry point instead of failing. This is the same correctness gap #12307 fixed for the Linux patcher's five sites; the entry stub is the shared builder both that PR's body and its review thread point at, and it sits in elfpatcher/general, so a crafted ELF reaches it through every output target.

ComputeExtraBlockVaddr anchors the extra block at the page end of the highest kept PT_LOAD, which comes from the input program headers, and e_entry is guest-controlled, so the pair is attacker-reachable. With the change the builder throws Entry stub call exceeds rel32 range for such inputs; without it, main writes a wrapped rel32 and produces a broken image with no diagnostic.

Changed: core/relinker/elfpatcher/src/general/EntryStubBuilder.cpp takes the shared SignedDistance(to, from, out) helper (elfpatcher/general/AddressDistance.hpp, identical to the one in #12307): it classifies both addresses by the 2^63 boundary — within one half the modular difference equals the mathematical one — and for opposite halves takes the high-minus-low magnitude as a plain subtraction, rejecting a magnitude int64 cannot hold. Regression case stubRejectsAnEntryBeyondTheWrapBoundary in EntryStubTests.cpp: stub at 0x1000, entry at 0xFFFFFFFFFFFFF000; on main the builder emits a wrapped rel32, with the change it throws with the rel32 message.

Not changed: StubBodyBuilder::Finish's constant fixups subtract two offsets that are both bounded by the stub body itself, so no pair can wrap; the macOS and Windows patchers' own displacement math runs in 32-bit RVA space; the Linux patcher's five sites are #12307.

Fixes: none (new finding, same malformed-input method as #10653 and #12307).

Branch: fix/entry-stub-rel32-wrap, based on main 319621ba2.

Depends on: #12307 (shares the identical AddressDistance.hpp; if #12307 lands first the files merge cleanly, otherwise both add the same bytes).

Tested

  • entry_stub_tests: on main the new case fails with "an entry point more than 2^63 from the stub was accepted with a wrapped displacement"; with the change the whole suite passes (Windows 11, MinGW-w64 GCC 15.2.0, Ninja, Release).
  • linux_load_pages_tests (links the changed builder) passes with the change.
  • tools/check_conventions.py --base origin/main passes.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); no silent stubs added
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: #12307
  • Fixes: none (new finding)
  • Unblocks: none
  • GPUs tested: n/a (relinker only)
  • AI-assisted: yes

AI-assisted (ZCode): the finding, the fix and the verification were prepared with AI assistance; every line was reviewed and all runs were executed locally.

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5056417238 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12554). Originally posted by [dkdhanda8](https://github.com/dkdhanda8) on 2026-10-28T19:26:01Z. --- ### What `BuildEntryStub` (the stub every target's patcher calls before the guest's real entry point) computed its rel32 call displacement as `static_cast<std::int64_t>(realEntryVaddr - callNextVaddr)` — an unsigned difference cast to signed — and range-checked the result. Two addresses more than 2^63 apart wrap into a small in-range value (`entry = 0xFFFFFFFFFFFFF000`, `callNext = 0x1015` wraps to `-0x2015`), so the rel32 check passed and the stub called an address ~2^64 away from the entry point instead of failing. This is the same correctness gap #12307 fixed for the Linux patcher's five sites; the entry stub is the shared builder both that PR's body and its review thread point at, and it sits in `elfpatcher/general`, so a crafted ELF reaches it through every output target. `ComputeExtraBlockVaddr` anchors the extra block at the page end of the highest kept PT_LOAD, which comes from the input program headers, and `e_entry` is guest-controlled, so the pair is attacker-reachable. With the change the builder throws `Entry stub call exceeds rel32 range` for such inputs; without it, main writes a wrapped rel32 and produces a broken image with no diagnostic. Changed: `core/relinker/elfpatcher/src/general/EntryStubBuilder.cpp` takes the shared `SignedDistance(to, from, out)` helper (`elfpatcher/general/AddressDistance.hpp`, identical to the one in #12307): it classifies both addresses by the 2^63 boundary — within one half the modular difference equals the mathematical one — and for opposite halves takes the high-minus-low magnitude as a plain subtraction, rejecting a magnitude `int64` cannot hold. Regression case `stubRejectsAnEntryBeyondTheWrapBoundary` in `EntryStubTests.cpp`: stub at 0x1000, entry at `0xFFFFFFFFFFFFF000`; on `main` the builder emits a wrapped rel32, with the change it throws with the rel32 message. Not changed: `StubBodyBuilder::Finish`'s constant fixups subtract two offsets that are both bounded by the stub body itself, so no pair can wrap; the macOS and Windows patchers' own displacement math runs in 32-bit RVA space; the Linux patcher's five sites are #12307. Fixes: none (new finding, same malformed-input method as #10653 and #12307). Branch: `fix/entry-stub-rel32-wrap`, based on `main` `319621ba2`. Depends on: #12307 (shares the identical `AddressDistance.hpp`; if #12307 lands first the files merge cleanly, otherwise both add the same bytes). ### Tested - `entry_stub_tests`: on `main` the new case fails with "an entry point more than 2^63 from the stub was accepted with a wrapped displacement"; with the change the whole suite passes (Windows 11, MinGW-w64 GCC 15.2.0, Ninja, Release). - `linux_load_pages_tests` (links the changed builder) passes with the change. - `tools/check_conventions.py --base origin/main` passes. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); no silent stubs added - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: #12307 - [x] Fixes: none (new finding) - [x] Unblocks: none - [x] GPUs tested: n/a (relinker only) - [x] AI-assisted: yes AI-assisted (ZCode): the finding, the fix and the verification were prepared with AI assistance; every line was reviewed and all runs were executed locally.
MarcZX10 commented 2026-10-28 19:34:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-28T19:34:32Z.

Review: CHANGES_REQUESTED


Reviewed — changes requested

The exact head 62e201bd8fb8d744ca292ab97dc557b7f0976bd8 has a reproducible signed-overflow case in SignedDistance, and its new helper conflicts with the same helper added by declared dependency #12307.

What I ran

  • Reviewed head 62e201bd8fb8d744ca292ab97dc557b7f0976bd8 against base 319621ba2e578bd053b0baba2877fe70520e0737; merge preview is clean (3eeac2ff11f66eab8dcc70d9fe77ea4ea5d21d22).
  • git diff --check refs/review/current-main...refs/review/12554 — passed with no output.
  • Compiled and ran a minimal exact-helper reproducer with GCC 12.2 / C++20 / UBSan:
    g++ -std=c++20 -fsanitize=undefined -fno-sanitize-recover=undefined -I /dev/shm/include /dev/shm/test_address_distance_12554.cpp -o /dev/shm/test_address_distance_12554
    /dev/shm/test_address_distance_12554
    
  • Compared the helper with open PR #12307 and ran a combined merge preview.
  • Refreshed gh pr checks 12554: Ubuntu relinker, relinker ASan, conventions, eligibility, intake and labels pass; Windows and macOS relinker jobs are pending; product jobs are skipped.

Results

Check Result
Current-main merge preview Clean
Diff check Pass
Exact-helper UBSan reproduction Fails: signed overflow at the negative INT64_MIN boundary
Combined merge preview with #12307 Add/add conflict in AddressDistance.hpp
Hosted Ubuntu relinker and relinker ASan Pass
Hosted Windows/macOS relinker Pending
Product tests Skipped by CI
Raw UBSan and merge output
/dev/shm/include/elfpatcher/general/AddressDistance.hpp:21:22: runtime error: negation of -9223372036854775808 cannot be represented in type 'long int'; cast to an unsigned type to negate this value to itself

CONFLICT (add/add): Merge conflict in core/relinker/elfpatcher/include/elfpatcher/general/AddressDistance.hpp

Negative control

Assertion Change under test Result
SignedDistance(0, 1ULL << 63, out) must not invoke signed overflow Ran the exact PR helper with -fsanitize=undefined -fno-sanitize-recover=undefined UBSan aborts at the unary negation on line 21

Findings

Blocking

  • Signed overflow at the negative INT64_MIN boundary. When magnitude == 2^63 and high != to, the helper converts 2^63 to int64_t and negates it. UBSan confirms negating INT64_MIN is undefined. Return the representable INT64_MIN explicitly for this negative boundary, or reject this magnitude; add a regression assertion under UBSan.
  • The shared helper does not match its declared dependency. #12307 adds the same AddressDistance.hpp path, but the PR versions differ: #12307 rejects magnitude >= 2^63, while this head accepts the negative-equal case. The combined merge preview reports an add/add conflict, contrary to the description that the files merge cleanly or add identical bytes. Please restack on #12307 and reuse/reconcile the helper, then rerun the focused test and overlap check.

Non-blocking

No other source issue identified in the small call-site change.

Sources

Not verified

I did not run the full relinker suite, Windows/macOS builds, or a console/title run. Those hosted jobs are pending or skipped as listed.

To get this to a good state

Fix or reject the negative 2^63 magnitude without signed overflow, add an exact boundary regression, and reconcile this branch with #12307 so the shared helper has one agreed implementation. I will rerun the sanitizer reproducer, focused tests, overlap check and merge preview on the updated head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5688588857 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12554#pullrequestreview-5688588857). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-28T19:34:32Z. **Review:** CHANGES_REQUESTED --- # Reviewed — changes requested The exact head `62e201bd8fb8d744ca292ab97dc557b7f0976bd8` has a reproducible signed-overflow case in `SignedDistance`, and its new helper conflicts with the same helper added by declared dependency #12307. ## What I ran - Reviewed head `62e201bd8fb8d744ca292ab97dc557b7f0976bd8` against base `319621ba2e578bd053b0baba2877fe70520e0737`; merge preview is clean (`3eeac2ff11f66eab8dcc70d9fe77ea4ea5d21d22`). - `git diff --check refs/review/current-main...refs/review/12554` — passed with no output. - Compiled and ran a minimal exact-helper reproducer with GCC 12.2 / C++20 / UBSan: ```sh g++ -std=c++20 -fsanitize=undefined -fno-sanitize-recover=undefined -I /dev/shm/include /dev/shm/test_address_distance_12554.cpp -o /dev/shm/test_address_distance_12554 /dev/shm/test_address_distance_12554 ``` - Compared the helper with open PR #12307 and ran a combined merge preview. - Refreshed `gh pr checks 12554`: Ubuntu relinker, relinker ASan, conventions, eligibility, intake and labels pass; Windows and macOS relinker jobs are pending; product jobs are skipped. ## Results | Check | Result | |---|---| | Current-main merge preview | Clean | | Diff check | Pass | | Exact-helper UBSan reproduction | Fails: signed overflow at the negative `INT64_MIN` boundary | | Combined merge preview with #12307 | Add/add conflict in `AddressDistance.hpp` | | Hosted Ubuntu relinker and relinker ASan | Pass | | Hosted Windows/macOS relinker | Pending | | Product tests | Skipped by CI | <details> <summary>Raw UBSan and merge output</summary> ```text /dev/shm/include/elfpatcher/general/AddressDistance.hpp:21:22: runtime error: negation of -9223372036854775808 cannot be represented in type 'long int'; cast to an unsigned type to negate this value to itself CONFLICT (add/add): Merge conflict in core/relinker/elfpatcher/include/elfpatcher/general/AddressDistance.hpp ``` </details> ## Negative control | Assertion | Change under test | Result | |---|---|---| | `SignedDistance(0, 1ULL << 63, out)` must not invoke signed overflow | Ran the exact PR helper with `-fsanitize=undefined -fno-sanitize-recover=undefined` | UBSan aborts at the unary negation on line 21 | ## Findings ### Blocking - **Signed overflow at the negative `INT64_MIN` boundary.** When `magnitude == 2^63` and `high != to`, the helper converts `2^63` to `int64_t` and negates it. UBSan confirms negating `INT64_MIN` is undefined. Return the representable `INT64_MIN` explicitly for this negative boundary, or reject this magnitude; add a regression assertion under UBSan. - **The shared helper does not match its declared dependency.** #12307 adds the same `AddressDistance.hpp` path, but the PR versions differ: #12307 rejects `magnitude >= 2^63`, while this head accepts the negative-equal case. The combined merge preview reports an add/add conflict, contrary to the description that the files merge cleanly or add identical bytes. Please restack on #12307 and reuse/reconcile the helper, then rerun the focused test and overlap check. ### Non-blocking No other source issue identified in the small call-site change. ## Sources - [Changed distance helper at this PR head](https://github.com/boykopovar/AnyPS5/blob/62e201bd8fb8d744ca292ab97dc557b7f0976bd8/core/relinker/elfpatcher/include/elfpatcher/general/AddressDistance.hpp) - [Entry-stub call-site at this PR head](https://github.com/boykopovar/AnyPS5/blob/62e201bd8fb8d744ca292ab97dc557b7f0976bd8/core/relinker/elfpatcher/src/general/EntryStubBuilder.cpp) - [Dependency #12307 helper at head `d9ab85865a09be22241ae6631e0d1fa8e800b273`](https://github.com/boykopovar/AnyPS5/blob/d9ab85865a09be22241ae6631e0d1fa8e800b273/core/relinker/elfpatcher/include/elfpatcher/general/AddressDistance.hpp) - [Contribution rules on dependency ordering and overlap](https://github.com/boykopovar/AnyPS5/blob/319621ba2e578bd053b0baba2877fe70520e0737/CONTRIBUTING.md) ## Not verified I did not run the full relinker suite, Windows/macOS builds, or a console/title run. Those hosted jobs are pending or skipped as listed. ## To get this to a good state Fix or reject the negative `2^63` magnitude without signed overflow, add an exact boundary regression, and reconcile this branch with #12307 so the shared helper has one agreed implementation. I will rerun the sanitizer reproducer, focused tests, overlap check and merge preview on the updated head.
Sign in to join this conversation.
No reviewers
No labels
No milestone
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.

Reference
boykopovar/AnyPS5!12554
No description provided.