feat(libkernel): implement getcontext, setcontext and makecontext #1841
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/1841"
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 DariusHQ on 2026-10-08T21:18:48Z.
What
getcontext(dar03AOn+nM) andsetcontext(2VRU7xiqLO8) in libkernel andmakecontext(GipcbdDM5cI) in libSceLibcInternal are missing, so the 15 titles that #1578 lists for them stop at start-up. Part of #1578; no open PR implements them.In PPSA99039 (EVO Player 0.10.0) every call site is in the statically linked OpenSSL's ASYNC code (
crypto/async/arch/async_posix.c):ASYNC_is_capable,async_fibre_makecontext, andasync_fibre_swapcontext, which enters a new fibre withsetcontextand switches afterwards with_setjmp/_longjmp.getcontext is written in assembly, so it saves every register as it was at the call. It stores the context as FreeBSD's
sys_getcontextdoes:raxandrdxas 0, the carry flag clear,ripandrspas after the return, the FXSAVE image,mc_len, and the signal mask (throughsigprocmask). LikeUC_COPY_SIZE, it writes only the 0x4c0 bytes beforeuc_link, souc_link,uc_stackanduc_flagskeep what the caller stored.setcontext fails with
EINVALon a null context, a wrongmc_lenor unknownmc_flagsbits, asset_mcontextdoes. It installs the context's signal mask, masks MXCSR with the host'sMXCSR_MASKasfpusetregsdoes (FXRSTOR faults on reserved bits), and returns throughiretq: every general register,rip,rspand thePSL_USERCHANGEflags come from the context, and 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 leastMINSIGSTKSZ(2048) bytes, otherwisemc_lenbecomes 0. Its wrapper calls the function, thensetcontext(uc_link), orexit(0)when there is no link. It lives in the libSceLibcInternal module, which links libkernel.The three use the layout of the exception handler's context (
mcontextat 0x40, 0x500 bytes), whichSystem/include/GuestContext.hppnow declares for them. shadPS4 passes the same layout tosigactionhandlers, and Unity's PS5Util readsmc_rspat 0xf8. Homebrew built against FreeBSD's headers expects FreeBSD's 0x370-byte layout instead: PPSA99039'sASYNC_is_capablepasses a 0x370-byte stack buffer. This is recorded in TechnicalDebt.Exception.cppkeeps its own copy of the structures for now: #1431, #1562 and #1802 all change them, and moving them here would conflict with all three. Once those land,Exception.cppcan include the header in a follow-up.Windows stack bounds. Windows checks guard-page growth against
StackBaseandDeallocationStackin the TEB, and exception dispatch and unwinding againstStackLimitandStackBase, so the TEB must describe the stack the thread runs on, as libSceFiber keeps it for fiber stacks. A new libc helper,GuestStacks, does this forsetcontextandlongjmp.makecontextregisters its stack and pins it writable, as fiber stacks are pinned. A switch to a registered stack takes its bounds; any other switch takes the committed region around the targetrspfromVirtualQuery, which for a thread stack is its currentStackLimittoStackBase. The bounds change after the last write to the old stack.longjmpneeds 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 raiseSTATUS_GUARD_PAGE_VIOLATION. Linux gets the three functions and no other change.TechnicalDebt records the unverified layout and the FreeBSD-header mismatch, the FreeBSD source of
makecontext, what the FXSAVE-only state andsetcontextleave out, the Windows pin, and the bounds fallback.A test merge of this branch with every other open pull request on
364a56b6conflicts only with #1128, which reformats the whole tree, including thesetjmp/longjmpassembly. The overlap report's__error_nid_postfixentries are declarations of the existing libc export, as in nine files onmain; this PR does not export it.Tested
Windows 11 (26200), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, full build with
BUILD_TESTING=ONon364a56b6:ctest483/483 passed.guest_user_contextandguest_user_context_exitpassed 200 runs in a row (--repeat until-fail:200).guest_user_contextcovers:mc_len, unknownmc_flags;makecontextwith seven arguments, a 2047-byte stack, no stack, and an invalid context;rax/rdx0, carry clear,rip,rsp, MXCSR, the x87 control word, the signal mask, the zeroed fields, and that nothing fromuc_linkon changes;makecontextwith six 64-bit arguments, an aligned entry stack and a return throughuc_link;setcontextinto a job, then four rounds ofsetjmp/longjmpboth ways;setcontext;guest_user_context_exitchecks that a context withoutuc_linkexits with 0.Mutation check, all caught:
setcontextorlongjmpkeeping the old bounds,makecontextnot registering its stack,getcontextkeeping the carry flag, writing pastuc_linkor savingrcxasrbx,setcontextkeeping reserved MXCSR bits, ignoring the context's flags, not loadingr11, keeping the current signal mask or accepting a wrongmc_len,makecontextshifting its arguments or misaligning the entry stack, and a context withoutuc_linkaborting instead of exiting.tools/import_audit.pyon PPSA99039 (EVO Player 0.10.0): 24 absent imports onmain, 21 with this branch; the three are resolved, and the built prx export the NIDs above. No title run: PPSA99039 still has other absent imports.Not run on Linux (no Linux host here). The Linux path is the same assembly without the TEB call; CI runs it.
Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-08T21:22:44Z.
Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.
main)__error_nid_postfix__error_nid_postfixcore/libs/prx/libSceLibcInternal/CMakeLists.txtL1__error_nid_postfix__error_nid_postfixImported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T09:29:57Z.
Closing: no title stops at
getcontext,setcontextormakecontexton main; EVO-PLAYER stops at other imports first, and its OpenSSL passes FreeBSD's 0x370-byteucontextwhile this uses the 0x500-byte layout. Reopen when these are a title's next stop on main, with the log line.Imported from boykopovar/AnyPS5. Originally posted by babyhuey on 2026-10-11T06:37:43Z.
@DariusHQ
setcontextis now the next stop for three catalog titles onmain52ce9b8a(Linux, catalog builds withsce_module/libc.prxunwrapped as #2605 requires), each withapp.elf: symbol lookup error: app.elf: undefined symbol: 2VRU7xiqLO8:Three more reach it right after other open fixes: EVO Player after
pthread_getaffinity_np(#1922), and PS5MC and Emby5 aftergetprogname(#1869).The closing note's layout point still applies: EVO Player's OpenSSL passes FreeBSD's 0x370-byte
ucontext, and this branch uses 0x500. Intake needs 10 merged PRs to open a new one. Would you like to update the layout, or would you rather I carry it with your authorship and make that change on top?Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-11T08:33:24Z.
Windows data for the count above (Windows 11, WinLibs GCC 15.2.0 r7, Release, titles relinked with their own
libc.prxunwrapped):setcontexton plainmainf60923bfhere, without #1922:FAIL: unresolved ELF import 2VRU7xiqLO8 from libkernel.prx. Windows binds the imports in a different order from Linux, sopthread_getaffinity_npisn't reached first._umtx_op) and #3347 (getprogname) are merged on top.Once this is reopened I can run both titles on Windows with it.
Imported from boykopovar/AnyPS5. Originally posted by orishamir on 2026-10-11T08:57:34Z.
@oneandonlydean two more catalog titles import all three, from
tools/import_audit.pyonmainccf9ff90with theireboot.binandlibc.prxunwrapped (details in the linked comments): ProsperoStore (PPSA99000, #2908) reachesgetcontext/setcontext/makecontextafter_umtx_op(#1482) andgetprogname(#3347); Cloud Play (PPSA99600, #3249) afterlocaleconv,getprognameand_umtx_op. With @babyhuey's three titles that stop atsetcontextonmaintoday and @LeandroLP23's Windows run of EVO Player, that is nine catalog titles on this thread that need the three, and the condition in the closing note is met. Nothing else open implements them; theucontextsize question (0x370 vs 0x500) is the one point left for whoever carries it.AI-assisted: yes (Claude Code Fable 5.1 xhigh)
Imported from boykopovar/AnyPS5. Originally posted by orishamir on 2026-10-11T09:33:26Z.
The log line for the closing note's condition, now that #1482 is merged: ProsperoStore (PPSA99000, catalog v1.000.050) stops at start-up on
setcontextonmain09bd4aa1+3879e7ed(the #1482 merge), Windows 11, WinLibs GCC 15.2.0 r7,relinker --windows --windows-diagnostics --registry:Windows binds
setcontextbeforegetprognamehere, as @LeandroLP23 saw for EVO Player; on Linux the loader reports whichever of the two it reaches first.AI-assisted: yes (Claude Code Fable 5.1 xhigh)
Imported from boykopovar/AnyPS5. Originally posted by DariusHQ on 2026-10-11T10:06:11Z.
Opened #3421 with FreeBSD's 0x370-byte layout. Thanks for the logs.
Pull request closed