fix(libkernel): start thread stacks on a 16 KiB page boundary on Linux #9684
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/9684"
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 NevesHenry on 2026-10-22T08:26:45Z.
What
On Linux,
scePthreadAttrGet,pthread_attr_get_npandsceKernelIsStackreported a thread's stack starting at an address the host picked. A created thread's stack started wherever the host's start frames ended (for example0x200107f90), and the main thread's started at glibc's 4 KiB boundary. On the console a stack starts on a 16 KiB page boundary.HotSpot (OpenJDK 25) aligns its stack guard zone down to the page size it reads (16384) before protecting it. That protect started below the reported stack,
mprotectrefused it withEINVAL(main thread) orEACCES(created threads), and the VM stopped:The VM's error report then aborted the process with
sysctl_nid_postfix: unsupported MIB 1.21(kern.boottime, read byos::print_os_infofor the report).scePthreadSelf(the main thread, when it doesn't run on the guest main stack from #7532) reports its host stack from the first 16 KiB boundary above its bottom.#7532, on
mainsince 2026-11-03, runs a relinked executable's main thread on a stack at the console's address, which starts on a 16 KiB boundary. It doesn't change created threads, which is where ProsperoCraft stops with it (below).Tested
Linux (Ubuntu 22.04, WSL2), Ryzen 9 7900, lavapipe, GCC 13, Release.
Titles, from mateo-cogeanu/ps5-java25-homebrew, unwrapped and relinked with
--trap-sdk-syscall-stubs --registry, rows driven withtools/pad_input.py, run onmain504ea3b53. All three report ALL PASS on a PS5 (firmware 13.60):mainCalling real JNI_CreateJavaVMwith the error aboveJNI_CreateJavaVM returned 0,FileIO25 returned normally,DestroyJavaVM completeJNI_CreateJavaVM returned 0,ZipJar25 returned normally,DestroyJavaVM completeSystem.loadLibraryof the embedded JNI fixture,Dependencies fixture returned normally,DestroyJavaVM completeAt
DestroyJavaVMHotSpot still warnsAttempt to deallocate stack guard pages failedfor the main thread; it isn't fatal and the row passes.milescoviello ran ProsperoCraft (PPSA99874, 01.000.117), the catalog's Minecraft Java launcher, on
main750cf6cf48(comment). With #12436 the JVM stops at start-up with themprotecterror above, in the primordial thread. With #7532 as well, the primordial thread gets past it and the same error moves to theReference Handlerthread, whose stack doesn't start on a page boundary. With #7532 and this PR it runs the full 120 s (#7532 is onmainnow): the Instances screen, the new-instance form and its on-screen keyboard, following pad input.guest_thread_stack_guard: the main thread's and created threads' (64 KiB, 1 MiB, 16 MiB) stacks start on a 16 KiB boundary, keep the requested size, contain the running frame, matchsceKernelIsStack, and their lowest three pages can be protected read/write, none, read/write. It aborts onmainand passes here.8989d4ff10mergesmaind63781e9ce. The one conflict was indocs/dev/debt/libkernel.md, where #7192 split thesceKernelInstallExceptionHandlerentry: those entries aremain's, the stack entry is this branch's.main'sThread.cppchanges since5454cd2e45(the guest main stack from #7532, the Windows GS state, thread references in join and detach) don't move created threads' stacks, and on the guest main stackHostStackLimitsreturns bounds that already start on a 16 KiB boundary, so the rounding changes nothing there. On that head, GCC 11.4:ctest -Rnow selects 172 tests (mainadded 22) and all pass.guest_thread_stack_guardpasses 50/50 repeats, andpublic_headerspasses.setarch -R. With address randomization on, 7 of them pass 20/20, andguest_kernel_stack_protectaborts in 25 of 40 runs at ASan start-up, before the test runs (Shadow memory range interleaves with an existing memory mapping, google/sanitizers#856, with GCC 11's libasan here). It aborts the same way in 25 of 40 runs withThread.cppfrommain; the other 15 runs pass, as with this PR.Thread.cppfrommain:guest_thread_stack_guardaborts, in Release and under ASan.tools/check_conventions.py --base origin/mainandgit diff --checkpass.790fe650fb(main5454cd2e45): the 150 tests then selected byctest -R '^guest_(.*pthread.*|.*thread.*|.*stack.*|cond_.*|.*sem.*|.*sleep_cancel.*|.*tls.*|rwlock_retire|timed_join.*|sigaltstack|kernel_sys.*)$', withoutult_,libressl,net_thread,ampr,savedataand the relinker TLS tests, passed in Release. ASan + UBSan, Debug (-DANYPS5_ENABLE_ASAN=ON,-fsanitize=undefined -fno-sanitize-recover=undefined,UBSAN_OPTIONS=halt_on_error=1), defaultASAN_OPTIONS:guest_thread_stack_guard(which setsdetect_stack_use_after_return=0, like its neighbours),guest_kernel_is_stack,guest_kernel_stack_protect,guest_thread_self,guest_pthread_stack,guest_pthread_join_detach,guest_cond_timedwaitandguest_pthread_join_selfpassed 20/20; of the 150, 146 passed, andguest_libc_threads,guest_posix_sem_post,guest_pthread_rwlock(LeakSanitizer leaks) andguest_force_tls_destructor(UBSan misaligned load atlibSceLibcInternal/Export.cpp:87) failed with the same reports withThread.cppfrommain.504ea3b53,737f17291a):ctest -R '^guest_'passed 737/738;guest_runtime_lifecycletimed out in itsconcurrentmode, as it did withThread.cppfrommain.guest_thread_stack_guardpassed withulimit -s1024, 8192, 65536 andunlimited. With the thread start frame taken from a local's address, as before9c1557eaf,guest_pthread_join_detach,guest_cond_timedwaitandguest_pthread_join_selfsegfaulted under ASan, as reported in review. The test includesprx/libkernel/include/Api.hppinstead of declaring the libkernel exports itself (2d1d41779), as the public header audit from #10706 requires.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T08:45:37Z.
Review: APPROVED
Reviewed the Linux stack-bound calculations and thread startup path, including the native-stack reserve and the downward alignment of the guest stack start. The new test covers adopted main and created threads at three stack sizes, verifies the reported bounds against the active frame and
sceKernelIsStack, and exercises guard-page protection. I ran the current-main conventions check andgit diff --check; both passed. Pairwise merge-tree checks with open #7532 and #7838 are clean, and #9683 is the Game bring-up discussion documenting all three Java 25 titles and this blocker. The PR author reports 547/547 guest tests passing on a supported Linux host plus before/after title runs; local runtime reproduction is not available on this Xeon E5-1620 v2 host because the project CPU guard requires features it lacks. The automatic product jobs are skipped by repository policy. I found no remaining issue requiring changes.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-22T09:01:45Z.
Review: COMMENTED
Ran on native Linux (the PR was tested on WSL2 / glibc 2.35): Ubuntu 26.04, kernel 7.0, glibc 2.43, x86_64 i7-8700, GCC 15.2.0, Release, head d82130743 merged
--no-commitontoorigin/main7e2ba73e4.guest_thread_stack_guard+patched_libraries: 2/2 pass.Thread.cppfrommain, test and CMake from the PR):guest_thread_stack_guardaborts, as described.ulimit -s1024, 8192, 16384, 65536 andunlimited(main thread bounds come frompthread_getattr_np, which depends on that limit).One thing for the
-DANYPS5_ENABLE_ASAN=ONbuild:guest_thread_stack_guardaborts there aton the main thread, because ASan's use-after-return fake stack puts
localon the heap (start=0x7ffdc63e0000,&local=0x7097fc722130). No ASan or UBSan report. It's the same reasonguest_kernel_is_stack,guest_pthread_stack,guest_thread_selfandguest_kernel_stack_protecthaveadd_asan_test_options(... detect_stack_use_after_return=0). Adding the same line after theset_tests_propertiescall:makes it pass under ASan+UBSan with no reports, as do those three neighbours.
Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T12:28:11Z.
Review: DISMISSED
A new independent test report found one configuration gap in the added Linux-only guest_thread_stack_guard test. It passes in Release, but aborts in an ASan+UBSan build at the assertion that a local variable lies inside the native main-thread stack. With ASan use-after-return detection enabled, that local can be placed on ASan's fake heap stack instead. The neighboring guest_kernel_is_stack, guest_kernel_stack_protect, guest_thread_self and guest_pthread_stack tests all call add_asan_test_options with detect_stack_use_after_return=0 for this same stack-inspection reason. Please add the same option for guest_thread_stack_guard and rerun it under ASan+UBSan; the independent report says this makes the test pass without sanitizer findings. The exact PR head is unchanged, so the prior code review stands apart from this newly identified test-configuration blocker.
Imported from boykopovar/AnyPS5. Originally posted by valenciana-nc on 2026-10-22T15:33:20Z.
Merge-order coordination with #9482: I rebased that pthread lifetime fix onto main
b7d1d47a5f(head6298429beb) and reran the overlap check.git merge-treefinds only one conflict between our branches: adjacent entries indocs/dev/debt/libkernel.md. Your stack-alignment update and my ended-thread update are separate; there is no code/test conflict or runtime dependency.Proposing #9482 first, followed by rebasing this PR and keeping both updated debt entries. If this PR is ready first, I can instead rebase #9482 afterward and preserve your stack-alignment text. Please let me know which order you prefer; not treating this as an agreed dependency or copying your changes into my PR.
For #9482, Windows focused pthread tests pass 27/27, with 25 attribute-test repeats and a new-main negative control. No Linux/title validation of your stack change is implied. AI-assisted investigation/report.
Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-10-25T16:18:04Z.
Review: COMMENTED
Reviewed head
cbb1115af0b6merged onto main0119103fa9ed(merges clean). WSL2 Ubuntu 24.04, GCC 13.3, i7-13700K. Two builds: Release, and Debug with-DANYPS5_ENABLE_ASAN=ONplus-fsanitize=undefined -fno-sanitize-recover=undefined.What I ran, on this PR and with
Thread.cppfrom main as the control:guest_thread_stack_guard,guest_kernel_is_stack,guest_kernel_stack_protect,guest_thread_self,guest_pthread_stack,guest_pthread_join_detach,guest_cond_timedwait,guest_pthread_join_selfall pass.guest_thread_stack_guardpasses 50/50 repeats, and withulimit -s1024, 8192, 65536 and unlimited. On the control it aborts and the other 7 pass.AllocateGuestStack).nativeStackincludesHOST_STACK_MARGIN, so the aligned-down start stays about 1 MiB above the guard page, whatever the stack size.ASan: the alloca segfaults guest threads.
StartNativeThreadsizes the alloca from&stackEnd(Thread.cpp L812). With ASan's default options, use-after-return detection is on. A local's address can then point into ASan's fake stack, as jotitadev saw forlocalin the test, soframe - stackEndis no longer a distance on the thread stack. Tests that start a guest thread withoutdetect_stack_use_after_return=0crash. The three I ran:guest_pthread_join_detachguest_cond_timedwaitguest_pthread_join_selfASAN_OPTIONS=detect_stack_use_after_return=0Taking the frame from the compiler fixes it:
With only that line changed, all 8 tests above pass in Release and in ASan+UBSan, with no sanitizer report. The three tests above pass 20/20 under default ASan options, and so does
guest_thread_stack_guardwith its option.Nit, debt entry. The rewritten line in
docs/dev/debt/libkernel.mdstill ends with "on Linux it cannot change the unmapped lower pages". That is no longer true: sinceb5909a5ee0,DoMprotectmaps a host stack's unmapped pages before protecting them (MapUnmappedPagesin DirectMemory.cpp, and the "Protecting a host thread's stack" entry says so). Your own test relies on this: it protects the bottom three pages of the main thread's 8 MiB range, which are unmapped, and it passes. I'd drop that clause.Not covered: Windows (I didn't build it) and the Java titles (no dumps here).
AI-assisted (Claude Code); I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-27T03:11:21Z.
Review: COMMENTED
Follow-up to my earlier ASan note, on head
229567502: with theadd_asan_test_optionsline in,guest_thread_stack_guardpasses under ASan. The guest-thread tests from @ahmadmuj's table pass with ASan's default options.Machine: Linux x86_64, i7-8700, Ubuntu 26.04, glibc 2.43, GCC 15.2. Head
229567502merged--no-commitontomainabed03546(clean).guest_thread_stack_guard3/3. The 64 non-GPUpthread|thread|stacktests pass,patched_librariestoo.Thread.cppfrommainwith the rest of the PR kept:guest_thread_stack_guardaborts 3/3.-DANYPS5_ENABLE_ASAN=ON,-fsanitize=undefined -fno-sanitize-recover=undefined, RelWithDebInfo):guest_thread_stack_guard,guest_kernel_is_stack,guest_kernel_stack_protect,guest_thread_self,guest_pthread_stack,guest_pthread_join_detach,guest_cond_timedwaitandguest_pthread_join_selfpass 8/8, three times, with no sanitizer report.guest_thread_stack_guardwithdetect_stack_use_after_return=0. Run by hand withdetect_stack_use_after_return=1, it still aborts, so the option is still needed.detect_stack_use_after_returnoverride. They pass, so the__builtin_frame_address(0)change holds on this toolchain.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-27T06:34:02Z.
Review: COMMENTED
public_headersfails on this head, both on its own and merged onto currentmain(b7105f728). All 10 functions declared at the top of the newcore/libs/tests/GuestThreadStackGuard.cppare also declared incore/libs/prx/libkernel/include/Api.hpp:#10706 (merged 2026-10-24) added this audit: every export must be declared exactly once, in its library's public header. CI did not catch it because the
linux/windowsjobs were skipped on this head.Fix: include the libkernel header in place of
SceTypes.hppand drop theextern "C"block. The header's signatures match the ones in the test:With that change the audit passes for this PR. The only remaining error is the
sceKernelGetModuleInfoForUnwindone that is already onmainfrom #9263 (#11718 fixes it). The test passes a GCC 15.2-fsyntax-onlycheck with the test build flags.Checked on Linux (i7-8700, Ubuntu 26.04, GCC 15.2):
core/libs/tests/test_public_headers.py --audit-onlyon head229567502, alone and merged ontomainb7105f728.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T09:58:34Z.
Review: CHANGES_REQUESTED
Re-review — changes requested
The earlier ASan configuration issue is resolved: the current PR includes
detect_stack_use_after_return=0for the stack-inspection test, the thread-start frame now comes from__builtin_frame_address(0), and the declaration-only test change uses the public libkernel header. The title report is also a useful direct before/after: ProsperoCraft advances from the primordial-thread failure to the created-thread failure with #7532, then completes its 120-second flow with this PR.I checked exact head
2d1d41779e22266275f103085a77b6a055e1c1a9against currentmainf7e84c4cf1609cc10bac95a44cd431805e5ebc8a:tools/check_conventions.pyandgit diff --checkpass.tools/check_main_sync.pyreports 3 changed paths on both sides since merge base504ea3b53:Thread.cpp, libkernelCMakeLists.txt, anddocs/dev/debt/libkernel.md. Main'sThread.cppchanges include thread creation/cancellation and scheduling behavior, so the earlier test runs on main504ea3b53or737f17291ado not cover the current combined thread implementation.Please merge current
main, preserve the 16 KiB stack-bound behavior alongside the newer thread lifecycle changes, and rerunguest_thread_stack_guardplus the focused stack/thread tests and ASan/UBSan check on that integrated head. The earlier code findings appear addressed; this request is for current-main integration and exact-head validation.Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-10-29T12:51:30Z.
Review: APPROVED
Reviewed — approved
On the current head, merged onto current
main, the 16 KiB stack start works with the newer thread lifecycle code: the focused stack and thread tests pass in Release and in ASan + UBSan, andguest_thread_stack_guardfails whenThread.cppcomes frommain.What I ran
790fe650fb37edeb3a89ef25adde463110e01050main:5454cd2e455994d992aca39335ce60507eeda1eb. This is also the merge base, so the merged tree is identical to the head tree.Results
mainmain.git diff --checktools/check_conventions.py --base origin/mainAll conventions checks passed.libs+ 11 test targets)guest_thread_stack_guardrepeatedguest_thread_stack_guardwithulimit -s1024, 8192, 65536, unlimitedpublic_headersAddressSanitizerorruntime erroroutputdetect_stack_use_after_return=1Thread.cppfrommain)guest_thread_stack_guardabortsRelease focused tests
ASan + UBSan focused tests
ctest runs
guest_thread_stack_guardwithASAN_OPTIONS=string_append::detect_stack_use_after_return=0. The three join/condvar tests have no such override, and they also pass when run directly withdetect_stack_use_after_return=1.Negative control
Negative control
I restored only
core/libs/prx/libkernel/Pthread/src/Thread.cppfrommainand kept the new test and the CMake entry. After a rebuild,guest_thread_stack_guardaborted. With the mergedThread.cpprestored and rebuilt, it passes again.Findings
Blocking
None.
MarcZX10's last review asked for the stack/thread tests and ASan/UBSan to be run again on a head that merges current
main. The results above are from such a head (790fe650fb, which mergesmain5454cd2e45), and all of those tests pass. They also confirm ahmadmuj's__builtin_frame_address(0)fix and jotitadev's ASan option on this head.FreeBSD's libthr supports the created-thread layout.
_thr_stack_allocplaces a page-aligned stack directly above its guard and keeps the requestedstacksize_attr, which leaves "unused space above the beginning of the stack" when the size is not a page multiple (thr_stack.c, release/11.4.0).Thread.cpp:930does the same: it aligns the start down and keepsstackSize. TheallocaatThread.cpp:952-954then moves the guest frames below the reported end.nativeStackincludes the 1 MiBHOST_STACK_MARGIN, so the lower start (at most 16 KiB − 1 lower) stays inside the mapping. This matches ahmadmuj's earlier reading.Non-blocking
Thread.cpp:895still setsstackAddress = high - stackSize.scePthreadAttrSetstacksizeaccepts any size of at least the minimum (Attr.cpp:72-80). So on Windows, a size that is not a multiple of 16 KiB gives the same unaligned start this PR fixes on Linux, and HotSpot's aligned-down guard protect would fail there too. The description says the Windows path is unchanged, which is fine for this PR's scope. CONTRIBUTING.md asks for known gaps to be recorded in technical debt, so consider adding a line for this todocs/dev/debt/libkernel.md, or a follow-up that aligns the Windows start the same way.SetStackFromHost(Thread.cpp:331-339) has no platform guard, and the created-thread change sits in the#else(non-Windows)StartNativeThread, so macOS gets both changes too. The PR title and the debt entry atdocs/dev/debt/libkernel.md:197say "on Linux". Either say "outside Windows" or note that macOS was not tested. This is wording only. The code is correct on any host whose page size divides 16 KiB.Not verified
libsand the focused test targets and ran the 11 tests listed above pluspublic_headers. I did not runpatched_librariesor the rest of theguest_suite.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-30T14:28:27Z.
Review: COMMENTED
Follow-up on the
public_headersfailure from my last review: fixed on790fe650f.Linux, Ubuntu 26.04, i7-8700, GCC 15.2, Release, full build. Head merged
--no-commitontomainf91137142e(clean).public_headersandguest_thread_stack_guardpass, 3/3 each. The 102 non-GPUpthread|thread|stacktests pass.GuestThreadStackGuard.cpp(229567502) makes the audit fail again (scePthreadCreate,scePthreadJoin,scePthreadSelf, ... found 2).Thread.cppfrommainwith the rest of the PR kept makesguest_thread_stack_guardabort, 3/3.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.