fix(elfpatcher): take rel32 displacements as unsigned differences #12307
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/12307"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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_tcasts:LinuxElfPatcher::_appendTrampoline(site.AddressvsbodyVaddr),TracePrologue(targetvsvaddr + code.size() + 4),stubDisplacementlambda and the finaliser distance inLinuxGuestModuleWriter(target/image.Init/image.Finivs the stub being emitted)._programHeaderLayoutBuilder->ComputeExtraBlockVaddranchors 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 (ande_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 withIllegal instructionunder-fsanitize=undefined -fsanitize-undefined-trap-on-erroronmain.The differences are now taken in unsigned arithmetic and cast to
std::int64_tonce — the shapeBuildEntryStubalready 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 wheremainaborted under sanitizers; unsanitized the wrap is exact, so output bytes are unchanged onmainfor 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 caseTrampolineDisplacementAcrossInt64MaxinLinuxLoadPageTests.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_MAXwraps to0x101). The five sites now take a sharedSignedDistance(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 exceedsint64; the patcher throws instead of writing the wrapped value. The newTrampolineDisplacementBeyondInt64Rangetest 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.TracePrologueand the guest module writer share the fixed idiom but have no lightweight fixture (the former needs a full dynamic section withlibc.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 onmain87b810a1d. Different files from the rest of the queue; no conflicts.Tested
linux_load_pages_tests: onmainit 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.ctestunder the trap-on-error build (Windows 11, MinGW-w64 GCC 15.2.0): failure set identical tomain; 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/mainpasses.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); no silent stubs added.mdfiles or images added to the repository (attach them to this PR)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.
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 = 0x100andnext = UINT64_MAXproduces0x101, 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 againstINT32_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.Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-28T10:23:02Z.
Review: COMMENTED
Review at 019aadb45c, merged onto
main3a40945e62, macOS arm64 Apple clang relinker-only build.What I ran
ctest378/378.-fsanitize=undefined -fno-sanitize-recover=all:linux_load_pages_testspasses on the head. Withcore/relinker/elfpatcher/srcreverted tomain, it reportsLinuxElfPatcher.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.
mainaccepts it too. Withtarget = 0x100, next = UINT64_MAX, bothint64(t) - int64(n)and the newint64(t - n)give257, 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 wheremain'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 thatmaineither 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:
Compared against
__int128exact differences over the same 20 M-pair generator (UBSan on): 0 mismatches. Boundary cases:0x7fffffff−0and0−0x80000000accepted,0x80000000−0,0−0x80000001and0x100−UINT64_MAXrejected, 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 whetherComputeExtraBlockVaddrcan 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:
Rebasedalready 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.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T06:07:32Z.
Review: APPROVED
Re-checked — approved
What I checked
d9ab85865a09be22241ae6631e0d1fa8e800b273against fetchedmain2960e9a6e7.SignedDistancerejects 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 acrossINT64_MAXand the malformed >2^63 case. The follow-up also avoids negatingINT64_MIN.git diff --checkis clean. Exact-head CI merged the PR intomainand 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_testspassing in Release and trap-on-error UBSan on the immediately preceding commitcb7ed5672e. The exact-head CI relinker CTest and ASan jobs pass ond9ab85865a. I did not run the tests locally.The wraparound and signed-boundary cases are addressed, with current-main integration tested. No blocking issue remains.