Skip to content

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

Merged
adriadam10 merged 1 commit into
boykopovar:mainfrom
DariusHQ:feat/libkernel-ucontext-freebsd
Oct 11, 2026
Merged

adriadam10 merged 1 commit into
boykopovar:mainfrom
DariusHQ:feat/libkernel-ucontext-freebsd

Conversation

@DariusHQ

Copy link
Copy Markdown
Contributor

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

PSXS5, SwanStationPS5 and Nuvio stop at start-up on setcontext on main,
and EVO Player and ProsperoStore do on Windows. The three are imported
by the statically linked OpenSSL's ASYNC code.

The three use FreeBSD 11's amd64 ucontext_t (mcontext at 0x10, mc_len
800, uc_link at 0x330, 0x370 bytes), which the titles are built
against: EVO Player's ASYNC_is_capable captures into a 0x370-byte stack
buffer, and async_fibre_makecontext sets uc_link at 0x330 and uc_stack
at 0x338. getcontext saves every register at its call in assembly and
stores the context as FreeBSD's sys_getcontext does: rax and rdx as 0,
the carry flag clear, the FXSAVE image and the signal mask, and nothing
from uc_link on. setcontext checks mc_len and mc_flags as set_mcontext
does, installs the signal mask, masks MXCSR with the host's MXCSR_MASK
and returns through iretq, so every general register and the flags are
restored and nothing is written below the target stack pointer.
makecontext follows FreeBSD 11's amd64 libc.

Windows checks guard-page growth and exception unwinding against the
stack bounds in the TEB. setcontext and longjmp now set them to the
stack they switch to, which makecontext registers and pins writable as
libSceFiber does for fiber stacks. OpenSSL enters a context with
setcontext and then switches with _setjmp and _longjmp.
@github-actions

Copy link
Copy Markdown

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

@adriadam10

Copy link
Copy Markdown
Collaborator

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 up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants