fix(elfpatcher): take rel32 displacements as unsigned differences #12307

Merged
dkdhanda8 merged 3 commits from upstream-pr/12307 into main 2026-10-30 01:04:11 +00:00
dkdhanda8 commented 2026-10-28 08:39:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by dkdhanda8 on 2026-10-28T08:39:42Z.


What

The Linux output path computed branch displacements as subtractions of two std::int64_t casts:

  • the trampoline return/jump displacements in LinuxElfPatcher::_appendTrampoline (site.Address vs bodyVaddr),
  • the RIP-relative import-trace displacement in TracePrologue (target vs vaddr + code.size() + 4),
  • the guest module stubDisplacement lambda and the finaliser distance in LinuxGuestModuleWriter (target/image.Init/image.Fini vs the stub being emitted).

_programHeaderLayoutBuilder->ComputeExtraBlockVaddr anchors the extra block at the page end of the highest kept PT_LOAD, which comes from the input program headers. Crafted headers can end that segment exactly at 2^63, so the trampoline bodies, the import trace and the entry stub land above the sign boundary while the original AMD-only sites (and e_entry, if it points into that segment) sit below it. Both casts then flip sign and the subtraction overflows before the rel32 range check runs: undefined behaviour. Found while extending the #10653 verification to the rest of the relinker: the new unit test aborts with Illegal instruction under -fsanitize=undefined -fsanitize-undefined-trap-on-error on main.

The differences are now taken in unsigned arithmetic and cast to std::int64_t once — the shape BuildEntryStub already uses for the entry-stub call (EntryStubBuilder.cpp), which is why that path stays in range and the patcher gets as far as the trampoline loop. With the change the true displacement (a few KB) fits rel32, so a segment laid out this way now patches into a valid image where main aborted under sanitizers; unsanitized the wrap is exact, so output bytes are unchanged on main for every input whose addresses do not straddle the boundary.

Changed: core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp (three subtractions), core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp (two), with the regression case TrampolineDisplacementAcrossInt64Max in LinuxLoadPageTests.cpp: one PT_LOAD whose page end is 2^63, an INSERTQ site mapped just below the boundary, the entry point inside the high segment (so the entry stub's rel32 call stays in range), asserting the body lands above 2^63 and both written rel32 values equal the true differences.

Review follow-up (second commit): unsigned subtraction still wraps two addresses that are more than 2^63 apart into a small in-range value, so the rel32 check passed on a displacement that was never real (target = 0x100, next = UINT64_MAX wraps to 0x101). The five sites now take a shared SignedDistance(to, from, out) helper (elfpatcher/general/AddressDistance.hpp) that classifies both addresses by the 2^63 boundary, takes the high-minus-low magnitude as a plain subtraction and returns false when the magnitude exceeds int64; the patcher throws instead of writing the wrapped value. The new TrampolineDisplacementBeyondInt64Range test places the site at 0x500 and the body near 2^64: on the previous commit it wrote a wrapped rel32 and "succeeded", with the change it throws.

Left alone on purpose: TracePrologue's backward loop byte subtracts code indices, never addresses; the macOS and Windows patchers do the same math in 32-bit RVA space, where no pair can straddle the boundary. TracePrologue and the guest module writer share the fixed idiom but have no lightweight fixture (the former needs a full dynamic section with libc.prx, the latter a guest image); the trampoline test pins the shared pattern.

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

Branch: fix/linux-patch-unsigned-displacement, based on main 87b810a1d. Different files from the rest of the queue; no conflicts.

Tested

  • linux_load_pages_tests: on main it aborts under the trap-on-error UBSan build and passes with the change under the same build; it passes unsanitized on both.
  • relinker_core (both changed files) builds clean under the same sanitizer flags.
  • Full relinker-only ctest under the trap-on-error build (Windows 11, MinGW-w64 GCC 15.2.0): failure set identical to main; every failure is this machine's Application Control policy refusing to execute freshly built outputs (WinError 4551) or its knock-on subprocess timeouts, present before 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: none
  • 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:5047600519 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12307). Originally posted by [dkdhanda8](https://github.com/dkdhanda8) on 2026-10-28T08:39:42Z. --- ### What The Linux output path computed branch displacements as subtractions of two `std::int64_t` casts: - the trampoline return/jump displacements in `LinuxElfPatcher::_appendTrampoline` (`site.Address` vs `bodyVaddr`), - the RIP-relative import-trace displacement in `TracePrologue` (`target` vs `vaddr + code.size() + 4`), - the guest module `stubDisplacement` lambda and the finaliser distance in `LinuxGuestModuleWriter` (`target`/`image.Init`/`image.Fini` vs the stub being emitted). `_programHeaderLayoutBuilder->ComputeExtraBlockVaddr` anchors the extra block at the page end of the highest kept PT_LOAD, which comes from the input program headers. Crafted headers can end that segment exactly at 2^63, so the trampoline bodies, the import trace and the entry stub land *above* the sign boundary while the original AMD-only sites (and `e_entry`, if it points into that segment) sit *below* it. Both casts then flip sign and the subtraction overflows before the rel32 range check runs: undefined behaviour. Found while extending the #10653 verification to the rest of the relinker: the new unit test aborts with `Illegal instruction` under `-fsanitize=undefined -fsanitize-undefined-trap-on-error` on `main`. The differences are now taken in unsigned arithmetic and cast to `std::int64_t` once — the shape `BuildEntryStub` already uses for the entry-stub call (`EntryStubBuilder.cpp`), which is why that path stays in range and the patcher gets as far as the trampoline loop. With the change the true displacement (a few KB) fits rel32, so a segment laid out this way now patches into a valid image where `main` aborted under sanitizers; unsanitized the wrap is exact, so output bytes are unchanged on `main` for every input whose addresses do not straddle the boundary. Changed: `core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp` (three subtractions), `core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp` (two), with the regression case `TrampolineDisplacementAcrossInt64Max` in `LinuxLoadPageTests.cpp`: one PT_LOAD whose page end is 2^63, an INSERTQ site mapped just below the boundary, the entry point inside the high segment (so the entry stub's rel32 call stays in range), asserting the body lands above 2^63 and both written rel32 values equal the true differences. Review follow-up (second commit): unsigned subtraction still wraps two addresses that are more than 2^63 apart into a small in-range value, so the rel32 check passed on a displacement that was never real (`target = 0x100`, `next = UINT64_MAX` wraps to `0x101`). The five sites now take a shared `SignedDistance(to, from, out)` helper (`elfpatcher/general/AddressDistance.hpp`) that classifies both addresses by the 2^63 boundary, takes the high-minus-low magnitude as a plain subtraction and returns false when the magnitude exceeds `int64`; the patcher throws instead of writing the wrapped value. The new `TrampolineDisplacementBeyondInt64Range` test places the site at 0x500 and the body near 2^64: on the previous commit it wrote a wrapped rel32 and "succeeded", with the change it throws. Left alone on purpose: `TracePrologue`'s backward loop byte subtracts code indices, never addresses; the macOS and Windows patchers do the same math in 32-bit RVA space, where no pair can straddle the boundary. `TracePrologue` and the guest module writer share the fixed idiom but have no lightweight fixture (the former needs a full dynamic section with `libc.prx`, the latter a guest image); the trampoline test pins the shared pattern. Fixes: none (new finding, same malformed-input method as #10653). Branch: `fix/linux-patch-unsigned-displacement`, based on `main` `87b810a1d`. Different files from the rest of the queue; no conflicts. ### Tested - `linux_load_pages_tests`: on `main` it aborts under the trap-on-error UBSan build and passes with the change under the same build; it passes unsanitized on both. - `relinker_core` (both changed files) builds clean under the same sanitizer flags. - Full relinker-only `ctest` under the trap-on-error build (Windows 11, MinGW-w64 GCC 15.2.0): failure set identical to `main`; every failure is this machine's Application Control policy refusing to execute freshly built outputs (`WinError 4551`) or its knock-on subprocess timeouts, present before 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: none - [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 08:47:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-28T08:47:51Z.

Review: CHANGES_REQUESTED


The unsigned subtraction removes the signed-overflow UB for the near-boundary fixture, but it does not preserve the rel32 range check for all 64-bit addresses. Unsigned subtraction wraps modulo 2^64 before the cast: for example, target = 0x100 and next = UINT64_MAX produces 0x101, which then passes the signed rel32 check even though the mathematical displacement is far out of range. These addresses are input-derived in the ELF patcher/writer, and the PR already establishes that high-bit virtual addresses are accepted. Please compute the distance without wraparound (compare operands first, bound the unsigned magnitude against INT32_MAX/2^31, then form the signed result) and add a regression that verifies an out-of-range cross-boundary displacement is rejected, alongside the existing in-range case. The current test proves the small displacement at 2^63 but not this wraparound case.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5679961266 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12307#pullrequestreview-5679961266). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-28T08:47:51Z. **Review:** CHANGES_REQUESTED --- The unsigned subtraction removes the signed-overflow UB for the near-boundary fixture, but it does not preserve the rel32 range check for all 64-bit addresses. Unsigned subtraction wraps modulo 2^64 before the cast: for example, `target = 0x100` and `next = UINT64_MAX` produces `0x101`, which then passes the signed rel32 check even though the mathematical displacement is far out of range. These addresses are input-derived in the ELF patcher/writer, and the PR already establishes that high-bit virtual addresses are accepted. Please compute the distance without wraparound (compare operands first, bound the unsigned magnitude against `INT32_MAX`/`2^31`, then form the signed result) and add a regression that verifies an out-of-range cross-boundary displacement is rejected, alongside the existing in-range case. The current test proves the small displacement at 2^63 but not this wraparound case.
rooklz commented 2026-10-28 10:23:02 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-28T10:23:02Z.

Review: COMMENTED


Review at 019aadb45c, merged onto main 3a40945e62, macOS arm64 Apple clang relinker-only build.

What I ran

  • Merge is clean. ctest 378/378.
  • -fsanitize=undefined -fno-sanitize-recover=all: linux_load_pages_tests passes on the head. With core/relinker/elfpatcher/src reverted to main, it reports LinuxElfPatcher.cpp:355:91: signed integer overflow. So the new test catches the UB on a second toolchain (clang/macOS as well as MinGW GCC).

About the open CHANGES_REQUESTED (wraparound)
@MarcZX10's case is real, but this PR does not introduce it. main accepts it too. With target = 0x100, next = UINT64_MAX, both int64(t) - int64(n) and the new int64(t - n) give 257, and no UB is involved there. I tested 20 M pairs, random and clustered around 0 / 2^31 / 2^63 / 2^64. In every one of the 17,075,855 pairs where main's subtraction is defined, the new expression gives the same value and the same accept/reject. It differs from the true mathematical distance in 820,387 pairs, all of them wrap cases that main either accepts the same way or hits UB on. So: no regression, but the check is still not exact.

A helper with no wraparound settles it, and all five call sites can share it:

std::optional<std::int32_t> Rel32(const std::uint64_t target, const std::uint64_t next) {
    if (target >= next) {
        if (target - next > 0x7fffffffull) return std::nullopt;
        return static_cast<std::int32_t>(target - next);
    }
    if (next - target > 0x80000000ull) return std::nullopt;
    return static_cast<std::int32_t>(-static_cast<std::int64_t>(next - target));
}

Compared against __int128 exact differences over the same 20 M-pair generator (UBSan on): 0 mismatches. Boundary cases: 0x7fffffff−0 and 0−0x80000000 accepted, 0x80000000−0, 0−0x80000001 and 0x100−UINT64_MAX rejected, the PR's cross-2^63 fixture accepted (8187).

For the regression: a wrap only makes a small value when the operands are about 2^64 apart, e.g. a site near 0 and a body near UINT64_MAX. I have not checked whether ComputeExtraBlockVaddr can place the extra block there without wrapping first, so I'm not proposing a patcher-level fixture. A direct test of the helper on the boundary pairs above (wrap case included) seems like the cheapest way to pin it.

Non-blocking: Rebased already limits fixed-base images to < 0x800000000000, so this only applies when there is no fixed base. That matches the PR's scope.

AI-assisted: yes. All runs were done locally.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5681106716 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12307#pullrequestreview-5681106716). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-28T10:23:02Z. **Review:** COMMENTED --- Review at 019aadb45c, merged onto `main` 3a40945e62, macOS arm64 Apple clang relinker-only build. **What I ran** - Merge is clean. `ctest` 378/378. - `-fsanitize=undefined -fno-sanitize-recover=all`: `linux_load_pages_tests` passes on the head. With `core/relinker/elfpatcher/src` reverted to `main`, it reports `LinuxElfPatcher.cpp:355:91: signed integer overflow`. So the new test catches the UB on a second toolchain (clang/macOS as well as MinGW GCC). **About the open CHANGES_REQUESTED (wraparound)** @MarcZX10's case is real, but this PR does not introduce it. `main` accepts it too. With `target = 0x100, next = UINT64_MAX`, both `int64(t) - int64(n)` and the new `int64(t - n)` give `257`, and no UB is involved there. I tested 20 M pairs, random and clustered around 0 / 2^31 / 2^63 / 2^64. In every one of the 17,075,855 pairs where `main`'s subtraction is defined, the new expression gives the same value and the same accept/reject. It differs from the true mathematical distance in 820,387 pairs, all of them wrap cases that `main` either accepts the same way or hits UB on. So: no regression, but the check is still not exact. A helper with no wraparound settles it, and all five call sites can share it: ```cpp std::optional<std::int32_t> Rel32(const std::uint64_t target, const std::uint64_t next) { if (target >= next) { if (target - next > 0x7fffffffull) return std::nullopt; return static_cast<std::int32_t>(target - next); } if (next - target > 0x80000000ull) return std::nullopt; return static_cast<std::int32_t>(-static_cast<std::int64_t>(next - target)); } ``` Compared against `__int128` exact differences over the same 20 M-pair generator (UBSan on): **0 mismatches**. Boundary cases: `0x7fffffff−0` and `0−0x80000000` accepted, `0x80000000−0`, `0−0x80000001` and `0x100−UINT64_MAX` rejected, the PR's cross-2^63 fixture accepted (8187). For the regression: a wrap only makes a small value when the operands are about 2^64 apart, e.g. a site near 0 and a body near `UINT64_MAX`. I have not checked whether `ComputeExtraBlockVaddr` can place the extra block there without wrapping first, so I'm not proposing a patcher-level fixture. A direct test of the helper on the boundary pairs above (wrap case included) seems like the cheapest way to pin it. Non-blocking: `Rebased` already limits fixed-base images to `< 0x800000000000`, so this only applies when there is no fixed base. That matches the PR's scope. AI-assisted: yes. All runs were done locally.
MarcZX10 commented 2026-10-29 06:07:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T06:07:32Z.

Review: APPROVED


Re-checked — approved

What I checked

  • Reviewed exact head d9ab85865a09be22241ae6631e0d1fa8e800b273 against fetched main 2960e9a6e7.
  • SignedDistance rejects cross-half distances whose magnitude is at least 2^63, so wrapped unsigned differences cannot pass the rel32 check. The tests cover both the previously valid displacement across INT64_MAX and the malformed >2^63 case. The follow-up also avoids negating INT64_MIN.
  • Current-main merge preview is clean and git diff --check is clean. Exact-head CI merged the PR into main and passed the full relinker CTest job on Ubuntu, Windows, macOS arm64 and x86_64, plus the ASan job; conventions and eligibility pass.

Test evidence

The author reports linux_load_pages_tests passing in Release and trap-on-error UBSan on the immediately preceding commit cb7ed5672e. The exact-head CI relinker CTest and ASan jobs pass on d9ab85865a. I did not run the tests locally.

The wraparound and signed-boundary cases are addressed, with current-main integration tested. No blocking issue remains.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5693548217 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12307#pullrequestreview-5693548217). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-29T06:07:32Z. **Review:** APPROVED --- # Re-checked — approved ## What I checked - Reviewed exact head `d9ab85865a09be22241ae6631e0d1fa8e800b273` against fetched `main` `2960e9a6e7`. - `SignedDistance` rejects cross-half distances whose magnitude is at least 2^63, so wrapped unsigned differences cannot pass the rel32 check. The tests cover both the previously valid displacement across `INT64_MAX` and the malformed >2^63 case. The follow-up also avoids negating `INT64_MIN`. - Current-main merge preview is clean and `git diff --check` is clean. Exact-head CI merged the PR into `main` and passed the full relinker CTest job on Ubuntu, Windows, macOS arm64 and x86_64, plus the ASan job; conventions and eligibility pass. ## Test evidence The author reports `linux_load_pages_tests` passing in Release and trap-on-error UBSan on the immediately preceding commit `cb7ed5672e`. The exact-head CI relinker CTest and ASan jobs pass on `d9ab85865a`. I did not run the tests locally. The wraparound and signed-boundary cases are addressed, with current-main integration tested. No blocking issue remains.
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!12307
No description provided.