feat(libkernel): implement getcontext, setcontext and makecontext #3421

Merged
DariusHQ merged 1 commit from upstream-pr/3421 into main 2026-10-11 10:21:47 +00:00
DariusHQ commented 2026-10-11 10:05:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by DariusHQ on 2026-10-11T10:05:05Z.


What

getcontext (dar03AOn+nM) and setcontext (2VRU7xiqLO8) in libkernel and makecontext (GipcbdDM5cI) in libSceLibcInternal. This replaces #1841, which was closed because no title stopped at them yet and because it used the wrong ucontext layout. Both points are now settled on that thread:

  • PSXS5 (PPSA97510), SwanStationPS5 (PPSA98510) and Nuvio PS5 (PPSA99997) stop at setcontext on main on Linux (@babyhuey).
  • EVO Player (PPSA99039) and ProsperoStore (PPSA99000) stop at it on Windows, with FAIL: unresolved ELF import 2VRU7xiqLO8 from libkernel.prx (@LeandroLP23, @orishamir).

In these titles the callers are the statically linked OpenSSL's ASYNC code (crypto/async/arch/async_posix.c).

Layout. The three functions now use FreeBSD 11's amd64 ucontext_t, because the titles are built against that layout: mcontext at 0x10, mc_len 800, mc_fpstate at 0xe0 in it, uc_link at 0x330, uc_stack at 0x338, 0x370 bytes in all. In EVO Player 0.10.0:

  • ASYNC_is_capable captures into a 0x370-byte buffer on the stack (sub rsp, 0x370; lea rdi, [rbp-0x370]; call getcontext);
  • async_fibre_makecontext stores ss_sp at +0x338, ss_size at +0x340 and uc_link at +0x330;
  • the fibre's env_init follows the 0x370-byte context and its 96-byte jmp_buf, at +0x3d0.

The exception handler's 0x500-byte context in Exception.cpp is unrelated to these functions and stays as it is. The layout lives in System/include/UserContext.hpp.

getcontext is written in assembly, so it saves every register as it was at the call. It stores the context as FreeBSD's sys_getcontext does: rax and rdx as 0, the carry flag clear, rip and rsp as after the return, the FXSAVE image, mc_len and the signal mask (through sigprocmask). Like UC_COPY_SIZE, it writes only the 0x330 bytes before uc_link, so uc_link, uc_stack and uc_flags keep what the caller stored.

setcontext fails with EINVAL on a null context, a wrong mc_len or unknown mc_flags bits, as set_mcontext does. It installs the context's signal mask and masks MXCSR with the host's MXCSR_MASK, as fpusetregs does, because FXRSTOR faults on reserved bits. It returns through iretq, so every general register, rip, rsp and the PSL_USERCHANGE flags come from the context. Nothing is written below the target stack pointer, which matters for a context taken in a signal handler.

makecontext follows FreeBSD 11's lib/libc/amd64/gen/makecontext.c: at most six arguments and a stack of at least MINSIGSTKSZ (2048) bytes, otherwise mc_len becomes 0. Its wrapper calls the function, then setcontext(uc_link), or exit(0) when there is no link.

Windows stack bounds. Windows checks guard-page growth against StackBase and DeallocationStack in the TEB. It checks exception dispatch and unwinding against StackLimit and StackBase. So the TEB must describe the stack the thread runs on, as libSceFiber already keeps it for fiber stacks.

  • A new libc helper, GuestStacks, keeps the TEB in step for setcontext and longjmp.
  • makecontext registers its stack and pins it writable, as fiber stacks are pinned.
  • A switch to a registered stack takes that stack's bounds. Any other switch takes the committed region around the target rsp from VirtualQuery; for a thread stack, that is its current StackLimit to StackBase.
  • The bounds change after the last write to the old stack.

longjmp needs this because OpenSSL leaves a fibre with _longjmp. Without it, the thread would run on its own stack with the fibre's bounds, and its next guard-page hit would raise STATUS_GUARD_PAGE_VIOLATION. Linux gets the three functions and no other change.

