fix(libkernel): return ESRCH from thread name, priority and affinity calls on a released thread handle #10816

Merged
MarcZX10 merged 3 commits from upstream-pr/10816 into main 2026-11-02 10:24:34 +00:00
MarcZX10 commented 2026-10-25 02:43:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-25T02:43:42Z.


What

scePthreadGetname, scePthreadGetprio (and so scePthreadGetschedparam), scePthreadGetaffinity, scePthreadSetaffinity and scePthreadRename dereferenced the Pthread handle with no check that the thread object still exists. A detached thread frees its PthreadPrivate when it ends, so calling any of them on that handle read or wrote freed memory. AddressSanitizer reports heap-use-after-free in scePthreadGetprio (Thread.cpp, read of the freed object, freed in ~ThreadGuard) and in scePthreadSetaffinity (write).

Each now looks the handle up in the guest thread registry, which the object leaves before it is freed, and returns SCE_KERNEL_ERROR_ESRCH when it is gone. The lookup holds the registry lock for the access, so the object cannot be freed under the call. This is the answer scePthreadAttrGet (#7957) and pthread_setaffinity_np and pthread_getprio already give for an ended thread.

Only released handles change. A thread that is joined or finished but still retained keeps answering as before: GuestPthreadGetname pins scePthreadGetname on a joined thread as success, and no console measurement exists for the others. scePthreadSetprio and scePthreadSetschedparam are not touched because the open #10133 already adds the ESRCH check there with PS5 measurements.

Tested

Rebase follow-up (2026-10-25): rebased the three commits onto current upstream main cdcbd551341927ed91cafb479b2d1fd5fffac9ef without conflicts. On the rebased head, git diff --check upstream/main...HEAD and python3 tools/check_conventions.py --base upstream/main --head HEAD passed. The full local CMake test build could not configure because the SDL2 CMake package is unavailable, so no post-rebase runtime or sanitizer result is claimed. The ASan/runtime evidence below is from the prior base.

Linux x86-64, AddressSanitizer + UBSan build (ANYPS5_ENABLE_ASAN=ON with -fsanitize=undefined, RelWithDebInfo). The host CPU gate was bypassed locally for the run only (not committed). No Windows, no ThreadSanitizer run for this change, no console hardware.

  • New guest_pthread_handle_after_exit creates a detached thread, waits until scePthreadGetprio reports ESRCH, then checks all five calls return ESRCH. On current main it aborts under ASan with heap-use-after-free in scePthreadGetprio called from the test; with the fix it passes in three runs.
  • The guest_pthread_*, guest_cond_*, guest_rwlock_*, guest_semaphore and guest_kernel_sys* tests give the same results as on main. guest_pthread_stack aborts on main too under this ASan build, because it asserts the local frame sits within 4 KiB of the top of the guest stack and ASan frames are larger; guest_semaphore_trace was not built in my selective build.

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 under Silent stubs in their library's technical debt file (none added)
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source (none added)
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

Rebase validation (2026-10-25)

Rebased the three commits onto current upstream main a5a780eaaa7f187fe8f5c7f2ef244f6a6dab2762 without conflicts. On this head, strict GCC C++20 syntax-only checks with -Wall -Wextra -Werror passed for Thread.cpp (suppressing its existing missing-field-initializer warning) and GuestPthreadHandleAfterExit.cpp. git diff --check upstream/main...HEAD and python3 tools/check_conventions.py --base upstream/main --head HEAD also passed. The full local CMake test build could not configure because the SDL2 CMake package is unavailable, so no post-rebase runtime or sanitizer result is claimed. The ASan/runtime evidence above is from the prior base.

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5001232169 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10816). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-25T02:43:42Z. --- ### What `scePthreadGetname`, `scePthreadGetprio` (and so `scePthreadGetschedparam`), `scePthreadGetaffinity`, `scePthreadSetaffinity` and `scePthreadRename` dereferenced the `Pthread` handle with no check that the thread object still exists. A detached thread frees its `PthreadPrivate` when it ends, so calling any of them on that handle read or wrote freed memory. AddressSanitizer reports `heap-use-after-free` in `scePthreadGetprio` (`Thread.cpp`, read of the freed object, freed in `~ThreadGuard`) and in `scePthreadSetaffinity` (write). Each now looks the handle up in the guest thread registry, which the object leaves before it is freed, and returns `SCE_KERNEL_ERROR_ESRCH` when it is gone. The lookup holds the registry lock for the access, so the object cannot be freed under the call. This is the answer `scePthreadAttrGet` (#7957) and `pthread_setaffinity_np` and `pthread_getprio` already give for an ended thread. Only released handles change. A thread that is joined or finished but still retained keeps answering as before: `GuestPthreadGetname` pins `scePthreadGetname` on a joined thread as success, and no console measurement exists for the others. `scePthreadSetprio` and `scePthreadSetschedparam` are not touched because the open #10133 already adds the ESRCH check there with PS5 measurements. ### Tested Rebase follow-up (2026-10-25): rebased the three commits onto current upstream `main` `cdcbd551341927ed91cafb479b2d1fd5fffac9ef` without conflicts. On the rebased head, `git diff --check upstream/main...HEAD` and `python3 tools/check_conventions.py --base upstream/main --head HEAD` passed. The full local CMake test build could not configure because the SDL2 CMake package is unavailable, so no post-rebase runtime or sanitizer result is claimed. The ASan/runtime evidence below is from the prior base. Linux x86-64, AddressSanitizer + UBSan build (`ANYPS5_ENABLE_ASAN=ON` with `-fsanitize=undefined`, RelWithDebInfo). The host CPU gate was bypassed locally for the run only (not committed). No Windows, no ThreadSanitizer run for this change, no console hardware. - New `guest_pthread_handle_after_exit` creates a detached thread, waits until `scePthreadGetprio` reports ESRCH, then checks all five calls return ESRCH. On current `main` it aborts under ASan with `heap-use-after-free` in `scePthreadGetprio` called from the test; with the fix it passes in three runs. - The `guest_pthread_*`, `guest_cond_*`, `guest_rwlock_*`, `guest_semaphore` and `guest_kernel_sys*` tests give the same results as on `main`. `guest_pthread_stack` aborts on `main` too under this ASan build, because it asserts the local frame sits within 4 KiB of the top of the guest stack and ASan frames are larger; `guest_semaphore_trace` was not built in my selective build. ### 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 - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's technical debt file (none added) - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source (none added) - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes ### Rebase validation (2026-10-25) Rebased the three commits onto current upstream `main` `a5a780eaaa7f187fe8f5c7f2ef244f6a6dab2762` without conflicts. On this head, strict GCC C++20 syntax-only checks with `-Wall -Wextra -Werror` passed for `Thread.cpp` (suppressing its existing missing-field-initializer warning) and `GuestPthreadHandleAfterExit.cpp`. `git diff --check upstream/main...HEAD` and `python3 tools/check_conventions.py --base upstream/main --head HEAD` also passed. The full local CMake test build could not configure because the SDL2 CMake package is unavailable, so no post-rebase runtime or sanitizer result is claimed. The ASan/runtime evidence above is from the prior base.
thepoppfish commented 2026-10-25 08:58:03 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by thepoppfish on 2026-10-25T08:58:03Z.

