loader: resolve jump tables and tail calls in the guest patcher #1281
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1281
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1281"
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?
@NeySlim on GitHub · 2026-10-09 07:24 UTC · original
NeySlim:fix/patcher-jump-tables→main· +1418 −155 · 4 files · 4 commits · openProblem
With
--amd-cpu, God of War Ragnarök (PPSA08332, 05.005) logs at startup:The 522 trapped sites get the reserved VEX.vvvv mark and go through the SIGILL handler on every execution: 21,000 to 27,000 SIGILL per second from the opening cutscene on, from about 125 distinct sites.
All 522 sites are four-byte
vrsqrtps xmm, xmmin functions with an indirect jump the patcher cannot resolve, so it may not borrow neighbouring bytes for the five-byte jump to a trampoline. 284 of the 291 unresolved jumps in these functions are switch dispatches. The PS5 toolchain puts jump tables in read-only data, a separate segment, andResolveBoundedJumpTableonly reads tables inside the executable segment being patched. Most dispatches also fall outside its single pattern: the index is zero-extended after the bounds check, other instructions sit between the load and the add, the table base is set before a loop, a loop jumps again through the same register, or the index is bounded by a mask or set from constants:Four are tail calls after the epilogue (
pop rbp ; jmp rax,pop rbp ; jmp [rax+0x48]).The cases of an unresolved table are never decoded either, so 129 VRSQRTPS in them were not found at all and ran with the host approximation.
Change
Jump tables are read from the module's
PT_LOADsegments that are readable and not writable (registered by the loader withRegisterGuestInstructionPatchReadOnlyData), not only from the executable segment. A writable segment, a RELRO segment (still written by relocations) or a segment without permissions is never read.A dispatch is matched from the definitions of the jump register that reach the
jmp: each must be theadd target, tableofmovsxd target, dword [table + index*4], with unrelated instructions allowed in between. A loop that jumps again with the same computed target resolves to the same cases.The index bound comes from a
cmp+ja/jaeon the straight path before the load, through zero-extending copies (movzx r32, r8/r16,mov r32, r32, also when the copy precedes the compare), or from every definition reaching it: constants,setcc,and,shr,xor r, rand copies of bounded registers. A compare narrower than the index (cmp al, 3forrax) counts only when the index definition clears the bits above it (movzxfrom a byte,and eax, 0xf).The table base must be the same RIP-relative
leaon every path to the load (reaching definitions over the decoded control flow).A call clobbers every caller-saved register, in the reaching definitions and in each backward scan of the dispatch path (bound, base, load and target), so
cmp ecx, 3 ; ja ; call f ; ...gives no bound forecx.The target and table registers of the
addmust differ:add rax, raxdoubles the entry instead of adding the base.Nothing may enter the straight path between the bound and the dispatch.
An unresolved indirect jump is a tail call, and leaves the function, only when both hold:
mov rbp, rspsoleave,mov rsp, rbpandlea rsp, [rbp + disp]keep a known depth);&&resumein caller memory and jumps back there on a later call. The function loses its tail calls when the module holds the address of an instruction strictly inside it, or when it takes its own address (its entry included, as a base for label offsets). Taken addresses are the targets of RIP-relativeleain the code segment, decoded linearly from each function start, and ofR_X86_64_RELATIVEandR_X86_64_64relocations, which the loader registers withRegisterGuestInstructionPatchCodeAddresses. The loader now parses the dynamic info before patching, so relocations are known then.Anything else, for example the sum of an unmatched switch or an indexed table of absolute addresses after the epilogue, keeps the function marked as having an unresolved indirect jump, so no neighbouring bytes are borrowed and no short relay is used in it.
Once every edge is known, each match is checked again. If one no longer holds, or the decoded instructions overlap, the function falls back to direct control flow only, as before.
Fix: the red-zone liveness analysis (Windows) now follows jump-table edges. Before, a resolved dispatch had no successors in it, so a red zone read only in a case was considered dead before the dispatch and a faultable instruction there was left unprotected.
Test
Three new tests in
virtual_memory_allocation_tests(Linux and Windows, also under--rsqrt-only).ReciprocalSquareRootBesideJumpTables: the table sits in read-only data of the module, outside the patched segment.jmp [rax]). Both the straight-line site and the one in case 0 must be patched natively, run without SIGILL with exact results, and reach the right case for every selector.leabases, a branch entering the path below the guard, a call clobbering the index, a call clobbering the base, a table entry outside the function,add rax, rax(target register is the base), a table in writable memory, an unmatched dispatch after the epilogue, an absolute table after the epilogue, an indirect jump with the frame still in place, a second dispatch whose entry enters the first one's path (final re-check fallback) and an entry inside an instruction (overlap fallback).ReciprocalSquareRootBesideAddressTakenLabels: a resumable function saves a label placed right after a four-bytevrsqrtps, and a later call jumps there through caller memory (mov rax, [rdi] ; jmp raxorjmp [rdi]). The label address comes from aleain the function, an offset from its entry, aleain another function or a registered relocation: the site must stay trapped, and the second call must continue after the label. With no label address taken, the same jump stays a tail call and the site is patched natively. Each source was checked by removing its handling: the corresponding case fails.RedZoneLivenessAcrossJumpTables: runs the red-zone patcher (platform-independent code, so it runs on Linux too) on a leaf function that writes the red zone, dispatches through a table and reads it back only in case 0. The table load must be protected.Each rejection added with this revision and the red-zone fix was checked by reverting it: the corresponding case fails. The first revision of the jump-table test fails on main (trapped instead of native).
Validation
Linux, Ryzen AI Max+ 395 (Zen 5), Radeon 8060S, Mesa RADV 26.2.3.
leaor a relocation; one takes its own entry address (it passes itself as a callback) and keeps its jump unresolved, with no effect on the counts above. The pass takes about 1.55 s of CPU time instead of 1.15 s on main (fastest of 6 runs); finding the taken addresses costs about 0.15 s of it.perf stat -e signal:signal_deliver: the log now readsVRSQRTPS: native=4013, trapped=0; SIGILL go from 24,500 per second (the main game thread and the 11 task threads) to none, and all signals from 53,000 to 25,000 per second (the rest are write-tracking faults). A bare SIGILL round trip costs about 0.6 us on this CPU before any emulation, so this saves a few percent of one core. The frame rate does not change beyond run-to-run noise (12.3 fps before, 12.1 after, over the first 3 minutes of gameplay): the GPU command thread limits this game today. Rendering is unchanged.virtual_memory_allocation_tests: all pass, as on main.Not tested on Windows or macOS. The analysis is platform-independent; on Windows the red-zone patcher now runs its precise liveness analysis on more functions, and that analysis now follows jump-table edges.
Related: #833 also reads jump tables outside the code segment, in the red-zone patcher.
AI use
I used Claude Code (AI agent) to find why these sites were trapped, write the change and the test, and run the measurements above on my machine. I reviewed the diff and the results before opening this PR.
@coderabbitai[bot] on GitHub · 2026-10-09 07:29 UTC · original · edited 2026-10-12 16:02 UTC
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
92e97a10-6f79-43f7-b376-dab1f36a4ff4📥 Commits
Reviewing files that changed from the base of the PR and between 1feb4c5b522225fd219a14d19dc0a8e24706d786 and 97aca38070a47801b1b01c7fe04611b17e8aaa5c.
📒 Files selected for processing (4)
src/loader/guestInstructionPatcher.cppsrc/loader/guestInstructionPatcher.hsrc/loader/runtimeLinker.cpptests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review.
📝 Walkthrough
Walkthrough
The patcher analyzes control flow and register definitions to resolve eligible bounded jump tables. It adds resolved targets to decoding and red-zone liveness analysis, and classifies indirect branches using stack depth and target provenance. The runtime linker registers qualifying read-only segments and relocation-derived code addresses. Generated-code tests cover patching behavior for jump tables, address-taken labels, and red-zone liveness.
Suggested reviewers:
nmzikPriority: ➖ Normal
Change: Bug fix
Merge Risk: ⚪ Minimal · up to
97acaThis change resolves more jump tables and tail calls so that additional reciprocal-square-root sites can be patched natively. No outstanding defects were identified at the current head, and the earlier concern about tail-call classification has been addressed. Windows and macOS runs were not reported.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@NeySlim on GitHub · 2026-10-09 09:47 UTC · original
Updated after a review of the matching rules (1feb4c5b):
pop rbp/leaverule also accepted an unmatched dispatch after the epilogue.add rax, rax(target register equals the base) is rejected.PT_LOADsegments registered by the loader.GoW counts are unchanged (VRSQRTPS native 4013, trapped 0). Tail calls resolved go from 358 to 584 and functions with an unresolved indirect jump from 286 to 65. The body has the details.
@ -509,0 +1032,4 @@default: return false;}});}@coderabbitai[bot] on GitHub · 2026-10-09 09:52 UTC · original · edited 2026-10-09 10:07 UTC
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Indirect jumps through caller-owned memory are classified as tail calls even when they can target internal labels.
IsIndirectTailJumptreats a jump as leaving the function when the stack depth is 0 and the target comes from the caller or from a pointer slot. The comment on lines 985-986 says "A caller cannot hold an address inside it." That premise fails when an earlier call of the same function stored an internal address in memory that the caller owns.Example: a protothread or labels-as-values state machine.
lea rcx, [rip+resume]; mov [rdi+8], rcx.jmp [rdi+8], ormov rax, [rdi+8]; jmp rax, at depth 0.The code accepts that jump at three places:
IsPointerSlot(..., check_base=true)getsentry_reached = truewith no definitions forrdi, soall_ofover the empty set is true.HoldsExternalAddressaccepts theMOVfrom that slot in the same way.IsPointerSlot(..., false)accepts any base except RSP and RBP. Its doc comment says the base must be RIP, an argument, or such a pointer.The same gap applies to a RIP-relative slot in writable data that the function itself fills with
lea. It also applies to a constant-index read from a static&&labelarray.Consequence:
function.has_indirect_branchbecomes false, soRelocateGuestInstructionsmay borrow neighboring bytes. Theresumelabel is not inbranch_targets, because aleadoes not record its operand. A relocation span can therefore cover that label. The next resume then jumps into the overwrittenjmp/nopbytes, which corrupts guest control flow or crashes it. The PR description says tail-call resolution grew from 358 to 584, so the new rules accept more of these jumps than before.Fix: Before accepting a tail call, prove that the function never computes an address inside itself.
lea, or amov r64, imm, whose result lies in[function_start, function_end)and is not a resolved jump-table base.read_only_dataand its stored value lies outside the function.Sketch of the guard
✅ Addressed in commit 737087e
@coderabbitai[bot] on GitHub · 2026-10-09 09:52 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
a0eb1f1b-ca0d-4904-ade1-c2b313b6c6b6📥 Commits
Reviewing files that changed from the base of the PR and between a7719317a8b7ac779f329f855cc132f636b038e3 and 1feb4c5b522225fd219a14d19dc0a8e24706d786.
📒 Files selected for processing (4)
src/loader/guestInstructionPatcher.cppsrc/loader/guestInstructionPatcher.hsrc/loader/runtimeLinker.cpptests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.
@ -509,0 +1032,4 @@default: return false;}});}@NeySlim on GitHub · 2026-10-09 10:07 UTC · original
Right: a value from the caller or a pointer slot can still be a label of the function once its address is stored somewhere, so the premise did not hold.
Fixed in 737087e3 with an address-taken check. An unresolved indirect jump is no longer a tail call when the module holds the address of an instruction strictly inside the function, or when the function takes its own address (entry included, as a base for label offsets). Taken addresses are the targets of RIP-relative
leain the code segment (linear decode from each function start, soleain other functions count too) and ofR_X86_64_RELATIVE/R_X86_64_64relocations, registered by the loader throughRegisterGuestInstructionPatchCodeAddresses; the dynamic info is now parsed before patching. TheIsPointerSlotcomment now matches the nested case.Test:
ReciprocalSquareRootBesideAddressTakenLabels. A resumable function stores a label placed right after a four-bytevrsqrtpsand a later call jumps there (mov rax, [rdi] ; jmp raxorjmp [rdi]), with the address from aleain the function, an offset from its entry, aleain another function or a relocation. The site must stay trapped and the resumed call must continue after the label; with no address taken it stays a native tail call. Removing each source fails its case.GoW: 584 to 583 tail calls (one function takes its own entry as a callback), VRSQRTPS still 4013 native, 0 trapped.
@ -509,0 +1032,4 @@default: return false;}});}@coderabbitai[bot] on GitHub · 2026-10-09 10:08 UTC · original
@NeySlim, thanks for the fix and the explanation. The suppliedDecodeFunctionchecks module-held internal addresses and addresses taken by the function before accepting an unresolved indirect jump as a tail call. This addresses the unsafe neighboring-byte relocation described in the finding.The reported regression cases cover both jump forms and the address sources. The no-address-taken case also checks that native tail-call patching remains available. I have not independently run the tests.
✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@NeySlim on GitHub · 2026-10-09 12:07 UTC · original
Follow-up from another review pass (97aca380): a
cmpguard narrower than the table index was accepted as a full bound.cmp al, 3 ; jabounds only the low byte, so withmov eax, edibefore it the index could still be any 32-bit value. A narrow guard now counts only when the index definition clears the bits above it (movzxfrom a byte, including from memory, or a mask such asand esi, 0xf), which is what the compiler emits in GoW.Tests: one rejected case (byte compare of a 32-bit index, fails without the fix) and one accepted case (byte compare of a masked index). GoW offline pass unchanged: VRSQRTPS native 4013, trapped 0; 4780 tables, 66 functions with an unresolved indirect jump; red-zone counts unchanged.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.