fix(libkernel): lay out user contexts as the console's getcontext writes them #15794

Merged
root-over merged 7 commits from upstream-pr/15794 into main 2026-11-07 21:25:45 +00:00
root-over commented 2026-11-04 15:56:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by root-over on 2026-11-04T15:56:36Z.


What

Two catalog Xbox 360 ports by the same author, Naruto: Rise of a Ninja (PPSA99680) and Forza Horizon (PPSA99690), crash about 2 s after start on main with a jump to 0xa3/0xad.

Both build their fibers without makecontext (port patch, Fiber::Create):

  1. They call getcontext into a 2 KiB buffer.
  2. They store the entry stack at offset 0xf8, 0 at 0x88 and the entry function at 0xe0.
  3. They switch with swapcontext.

The same patch records what firmware 9.00 does: "getcontext reports mc_len=1152 and writes 1216 bytes".

That is the layout AnyPS5's exception path already uses (GuestUcontext in Exception.cpp): mcontext at 0x40, mc_rip at 0xe0, mc_rsp at 0xf8, sizeof(GuestMcontext) 0x480 (1152), uc_link at 0x4c0 (1216). getcontext, setcontext, swapcontext and makecontext instead used FreeBSD 11's layout: mcontext at 0x10, 800 bytes, mc_rip at 0xb0. So swapcontext resumed the fiber at getcontext's old return address, on a stack frame that had already returned. That frame's saved r13 had since been overwritten by a return address, and the next call *%r13 crashed. I traced it with gdb, single-stepping from the last pthread_mutex_unlock to the crash: getcontext at 0x4abf7d, swapcontext from 0x12a5e9a, then a second return at 0x4abf82.

Four commits:

  1. fix: UserMcontext and UserUcontext take the console layout:

    • lbrfrom, lbrto, aux1 and aux2 after mc_ownedfp;
    • an 832-byte mc_fpstate at mcontext + 0x100, still holding the 512-byte FXSAVE image at its start;
    • fsbase, gsbase, spare[6];
    • uc_link at 0x4c0.

    guest_user_context checks the new fields in place of mc_xfpustate.

  2. refactor: Exception.cpp uses UserMcontext/UserUcontext through aliases instead of its own copy of the same layout. No behaviour change.

  3. test: guest_user_context sets up a fiber the way the ports do, with raw offsets 0xf8/0x88/0xe0, and switches into it and back three times. It checks mc_len 1152 at 0x108 and that nothing is written from 0x4c0 on.

  4. docs: the debt entry gives the layout and its source, and keeps uc_stack at 0x4c8 (FreeBSD's order after uc_link) as not measured.

The previous layout came from the sizes PPSA99039 (EVO Player)'s OpenSSL ASYNC passes. EVO Player makes no getcontext/makecontext/swapcontext/setcontext call in its first 45 s (gdb breakpoints on all four), and still runs.

Tested

Ubuntu, kernel 7.0, GCC 15.2.0, Release.

Title main this PR
PPSA99680 Naruto: Rise of a Ninja SIGSEGV at 0xa3 after 2 s logs native fiber round-trip check: passed, then looks for /app0/game/naruto.module and exits 0 (no game data here)
PPSA99690 Forza Horizon SIGSEGV at 0xad after 2 s logs native fiber round-trip check: passed, then exits 0 the same way
PPSA99039 EVO Player alive at 30 s alive at 30 s
  • Context and exception tests: 13 tests, passing on main and on this PR: guest_user_context, guest_user_context_exit, guest_kernel_sys, guest_kernel_sys_swapcontext, guest_exception_handler, guest_raise_exception, guest_signals, guest_signal_handler_mask, guest_sce_v2_exceptions, fiber_contextless, register_context_capture, register_context_restore, register_context_threads.
  • Each commit on its own: builds, and these tests pass.
  • tools/check_conventions.py: passes.
  • Windows: not built here. The changed Windows code in Exception.cpp uses the same field names, and FltSave (512 bytes) still fits mc_fpstate, which the existing static_assert checks.
  • tools/pr_overlap.py: #12682, #12688, #12700 and #12965 edit GuestUserContext.cpp lines 302-303 and the same debt entry. They store metadata in mc_spare, which the new layout keeps (6 words instead of 4), so whichever lands second keeps both. #4630, #5021, #8592, #12642 and #13486 touch other parts of Exception.cpp.

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); silent stubs are listed under Silent stubs in their library's technical debt file
  • 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
  • Unblocks: PPSA99680 and PPSA99690, no Game bring-up discussion yet (both get past their fiber self-check instead of crashing at start)
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5157361539 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15794). Originally posted by [root-over](https://github.com/root-over) on 2026-11-04T15:56:36Z. --- ### What Two catalog Xbox 360 ports by the same author, **Naruto: Rise of a Ninja (PPSA99680)** and **Forza Horizon (PPSA99690)**, crash about 2 s after start on `main` with a jump to `0xa3`/`0xad`. Both build their fibers without `makecontext` ([port patch](https://github.com/mshivam019/naruto-ps5/blob/main/ps5/patches/rexglue-ps5.patch), `Fiber::Create`): 1. They call `getcontext` into a 2 KiB buffer. 2. They store the entry stack at offset `0xf8`, 0 at `0x88` and the entry function at `0xe0`. 3. They switch with `swapcontext`. The same patch records what firmware 9.00 does: "getcontext reports mc_len=1152 and writes 1216 bytes". That is the layout AnyPS5's exception path already uses (`GuestUcontext` in `Exception.cpp`): `mcontext` at 0x40, `mc_rip` at 0xe0, `mc_rsp` at 0xf8, `sizeof(GuestMcontext)` 0x480 (1152), `uc_link` at 0x4c0 (1216). `getcontext`, `setcontext`, `swapcontext` and `makecontext` instead used FreeBSD 11's layout: `mcontext` at 0x10, 800 bytes, `mc_rip` at 0xb0. So `swapcontext` resumed the fiber at `getcontext`'s old return address, on a stack frame that had already returned. That frame's saved `r13` had since been overwritten by a return address, and the next `call *%r13` crashed. I traced it with gdb, single-stepping from the last `pthread_mutex_unlock` to the crash: `getcontext` at `0x4abf7d`, `swapcontext` from `0x12a5e9a`, then a second return at `0x4abf82`. Four commits: 1. `fix`: `UserMcontext` and `UserUcontext` take the console layout: - `lbrfrom`, `lbrto`, `aux1` and `aux2` after `mc_ownedfp`; - an 832-byte `mc_fpstate` at mcontext + 0x100, still holding the 512-byte FXSAVE image at its start; - `fsbase`, `gsbase`, `spare[6]`; - `uc_link` at 0x4c0. `guest_user_context` checks the new fields in place of `mc_xfpustate`. 2. `refactor`: `Exception.cpp` uses `UserMcontext`/`UserUcontext` through aliases instead of its own copy of the same layout. No behaviour change. 3. `test`: `guest_user_context` sets up a fiber the way the ports do, with raw offsets 0xf8/0x88/0xe0, and switches into it and back three times. It checks `mc_len` 1152 at 0x108 and that nothing is written from 0x4c0 on. 4. `docs`: the debt entry gives the layout and its source, and keeps `uc_stack` at 0x4c8 (FreeBSD's order after `uc_link`) as not measured. The previous layout came from the sizes PPSA99039 (EVO Player)'s OpenSSL `ASYNC` passes. EVO Player makes no `getcontext`/`makecontext`/`swapcontext`/`setcontext` call in its first 45 s (gdb breakpoints on all four), and still runs. ### Tested Ubuntu, kernel 7.0, GCC 15.2.0, Release. | Title | `main` | this PR | |---|---|---| | PPSA99680 Naruto: Rise of a Ninja | SIGSEGV at `0xa3` after 2 s | logs `native fiber round-trip check: passed`, then looks for `/app0/game/naruto.module` and exits 0 (no game data here) | | PPSA99690 Forza Horizon | SIGSEGV at `0xad` after 2 s | logs `native fiber round-trip check: passed`, then exits 0 the same way | | PPSA99039 EVO Player | alive at 30 s | alive at 30 s | - **Context and exception tests:** 13 tests, passing on `main` and on this PR: `guest_user_context`, `guest_user_context_exit`, `guest_kernel_sys`, `guest_kernel_sys_swapcontext`, `guest_exception_handler`, `guest_raise_exception`, `guest_signals`, `guest_signal_handler_mask`, `guest_sce_v2_exceptions`, `fiber_contextless`, `register_context_capture`, `register_context_restore`, `register_context_threads`. - **Each commit on its own:** builds, and these tests pass. - **`tools/check_conventions.py`:** passes. - **Windows:** not built here. The changed Windows code in `Exception.cpp` uses the same field names, and `FltSave` (512 bytes) still fits `mc_fpstate`, which the existing `static_assert` checks. - **`tools/pr_overlap.py`:** #12682, #12688, #12700 and #12965 edit `GuestUserContext.cpp` lines 302-303 and the same debt entry. They store metadata in `mc_spare`, which the new layout keeps (6 words instead of 4), so whichever lands second keeps both. #4630, #5021, #8592, #12642 and #13486 touch other parts of `Exception.cpp`. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [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`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [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 - [x] Unblocks: PPSA99680 and PPSA99690, no Game bring-up discussion yet (both get past their fiber self-check instead of crashing at start) - [x] GPUs tested: n/a - [x] AI-assisted: yes
BunnyFl commented 2026-11-05 15:13:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by BunnyFl on 2026-11-05T15:13:36Z.

Review: APPROVED


@root-over looks right, and firmware 13.42's own makecontext agrees with the new layout.

Firmware 13.42

system/common/lib/libSceLibcInternal.sprx (SHA-256 a01795ab49df639dd40abd6194956ada062244826824ce486c9acab227bf5285), makecontext at 0x8de70, read to its return (disassembly only, not measured on a console):

8dee7: cmpq $0x480,0x108(%rdi)      ; mc_len must be 1152, at 0x40 + 0xc8
8def4: cmp  $0x6,%edx               ; at most 6 arguments
8def9: mov  0x4c8(%rdi),%rax        ; uc_stack.ss_sp
8df05: mov  0x4d0(%rdi),%rcx        ; uc_stack.ss_size
8df0c: cmp  $0x7ff,%rcx             ; must be above 0x7ff
8df15: movq $0x0,0x108(%rdi)        ; otherwise mc_len is cleared
8dfee: mov  %rdi,0x48(%rdi)         ; mc_rdi = ucp
8dffa: movq $0x0,0x88(%rdi)         ; mc_rbp = 0
8e00c: mov  %r14,0xf8(%rdi)         ; mc_rsp
8e013: mov  %rax,0xe0(%rdi)         ; mc_rip

system/common/lib/libkernel.sprx (SHA-256 4be40bf838a46e1ff83a1809960672526139b09dda6c4a6592cfeb485d29f243), swapcontext at 0xcad0, copies the context into a 0x500-byte stack buffer before the switch:

caef: mov $0x500,%edx

So mc_len 1152 at 0x108, mc_rip at 0xe0, mc_rsp at 0xf8 and sizeof(ucontext_t) 0x500 all match this PR's static_asserts. It also settles the one field the debt entry leaves open: uc_stack.ss_sp is at 0x4c8 and ss_size at 0x4d0 on 13.42, as you have them. You could cite that instead of "not measured" (non-blocking).

What I ran

Head 90c30d52be merged onto main 78e4248fea (clean merge), Windows 11, WinLibs GCC 15.2.0, Release, BUILD_TESTING=ON, test executables rebuilt. Your description says Windows wasn't built; this is a Windows run:

  • 10 tests: guest_user_context, guest_user_context_exit, guest_kernel_sys, guest_kernel_sys_swapcontext, guest_exception_handler, guest_raise_exception, guest_signals, guest_signal_handler_mask, guest_sce_v2_exceptions and fiber_contextless pass. register_context_capture, _restore and _threads aren't registered in this Windows build.
  • Negative control: main's UserContext.hpp and Exception.cpp with your GuestUserContext.cpp (its mc_xfpustate check put back so it compiles, CheckConsoleOffsets kept): guest_user_context aborts (0xc0000409). My log doesn't show which check stopped it.
  • check_conventions.py passes. pr_overlap.py --branch finds only shared lines, no shared exports, with #12682, #12688, #12700 and #12965, the four you named.

Approving.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5787241356 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15794#pullrequestreview-5787241356). Originally posted by [BunnyFl](https://github.com/BunnyFl) on 2026-11-05T15:13:36Z. **Review:** APPROVED --- @root-over looks right, and firmware 13.42's own `makecontext` agrees with the new layout. ## Firmware 13.42 `system/common/lib/libSceLibcInternal.sprx` (SHA-256 `a01795ab49df639dd40abd6194956ada062244826824ce486c9acab227bf5285`), `makecontext` at `0x8de70`, read to its return (disassembly only, not measured on a console): ``` 8dee7: cmpq $0x480,0x108(%rdi) ; mc_len must be 1152, at 0x40 + 0xc8 8def4: cmp $0x6,%edx ; at most 6 arguments 8def9: mov 0x4c8(%rdi),%rax ; uc_stack.ss_sp 8df05: mov 0x4d0(%rdi),%rcx ; uc_stack.ss_size 8df0c: cmp $0x7ff,%rcx ; must be above 0x7ff 8df15: movq $0x0,0x108(%rdi) ; otherwise mc_len is cleared 8dfee: mov %rdi,0x48(%rdi) ; mc_rdi = ucp 8dffa: movq $0x0,0x88(%rdi) ; mc_rbp = 0 8e00c: mov %r14,0xf8(%rdi) ; mc_rsp 8e013: mov %rax,0xe0(%rdi) ; mc_rip ``` `system/common/lib/libkernel.sprx` (SHA-256 `4be40bf838a46e1ff83a1809960672526139b09dda6c4a6592cfeb485d29f243`), `swapcontext` at `0xcad0`, copies the context into a `0x500`-byte stack buffer before the switch: ``` caef: mov $0x500,%edx ``` So `mc_len` 1152 at 0x108, `mc_rip` at 0xe0, `mc_rsp` at 0xf8 and `sizeof(ucontext_t)` 0x500 all match this PR's `static_assert`s. It also settles the one field the debt entry leaves open: `uc_stack.ss_sp` is at 0x4c8 and `ss_size` at 0x4d0 on 13.42, as you have them. You could cite that instead of "not measured" (non-blocking). ## What I ran Head `90c30d52be` merged onto `main` `78e4248fea` (clean merge), Windows 11, WinLibs GCC 15.2.0, Release, `BUILD_TESTING=ON`, test executables rebuilt. Your description says Windows wasn't built; this is a Windows run: - 10 tests: `guest_user_context`, `guest_user_context_exit`, `guest_kernel_sys`, `guest_kernel_sys_swapcontext`, `guest_exception_handler`, `guest_raise_exception`, `guest_signals`, `guest_signal_handler_mask`, `guest_sce_v2_exceptions` and `fiber_contextless` pass. `register_context_capture`, `_restore` and `_threads` aren't registered in this Windows build. - Negative control: `main`'s `UserContext.hpp` and `Exception.cpp` with your `GuestUserContext.cpp` (its `mc_xfpustate` check put back so it compiles, `CheckConsoleOffsets` kept): `guest_user_context` aborts (`0xc0000409`). My log doesn't show which check stopped it. - `check_conventions.py` passes. `pr_overlap.py --branch` finds only shared lines, no shared exports, with #12682, #12688, #12700 and #12965, the four you named. Approving. AI-assisted: yes (Claude Code)
gabichuuuuu commented 2026-11-07 07:27:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by gabichuuuuu on 2026-11-07T07:27:33Z.

Review: COMMENTED


A Windows check, and two notes on the debt entries.

On Windows 11 x64 (WinLibs GCC 15.2.0 r7 UCRT, Release, full build) I merged head 90c30d52 onto main c1e920e7 (clean merge) and ran ctest -R '^(guest_main_stack|guest_user_context|guest_.*exception|guest_.*unwind|guest_.*context)'. All 171 tests pass on main and with this PR, guest_user_context and guest_user_context_exit included.

In docs/dev/debt/libkernel.md:

  • The rewritten ksem entry drops its last clause, ksem_getvalue rejects an unwritable value pointer with EFAULT (14) via checked guest copy, as FreeBSD's sys_ksem_getvalue does through copyout. main still has it (L230), and it has nothing to do with this change.
  • The new entry gives FreeBSD's layout as mcontext at 0x10, which is right, since uc_sigmask is 16 bytes. The sceKernelRaiseException entry, which this PR does not touch, still says the handler's ucontext uses "FreeBSD's amd64 layout (16-byte sigmask, mcontext at 0x40, mc_rsp at 0xf8)". After this change, that is the console layout that getcontext shares, not FreeBSD's.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5810773250 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15794#pullrequestreview-5810773250). Originally posted by [gabichuuuuu](https://github.com/gabichuuuuu) on 2026-11-07T07:27:33Z. **Review:** COMMENTED --- A Windows check, and two notes on the debt entries. On Windows 11 x64 (WinLibs GCC 15.2.0 r7 UCRT, Release, full build) I merged head `90c30d52` onto `main` `c1e920e7` (clean merge) and ran `ctest -R '^(guest_main_stack|guest_user_context|guest_.*exception|guest_.*unwind|guest_.*context)'`. All 171 tests pass on `main` and with this PR, `guest_user_context` and `guest_user_context_exit` included. In `docs/dev/debt/libkernel.md`: - The rewritten ksem entry drops its last clause, `ksem_getvalue rejects an unwritable value pointer with EFAULT (14) via checked guest copy, as FreeBSD's sys_ksem_getvalue does through copyout`. `main` still has it (L230), and it has nothing to do with this change. - The new entry gives FreeBSD's layout as `mcontext` at 0x10, which is right, since `uc_sigmask` is 16 bytes. The `sceKernelRaiseException` entry, which this PR does not touch, still says the handler's `ucontext` uses "FreeBSD's amd64 layout (16-byte sigmask, `mcontext` at 0x40, `mc_rsp` at 0xf8)". After this change, that is the console layout that getcontext shares, not FreeBSD's. AI-assisted: yes.
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!15794
No description provided.