Review: COMMENTED


Independent native Windows validation of exact head f7350f42258f773ebbb515cae848bc2136b726b6.

Windows 11 build 26200, MSYS2 UCRT64 GCC 16.2.0-6 (SEH), CMake 4.3.1, Ninja 1.13.2, CPU only:

  • An out-of-tree target compiles the actual SCE thread/attribute/TSD/mutex/condition code, POSIX thread wrappers, kernel time/wait/sleep code, libc thread-forward registration and guest-allocation registry. No registry lookup, thread lifecycle, native thread creation, stack handling or synchronization implementation is substituted. The small support file below supplies guest errno as Process.cpp does, a throwing unimplemented entry, and Windows abort-report UI suppression.
  • The unmodified repository GuestPthreadHandleAfterExit.cpp, GuestPthreadGetname.cpp and GuestPthreadJoinDetach.cpp all pass. Three consecutive repeat runs of each also pass. This covers the new 20-round detached-thread case, preserves the SCE retained/joined-name answer alongside the POSIX joined-thread ESRCH answer, and checks join/detach compatibility.
  • Negative control: replace only Thread.cpp with main's prior implementation and retain the PR's new test and other sources. The new test fails after 5.08 s. GDB catches its abort in Require/main; the optimized backtrace does not identify the inlined wait helper, so no more precise backtrace claim is made. This is behavioral negative-control evidence, not an independent ASan use-after-free report.
  • Conventions and whitespace checks pass. Merge-tree is clean against main 2742004ed28f765c7147db0e0269ff5868e9eb6f; among the production sources under test, only the intended Thread.cpp additions differ from that main. Builds emit existing unused-function/parameter and missing-initializer warnings in unchanged code, plus LTO's serial-partition notice; no -Werror result is claimed.

