fix(libkernel): prevent TLS nullptr crash in scePthreadCreate #1746

Closed
Kikoarl wants to merge 1 commit from upstream-pr/1746 into main
Kikoarl commented 2026-10-08 18:21:25 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Kikoarl on 2026-10-08T18:21:25Z.


What

This PR addresses two concurrency and stability issues in core/libs/prx/libkernel/Pthread/src/Thread.cpp:

  1. Prevent TLS nullptr crash in scePthreadCreate:
    scePthreadCreate on Linux (#else branch) previously used std::promise<bool> start and start.set_value(true) to synchronize the creator and newly spawned threads.
    Under Linux GCC/glibc, std::promise::set_value invokes std::call_once, which relies on libstdc++ thread-local storage (_ZSt15__once_callable). When host tests or client code run across the boundary between the PRX shared library and test executables, the trampoline function executed via pthread_once / __once_proxy can dereference a null TLS pointer (_ZSt15__once_callable is 0x0 due to dual runtime / TLS model mismatch), resulting in an immediate SIGSEGV in std::once_flag::_Prepare_execution::_FUN at mov (%rax), %rdx.

    This change replaces std::promise<bool> on Linux with C++20 std::atomic<int> wait/notify synchronization (wait(0), release store + notify_one()), avoiding any call to std::call_once or libstdc++ TLS.

  2. Preserve configured thread stack size and bounds in SetStackFromHost:
    When a thread was created via scePthreadCreate with specific stack attributes, the child thread's RunThread executed SetStackFromHost(self) which unconditionally overwrote thread->stackSize with the host thread stack size (typically 8 MB).

    SetStackFromHost now preserves the configured stack size when non-zero. In addition, because x86-64 stacks grow downwards from high to low, it sets thread->stackAddress = reinterpret_cast<void*>(high - thread->stackSize) (matching the Windows behavior in StartNativeThread), ensuring guest thread local variables fall cleanly within the reported stack bounds.

Tested

  • Linux x86-64 (CachyOS, GCC 16, Release).
  • Built target libs: 0 errors.
  • ctest --test-dir /tmp/anyps5_build -R "guest_" -V: all 152 guest tests pass 100%.
  • Verified over 50+ stress test iterations of guest_kernel_is_stack, guest_thread_self, and guest_pthread_attr without failure.
  • python3 tools/check_conventions.py --base origin/main: all convention checks passed.

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:4791066080 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1746). Originally posted by [Kikoarl](https://github.com/Kikoarl) on 2026-10-08T18:21:25Z. --- ### What This PR addresses two concurrency and stability issues in `core/libs/prx/libkernel/Pthread/src/Thread.cpp`: 1. **Prevent TLS nullptr crash in `scePthreadCreate`**: `scePthreadCreate` on Linux (`#else` branch) previously used `std::promise<bool> start` and `start.set_value(true)` to synchronize the creator and newly spawned threads. Under Linux GCC/glibc, `std::promise::set_value` invokes `std::call_once`, which relies on libstdc++ thread-local storage (`_ZSt15__once_callable`). When host tests or client code run across the boundary between the PRX shared library and test executables, the trampoline function executed via `pthread_once` / `__once_proxy` can dereference a null TLS pointer (`_ZSt15__once_callable` is `0x0` due to dual runtime / TLS model mismatch), resulting in an immediate `SIGSEGV` in `std::once_flag::_Prepare_execution::_FUN` at `mov (%rax), %rdx`. This change replaces `std::promise<bool>` on Linux with C++20 `std::atomic<int>` wait/notify synchronization (`wait(0)`, release store + `notify_one()`), avoiding any call to `std::call_once` or libstdc++ TLS. 2. **Preserve configured thread stack size and bounds in `SetStackFromHost`**: When a thread was created via `scePthreadCreate` with specific stack attributes, the child thread's `RunThread` executed `SetStackFromHost(self)` which unconditionally overwrote `thread->stackSize` with the host thread stack size (typically 8 MB). `SetStackFromHost` now preserves the configured stack size when non-zero. In addition, because x86-64 stacks grow downwards from `high` to `low`, it sets `thread->stackAddress = reinterpret_cast<void*>(high - thread->stackSize)` (matching the Windows behavior in `StartNativeThread`), ensuring guest thread local variables fall cleanly within the reported stack bounds. ### Tested - Linux x86-64 (CachyOS, GCC 16, Release). - Built target `libs`: 0 errors. - `ctest --test-dir /tmp/anyps5_build -R "guest_" -V`: all 152 guest tests pass 100%. - Verified over 50+ stress test iterations of `guest_kernel_is_stack`, `guest_thread_self`, and `guest_pthread_attr` without failure. - `python3 tools/check_conventions.py --base origin/main`: all convention checks passed. ### 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-08 18:41:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-08T18:41:24Z.


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.

Pull request Conflicting files (lines on main) Same exports Same new files
#1988 core/libs/prx/libkernel/Pthread/src/Thread.cpp L317-335, L339-340
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6066655422 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1746#issuecomment-6066655422). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-08T18:41:24Z. --- <!-- pr-overlap --> 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**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | #1988 | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` [L317-335](https://github.com/boykopovar/AnyPS5/blob/745b775e2d883c68560b2d87f4ab96a01e221ccf/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L317-L335), [L339-340](https://github.com/boykopovar/AnyPS5/blob/745b775e2d883c68560b2d87f4ab96a01e221ccf/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L339-L340) | | |
WifeInLantern commented 2026-10-09 07:28:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by WifeInLantern on 2026-10-09T07:28:54Z.


Windows 11 (26200), WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON, #1746 merged onto current main (clean). All 146 guest_* tests pass (excluding the relinker Python tests, which I didn't build). guest_kernel_is_stack, guest_thread_self, guest_pthread_attr and guest_web_browser_dialog pass 30 repeated runs.

The Windows CI failure is guest_web_browser_dialog with reserve the guest arena range: Attempt to access invalid address; it passes here and the error is in address-space reservation, not threading, so it looks unrelated.

The change does not affect Windows at runtime: the promise removal is in the Linux branch, and SetStackFromHost is skipped on Windows because StartNativeThread already sets stackAddress. So this only confirms nothing breaks on Windows; the Linux fixes are not verified by me.

Two notes: the stack-bounds fix is separate from the scePthreadCreate TLS fix, and CONTRIBUTING asks for one topic per PR. The overlap bot also lists #1802 and #1988 on the same lines.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6076483127 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1746#issuecomment-6076483127). Originally posted by [WifeInLantern](https://github.com/WifeInLantern) on 2026-10-09T07:28:54Z. --- Windows 11 (26200), WinLibs GCC 15.2.0 r7, Release, `BUILD_TESTING=ON`, #1746 merged onto current main (clean). All 146 `guest_*` tests pass (excluding the relinker Python tests, which I didn't build). `guest_kernel_is_stack`, `guest_thread_self`, `guest_pthread_attr` and `guest_web_browser_dialog` pass 30 repeated runs. The Windows CI failure is `guest_web_browser_dialog` with `reserve the guest arena range: Attempt to access invalid address`; it passes here and the error is in address-space reservation, not threading, so it looks unrelated. The change does not affect Windows at runtime: the promise removal is in the Linux branch, and `SetStackFromHost` is skipped on Windows because `StartNativeThread` already sets `stackAddress`. So this only confirms nothing breaks on Windows; the Linux fixes are not verified by me. Two notes: the stack-bounds fix is separate from the `scePthreadCreate` TLS fix, and CONTRIBUTING asks for one topic per PR. The overlap bot also lists #1802 and #1988 on the same lines.
oneandonlydean commented 2026-10-09 09:22:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T09:22:32Z.


Which build crashes here on current main? Linux CI runs guest_pthread_attr green, so the null __once_callable points at two libstdc++ copies in your test build rather than at std::promise, and std::call_once elsewhere in Thread.cpp would hit the same thing. Please also move the stack-size commit to its own PR.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6078124402 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1746#issuecomment-6078124402). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T09:22:32Z. --- Which build crashes here on current main? Linux CI runs `guest_pthread_attr` green, so the null `__once_callable` points at two libstdc++ copies in your test build rather than at `std::promise`, and `std::call_once` elsewhere in `Thread.cpp` would hit the same thing. Please also move the stack-size commit to its own PR.
Kikoarl commented 2026-10-09 12:53:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Kikoarl on 2026-10-09T12:53:45Z.


Thanks for testing and review @WifeInLantern and @oneandonlydean!

  1. As requested, I have removed the SetStackFromHost stack bounds commit from this PR and kept it in a separate branch so this PR remains strictly focused on a single topic.

  2. Regarding the crash on Linux: running guest_pthread_attr_tests against unpatched libkernel.prx reproduces a SIGSEGV inside pthread_once() invoked by std::promise::set_value():

Thread 1 "guest_pthread_a" received signal SIGSEGV, Segmentation fault.
0x0000555555563f7b in std::once_flag::_Prepare_execution ... std::call_once<void (std::__future_base::_State_baseV2::*)
#1  0x00007ffff7ab2424 in libc.so.6
#2  0x00007ffff7ab2549 in pthread_once () from libc.so.6
#3  0x00007ffff7e6ee3d in scePthreadCreate () from libkernel.prx
#4  0x0000555555565490 in main ()

The crash occurs because std::call_once internally relies on __once_callable in thread-local storage (TLS), which dereferences null across the shared library / test executable DSO boundary. Replacing std::promise with std::atomic<int> synchronization avoids std::call_once and cross-DSO TLS lifetime issues in scePthreadCreate, passing all guest_pthread_* tests cleanly.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6081289372 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1746#issuecomment-6081289372). Originally posted by [Kikoarl](https://github.com/Kikoarl) on 2026-10-09T12:53:45Z. --- Thanks for testing and review @WifeInLantern and @oneandonlydean! 1. As requested, I have removed the `SetStackFromHost` stack bounds commit from this PR and kept it in a separate branch so this PR remains strictly focused on a single topic. 2. Regarding the crash on Linux: running `guest_pthread_attr_tests` against unpatched `libkernel.prx` reproduces a `SIGSEGV` inside `pthread_once()` invoked by `std::promise::set_value()`: ```text Thread 1 "guest_pthread_a" received signal SIGSEGV, Segmentation fault. 0x0000555555563f7b in std::once_flag::_Prepare_execution ... std::call_once<void (std::__future_base::_State_baseV2::*) #1 0x00007ffff7ab2424 in libc.so.6 #2 0x00007ffff7ab2549 in pthread_once () from libc.so.6 #3 0x00007ffff7e6ee3d in scePthreadCreate () from libkernel.prx #4 0x0000555555565490 in main () ``` The crash occurs because `std::call_once` internally relies on `__once_callable` in thread-local storage (`TLS`), which dereferences null across the shared library / test executable DSO boundary. Replacing `std::promise` with `std::atomic<int>` synchronization avoids `std::call_once` and cross-DSO TLS lifetime issues in `scePthreadCreate`, passing all `guest_pthread_*` tests cleanly.
oneandonlydean commented 2026-10-09 20:08:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T20:08:16Z.


Closing: Linux CI runs guest_pthread_attr green on main, so the null __once_callable comes from how your build links libstdc++ rather than from std::promise, and the std::call_once calls elsewhere in Thread.cpp would crash the same way there. If a CI configuration or a title hits it, please reopen with that.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6088416666 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1746#issuecomment-6088416666). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T20:08:16Z. --- Closing: Linux CI runs `guest_pthread_attr` green on main, so the null `__once_callable` comes from how your build links libstdc++ rather than from `std::promise`, and the `std::call_once` calls elsewhere in `Thread.cpp` would crash the same way there. If a CI configuration or a title hits it, please reopen with that.

Pull request closed

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!1746
No description provided.