TechnicalDebt records:

  • the layout source, and that the console's own layout for these functions is unverified;
  • the FreeBSD source of makecontext;
  • what the FXSAVE-only state and setcontext leave out;
  • the Windows stack pin and the bounds fallback.

Tested

Windows 11 (26200), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, full build with BUILD_TESTING=ON on a73a1af9c.

ctest: 824/825 passed. The failure is windows_exceptions (0xc0000409, "through runtime frames"), which fails the same way with this branch's libc changes reverted to main. guest_user_context and guest_user_context_exit passed 200 runs in a row (--repeat until-fail:200).

guest_user_context covers:

  • errors: null contexts, a wrong mc_len, unknown mc_flags; makecontext with seven arguments, a 2047-byte stack, no stack, and an invalid context;
  • capture: an assembly caller loads known values into every register and sets the carry flag. The test checks each saved register, rax/rdx 0, carry clear, rip, rsp, MXCSR, the x87 control word, the signal mask, the zeroed fields, and that nothing from uc_link to the end of the 0x370 bytes changes;
  • restore: a context with patterns in every general register, XMM0-15, MXCSR (with a reserved bit set), the x87 control word and the flags lands in an assembly stub that records them;
  • makecontext with six 64-bit arguments, an aligned entry stack and a return through uc_link;
  • OpenSSL's pattern, with the fibre laid out as OpenSSL's (context, jmp_buf, flag): setcontext into a job, then four rounds of setjmp/longjmp both ways;
  • the signal mask restored by setcontext;
  • on Windows: the TEB bounds after every switch, a C++ exception thrown and caught on the context stacks, and about 512 KiB of new host stack after returning.

guest_user_context_exit checks that a context without uc_link exits with 0.

Mutation check: the tests catch each of these. I ran the first one on this branch; the others ran on #1841, whose code is the same here apart from the layout:

  • getcontext writing the whole ucontext instead of stopping at uc_link;
  • getcontext keeping the carry flag or saving rcx as rbx;
  • setcontext or longjmp keeping the old bounds, or makecontext not registering its stack;
  • setcontext keeping reserved MXCSR bits, ignoring the context's flags, not loading r11, keeping the current signal mask, or accepting a wrong mc_len;
  • makecontext shifting its arguments or misaligning the entry stack;
  • a context without uc_link aborting instead of exiting.

tools/import_audit.py on EVO Player 0.10.0 relinked with --windows --registry (eboot.bin and libc.prx unwrapped): 0 absent imports with this branch, and the three NIDs resolve. I did not run a title. @LeandroLP23 offered to run EVO Player and ProsperoRadio on Windows with it.