The registry lock is held through each protected access, with the name lock released before the registry lock on the name paths. The distinction between registered and live threads preserves the retained-object behavior covered above. I found no additional blocking source issue in this pass. I am leaving this as validation evidence while the existing debt-entry update requested by @oneandonlydean remains pending; these tests do not establish the unmeasured console results.

This is target-level native Windows testing, not a full shared-libc/libkernel integration build, sanitizer/TSan run, console/game run or cross-PR composition test. No maintainer-triggered full CI is claimed. AI-assisted review and testing: yes (OpenAI Codex).

Out-of-tree replay files

CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)
project(AnyPS5ThreadReview LANGUAGES CXX)
enable_testing()
set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-10816" CACHE PATH "Exact PR checkout")
set(THREAD_SOURCE "${REPO}/core/libs/prx/libkernel/Pthread/src/Thread.cpp" CACHE FILEPATH "Thread source under test")
add_library(thread_sources OBJECT
    "${THREAD_SOURCE}"
    "${REPO}/core/libs/prx/libkernel/Pthread/src/Attr.cpp"
    "${REPO}/core/libs/prx/libkernel/Pthread/src/Tsd.cpp"
    "${REPO}/core/libs/prx/libkernel/Pthread/src/Mutex.cpp"
    "${REPO}/core/libs/prx/libkernel/Pthread/src/Cond.cpp"
    "${REPO}/core/libs/prx/libkernel/Pthread/Posix/Thread.cpp"
    "${REPO}/core/libs/prx/libkernel/Time/TimedWait.cpp"
    "${REPO}/core/libs/prx/libkernel/Time/Time.cpp"
    "${REPO}/core/libs/prx/libkernel/Time/SleepWake.cpp"
    "${REPO}/core/libs/prx/libc/src/GuestAllocations.cpp"
    "${REPO}/core/libs/prx/libc/src/Threads.cpp"
    Support.cpp)
target_compile_features(thread_sources PUBLIC cxx_std_20)
target_include_directories(thread_sources PUBLIC "${REPO}/core/libs" "${REPO}/core/libs/prx/libkernel/Pthread/src")
target_compile_options(thread_sources PUBLIC -O1 -g -Wall -Wextra -flto -ffunction-sections -fdata-sections)
foreach(pair IN ITEMS "guest_pthread_handle_after_exit|GuestPthreadHandleAfterExit" "guest_pthread_getname|GuestPthreadGetname" "guest_pthread_join_detach|GuestPthreadJoinDetach")
    string(REPLACE "|" ";" parts "${pair}")
    list(GET parts 0 name)
    list(GET parts 1 source)
    add_executable(${name} "${REPO}/core/libs/tests/${source}.cpp")
    target_link_libraries(${name} PRIVATE thread_sources)
    target_link_options(${name} PRIVATE -flto -Wl,--gc-sections)
    add_test(NAME ${name} COMMAND ${name})
    set_tests_properties(${name} PROPERTIES TIMEOUT 20)