Not run on Linux (no Linux host here). The Linux path is the same assembly without the TEB call; CI runs it.

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 in TechnicalDebt
  • 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
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4818252756 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3421). Originally posted by [DariusHQ](https://github.com/DariusHQ) on 2026-10-11T10:05:05Z. --- ### What `getcontext` (`dar03AOn+nM`) and `setcontext` (`2VRU7xiqLO8`) in libkernel and `makecontext` (`GipcbdDM5cI`) in libSceLibcInternal. This replaces #1841, which was closed because no title stopped at them yet and because it used the wrong `ucontext` layout. Both points are now settled on that thread: - PSXS5 (PPSA97510), SwanStationPS5 (PPSA98510) and Nuvio PS5 (PPSA99997) stop at `setcontext` on `main` on Linux (@babyhuey). - EVO Player (PPSA99039) and ProsperoStore (PPSA99000) stop at it on Windows, with `FAIL: unresolved ELF import 2VRU7xiqLO8 from libkernel.prx` (@LeandroLP23, @orishamir). In these titles the callers are the statically linked OpenSSL's ASYNC code (`crypto/async/arch/async_posix.c`). **Layout.** The three functions now use FreeBSD 11's amd64 `ucontext_t`, because the titles are built against that layout: `mcontext` at 0x10, `mc_len` 800, `mc_fpstate` at 0xe0 in it, `uc_link` at 0x330, `uc_stack` at 0x338, 0x370 bytes in all. In EVO Player 0.10.0: - `ASYNC_is_capable` captures into a 0x370-byte buffer on the stack (`sub rsp, 0x370; lea rdi, [rbp-0x370]; call getcontext`); - `async_fibre_makecontext` stores `ss_sp` at +0x338, `ss_size` at +0x340 and `uc_link` at +0x330; - the fibre's `env_init` follows the 0x370-byte context and its 96-byte `jmp_buf`, at +0x3d0. The exception handler's 0x500-byte context in `Exception.cpp` is unrelated to these functions and stays as it is. The layout lives in `System/include/UserContext.hpp`. **getcontext** is written in assembly, so it saves every register as it was at the call. It stores the context as FreeBSD's `sys_getcontext` does: `rax` and `rdx` as 0, the carry flag clear, `rip` and `rsp` as after the return, the FXSAVE image, `mc_len` and the signal mask (through `sigprocmask`). Like `UC_COPY_SIZE`, it writes only the 0x330 bytes before `uc_link`, so `uc_link`, `uc_stack` and `uc_flags` keep what the caller stored. **setcontext** fails with `EINVAL` on a null context, a wrong `mc_len` or unknown `mc_flags` bits, as `set_mcontext` does. It installs the context's signal mask and masks MXCSR with the host's `MXCSR_MASK`, as `fpusetregs` does, because FXRSTOR faults on reserved bits. It returns through `iretq`, so every general register, `rip`, `rsp` and the `PSL_USERCHANGE` flags come from the context. Nothing is written below the target stack pointer, which matters for a context taken in a signal handler. **makecontext** follows FreeBSD 11's `lib/libc/amd64/gen/makecontext.c`: at most six arguments and a stack of at least `MINSIGSTKSZ` (2048) bytes, otherwise `mc_len` becomes 0. Its wrapper calls the function, then `setcontext(uc_link)`, or `exit(0)` when there is no link. **Windows stack bounds.** Windows checks guard-page growth against `StackBase` and `DeallocationStack` in the TEB. It checks exception dispatch and unwinding against `StackLimit` and `StackBase`. So the TEB must describe the stack the thread runs on, as libSceFiber already keeps it for fiber stacks. - A new libc helper, `GuestStacks`, keeps the TEB in step for `setcontext` and `longjmp`. - `makecontext` registers its stack and pins it writable, as fiber stacks are pinned. - A switch to a registered stack takes that stack's bounds. Any other switch takes the committed region around the target `rsp` from `VirtualQuery`; for a thread stack, that is its current `StackLimit` to `StackBase`. - The bounds change after the last write to the old stack. `longjmp` needs this because OpenSSL leaves a fibre with `_longjmp`. Without it, the thread would run on its own stack with the fibre's bounds, and its next guard-page hit would raise `STATUS_GUARD_PAGE_VIOLATION`. Linux gets the three functions and no other change. TechnicalDebt records: - the layout source, and that the console's own layout for these functions is unverified; - the FreeBSD source of `makecontext`; - what the FXSAVE-only state and `setcontext` leave out; - the Windows stack pin and the bounds fallback. ### Tested Windows 11 (26200), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, full build with `BUILD_TESTING=ON` on `a73a1af9c`. `ctest`: 824/825 passed. The failure is `windows_exceptions` (`0xc0000409`, "through runtime frames"), which fails the same way with this branch's libc changes reverted to `main`. `guest_user_context` and `guest_user_context_exit` passed 200 runs in a row (`--repeat until-fail:200`). `guest_user_context` covers: - errors: null contexts, a wrong `mc_len`, unknown `mc_flags`; `makecontext` with seven arguments, a 2047-byte stack, no stack, and an invalid context; - capture: an assembly caller loads known values into every register and sets the carry flag. The test checks each saved register, `rax`/`rdx` 0, carry clear, `rip`, `rsp`, MXCSR, the x87 control word, the signal mask, the zeroed fields, and that nothing from `uc_link` to the end of the 0x370 bytes changes; - restore: a context with patterns in every general register, XMM0-15, MXCSR (with a reserved bit set), the x87 control word and the flags lands in an assembly stub that records them; - `makecontext` with six 64-bit arguments, an aligned entry stack and a return through `uc_link`; - OpenSSL's pattern, with the fibre laid out as OpenSSL's (context, `jmp_buf`, flag): `setcontext` into a job, then four rounds of `setjmp`/`longjmp` both ways; - the signal mask restored by `setcontext`; - on Windows: the TEB bounds after every switch, a C++ exception thrown and caught on the context stacks, and about 512 KiB of new host stack after returning. `guest_user_context_exit` checks that a context without `uc_link` exits with 0. Mutation check: the tests catch each of these. I ran the first one on this branch; the others ran on #1841, whose code is the same here apart from the layout: - `getcontext` writing the whole `ucontext` instead of stopping at `uc_link`; - `getcontext` keeping the carry flag or saving `rcx` as `rbx`; - `setcontext` or `longjmp` keeping the old bounds, or `makecontext` not registering its stack; - `setcontext` keeping reserved MXCSR bits, ignoring the context's flags, not loading `r11`, keeping the current signal mask, or accepting a wrong `mc_len`; - `makecontext` shifting its arguments or misaligning the entry stack; - a context without `uc_link` aborting instead of exiting. `tools/import_audit.py` on EVO Player 0.10.0 relinked with `--windows --registry` (`eboot.bin` and `libc.prx` unwrapped): 0 absent imports with this branch, and the three NIDs resolve. I did not run a title. @LeandroLP23 offered to run EVO Player and ProsperoRadio on Windows with it. Not run on Linux (no Linux host here). The Linux path is the same assembly without the TEB call; CI runs it. ### 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`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [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] AI-assisted: yes
github-actions[bot] commented 2026-10-11 10:05:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-11T10:05:31Z.


Progress report (24cb0d2 → cf1545d)

📈 System libraries: 85.61% (+0.01%, +2 implemented functions)

✅ 2 implemented
Library Name
libSceLibcInternal makecontext_nid_postfix
libkernel setcontext_nid_postfix
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6107875991 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3421#issuecomment-6107875991). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-11T10:05:31Z. --- <!-- progress-report --> ### Progress report (24cb0d2 → cf1545d) 📈 **System libraries**: 85.61% (+0.01%, +2 implemented functions) <details> <summary>✅ 2 implemented</summary> | Library | Name | | - | - | | libSceLibcInternal | `makecontext_nid_postfix` | | libkernel | `setcontext_nid_postfix` | </details>
adriadam10 commented 2026-10-11 10:21:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T10:21:44Z.


Checked on Linux: build, guest_user_context and guest_user_context_exit pass, and a mutation (getcontext keeping the carry flag) makes the test abort. makecontext matches FreeBSD 11's makecontext.c, the TechnicalDebt entries cover the unverified console layout, the FXSAVE-only state and the Windows stack pin, and no other open PR touches these functions. The Windows stack-bounds path is covered by the author's Windows 11 run, not reproduced here; merging.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6108025622 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3421#issuecomment-6108025622). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-11T10:21:44Z. --- Checked on Linux: build, `guest_user_context` and `guest_user_context_exit` pass, and a mutation (`getcontext` keeping the carry flag) makes the test abort. `makecontext` matches FreeBSD 11's `makecontext.c`, the TechnicalDebt entries cover the unverified console layout, the FXSAVE-only state and the Windows stack pin, and no other open PR touches these functions. The Windows stack-bounds path is covered by the author's Windows 11 run, not reproduced here; merging.
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!3421
No description provided.