endforeach()

Support.cpp:

#include "prx/libc/include/Api.hpp"
#include "prx/libc/include/General.hpp"
#include <cerrno>
#include <cstdlib>
#include <stdexcept>

[[maybe_unused]] const unsigned int abortFlags = _set_abort_behavior(0, _CALL_REPORTFAULT);

extern "C" int* APS5_VABI __error_nid_postfix() {
    return &errno;
}

extern "C" [[noreturn]] void NotImplemented_nid_no_patch(const char* name) {
    throw std::runtime_error(name);
}

Use GCC 16 UCRT64 bin first on PATH, followed by CMake/Ninja. Configure with cmake -S native-thread-review -B native-thread-review/build16 -G Ninja -DREPO=<exact-PR-checkout> -DCMAKE_CXX_COMPILER=<GCC16-bin>/g++.exe -DCMAKE_BUILD_TYPE=Release, build, then run ctest --test-dir native-thread-review/build16 --output-on-failure --repeat until-fail:3. For the negative control use a separate build directory with -DTHREAD_SOURCE=<main-Thread.cpp-copy> and run only guest_pthread_handle_after_exit. The extra original-source include directory preserves Thread.cpp's relative header paths when using that copy.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5642359049 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10816#pullrequestreview-5642359049). Originally posted by [thepoppfish](https://github.com/thepoppfish) on 2026-10-25T08:58:03Z. **Review:** COMMENTED --- Independent native Windows validation of exact head `f7350f42258f773ebbb515cae848bc2136b726b6`. Windows 11 build 26200, MSYS2 UCRT64 GCC 16.2.0-6 (SEH), CMake 4.3.1, Ninja 1.13.2, CPU only: - An out-of-tree target compiles the actual SCE thread/attribute/TSD/mutex/condition code, POSIX thread wrappers, kernel time/wait/sleep code, libc thread-forward registration and guest-allocation registry. No registry lookup, thread lifecycle, native thread creation, stack handling or synchronization implementation is substituted. The small support file below supplies guest errno as `Process.cpp` does, a throwing unimplemented entry, and Windows abort-report UI suppression. - The unmodified repository `GuestPthreadHandleAfterExit.cpp`, `GuestPthreadGetname.cpp` and `GuestPthreadJoinDetach.cpp` all pass. Three consecutive repeat runs of each also pass. This covers the new 20-round detached-thread case, preserves the SCE retained/joined-name answer alongside the POSIX joined-thread ESRCH answer, and checks join/detach compatibility. - Negative control: replace only `Thread.cpp` with main's prior implementation and retain the PR's new test and other sources. The new test fails after 5.08 s. GDB catches its abort in `Require`/`main`; the optimized backtrace does not identify the inlined wait helper, so no more precise backtrace claim is made. This is behavioral negative-control evidence, not an independent ASan use-after-free report. - Conventions and whitespace checks pass. Merge-tree is clean against main `2742004ed28f765c7147db0e0269ff5868e9eb6f`; among the production sources under test, only the intended `Thread.cpp` additions differ from that main. Builds emit existing unused-function/parameter and missing-initializer warnings in unchanged code, plus LTO's serial-partition notice; no `-Werror` result is claimed. The registry lock is held through each protected access, with the name lock released before the registry lock on the name paths. The distinction between registered and live threads preserves the retained-object behavior covered above. I found no additional blocking source issue in this pass. I am leaving this as validation evidence while the existing debt-entry update requested by @oneandonlydean remains pending; these tests do not establish the unmeasured console results. This is target-level native Windows testing, not a full shared-libc/libkernel integration build, sanitizer/TSan run, console/game run or cross-PR composition test. No maintainer-triggered full CI is claimed. AI-assisted review and testing: yes (OpenAI Codex). <details> <summary>Out-of-tree replay files</summary> CMakeLists.txt: ```cmake cmake_minimum_required(VERSION 3.20) project(AnyPS5ThreadReview LANGUAGES CXX) enable_testing() set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-10816" CACHE PATH "Exact PR checkout") set(THREAD_SOURCE "${REPO}/core/libs/prx/libkernel/Pthread/src/Thread.cpp" CACHE FILEPATH "Thread source under test") add_library(thread_sources OBJECT "${THREAD_SOURCE}" "${REPO}/core/libs/prx/libkernel/Pthread/src/Attr.cpp" "${REPO}/core/libs/prx/libkernel/Pthread/src/Tsd.cpp" "${REPO}/core/libs/prx/libkernel/Pthread/src/Mutex.cpp" "${REPO}/core/libs/prx/libkernel/Pthread/src/Cond.cpp" "${REPO}/core/libs/prx/libkernel/Pthread/Posix/Thread.cpp" "${REPO}/core/libs/prx/libkernel/Time/TimedWait.cpp" "${REPO}/core/libs/prx/libkernel/Time/Time.cpp" "${REPO}/core/libs/prx/libkernel/Time/SleepWake.cpp" "${REPO}/core/libs/prx/libc/src/GuestAllocations.cpp" "${REPO}/core/libs/prx/libc/src/Threads.cpp" Support.cpp) target_compile_features(thread_sources PUBLIC cxx_std_20) target_include_directories(thread_sources PUBLIC "${REPO}/core/libs" "${REPO}/core/libs/prx/libkernel/Pthread/src") target_compile_options(thread_sources PUBLIC -O1 -g -Wall -Wextra -flto -ffunction-sections -fdata-sections) foreach(pair IN ITEMS "guest_pthread_handle_after_exit|GuestPthreadHandleAfterExit" "guest_pthread_getname|GuestPthreadGetname" "guest_pthread_join_detach|GuestPthreadJoinDetach") string(REPLACE "|" ";" parts "${pair}") list(GET parts 0 name) list(GET parts 1 source) add_executable(${name} "${REPO}/core/libs/tests/${source}.cpp") target_link_libraries(${name} PRIVATE thread_sources) target_link_options(${name} PRIVATE -flto -Wl,--gc-sections) add_test(NAME ${name} COMMAND ${name}) set_tests_properties(${name} PROPERTIES TIMEOUT 20) endforeach() ``` Support.cpp: ```cpp #include "prx/libc/include/Api.hpp" #include "prx/libc/include/General.hpp" #include <cerrno> #include <cstdlib> #include <stdexcept> [[maybe_unused]] const unsigned int abortFlags = _set_abort_behavior(0, _CALL_REPORTFAULT); extern "C" int* APS5_VABI __error_nid_postfix() { return &errno; } extern "C" [[noreturn]] void NotImplemented_nid_no_patch(const char* name) { throw std::runtime_error(name); } ``` Use GCC 16 UCRT64 bin first on PATH, followed by CMake/Ninja. Configure with `cmake -S native-thread-review -B native-thread-review/build16 -G Ninja -DREPO=<exact-PR-checkout> -DCMAKE_CXX_COMPILER=<GCC16-bin>/g++.exe -DCMAKE_BUILD_TYPE=Release`, build, then run `ctest --test-dir native-thread-review/build16 --output-on-failure --repeat until-fail:3`. For the negative control use a separate build directory with `-DTHREAD_SOURCE=<main-Thread.cpp-copy>` and run only `guest_pthread_handle_after_exit`. The extra original-source include directory preserves Thread.cpp's relative header paths when using that copy. </details>
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!10816
No description provided.