Skip to content

fix(libc): store _Mtx_init's and _Cnd_init's handles through checked guest copies - #24466

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
domx4q:fix/libc-mutex-condition-init-guest-pointers
Nov 27, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
domx4q:fix/libc-mutex-condition-init-guest-pointers

Conversation

@domx4q

@domx4q domx4q commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

What

_Mtx_init, _Cnd_init, _Cnd_destroy and std::__sce_v2::_Mtx_init_with_name (Threads.cpp) read and wrote the caller's handle slot (void**) straight through the guest pointer, so an unmapped or read-only slot crashed the host. The slot now goes through GuestCopyIn_nid_no_patch/GuestCopyOut_nid_no_patch, and an unusable slot throws std::invalid_argument, as a null slot already does:

  • _Mtx_init and _Cnd_init clear the slot before allocating, as before, so a rejected slot allocates nothing. If the final store of the new handle fails, the new object is freed before the throw. _Mtx_init_with_name, _Mtx_init_with_default_name_override and _Cnd_init_with_default_name_override forward to them and are covered too.
  • _Cnd_destroy copies the handle in and resolves it from the host copy. It clears the slot before freeing the condition, so a read-only slot throws and leaves the condition alive and usable instead of freeing it and then faulting.
  • std::__sce_v2::_Mtx_init_with_name (and _Mtx_init, which forwards to it) clears the slot with a checked write, so an unwritable slot throws before the libkernel scePthreadMutexInit call writes through it.

The mutex and condition objects themselves are host allocations owned by libc (new DinkumwareMutex/DinkumwareCondition), so the handle values are opaque host pointers, not guest memory. Only the slot that holds them is guest memory.

Results for valid slots are unchanged.

Not changed: _Mtx_destroy (open #18347 edits it), and the timed waits and Timespec64 helpers (#22515).

Tested

Arch Linux, GCC, Release build. Re-run after rebasing onto origin/main 0a025bd.

  • ctest --test-dir build -R '^(guest_ampr_threads|guest_cnd_at_thread_exit|guest_libc_cnd_init_default_name|guest_libc_cnd_timed_wait|guest_libc_internal_mtx|guest_libc_internal_pad|guest_libc_mutex_init_with_name|guest_libc_named_exports|guest_libc_shared_mutex|guest_libc_static_imports|guest_libc_threads|public_headers)$': passed.
  • New UnusableHandlePointers in GuestLibcThreads.cpp:
    • Each init function throws for an unmapped (0x10) slot and for a slot on a read-only page.
    • _Cnd_destroy throws for an unmapped slot and returns for a read-only slot holding null.
    • _Cnd_destroy on a read-only slot that holds a live condition throws. The condition still signals and is destroyed normally afterwards.
  • Mutation check (repeated after the rebase): ignoring the result of the _Mtx_init stores makes the new test abort.
  • python3 tools/progress.py --module libc: implemented count unchanged (1850).
  • python3 tools/guest_pointer_audit.py libc no longer lists the four functions.

tools/pr_overlap.py --branch fix/libc-mutex-condition-init-guest-pointers: #1835 and #9447 conflict with main and could not be compared. #9447 is a stale PR that adds std::__sce_v2::_Mtx_init_with_name, which main already implements. #1835 does not touch these functions.

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • 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
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (Claude Code)

…guest copies

_Mtx_init, _Cnd_init, _Cnd_destroy and std::__sce_v2::_Mtx_init_with_name
read and wrote the caller's handle slot straight through the guest
pointer, so an unmapped or read-only slot crashed the host. The slot is
now read with GuestCopyIn_nid_no_patch and written with
GuestCopyOut_nid_no_patch, and an unusable slot throws
std::invalid_argument, as a null slot already does.

_Mtx_init and _Cnd_init clear the slot before allocating, so a
rejected slot allocates nothing, and free the new object if the final
store fails. _Cnd_destroy clears the slot before it frees the
condition, so a read-only slot leaves the condition alive.

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against a4af382870:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_libc_threads_tests built cleanly.
  • CTest (guest_libc_threads):
    1/1 Test #1298: guest_libc_threads ...............   Passed    0.51 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libc/src/Threads.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #1298: guest_libc_threads ...............***Exception: SegFault  3.48 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Threads.cpp: _Mtx_init_nid_postfix correctly validates and writes nullptr to the guest handle slot before allocating DinkumwareMutex, and if the second GuestCopyOut fails, it deallocates the mutex before throwing std::invalid_argument to prevent leaks.
    • Threads.cpp: _Cnd_init_nid_postfix similarly tests handle writability by writing nullptr prior to allocation and frees DinkumwareCondition on secondary GuestCopyOut failure.
    • Threads.cpp: _Cnd_destroy_nid_postfix safely reads current handle with GuestCopyIn, verifies non-null, checks writability by clearing handle slot with GuestCopyOut BEFORE destroying condition to avoid leaving a dangling pointer if unwritable.
    • Threads.cpp: std::__sce_v2::_Mtx_init_with_name clears the guest mutex slot using GuestCopyOut before invoking sync.mutexattrInit / scePthreadMutexInit, preventing unmapped/read-only pointer faults.
    • GuestLibcThreads.cpp: UnusableHandlePointers test exercises read-only and unmapped pointers across all modified functions on both POSIX (mprotect) and Windows (VirtualProtect) without leaking resources or leaving dirty state.

Looks Good To Me

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — no blocking findings

The changed code and tests at head a4af382870aacf105785e345e35ea06c29ad4d85 show no verified blocking defect; I could not run the reported checks in this review session.

What I ran

Read the prepared diff and all changed lines in both changed files at the pinned head. No commands or tests were run.

Results

Check Result Note
Changed lines reviewed passed Both changed files read
Author-reported test suite not run Pass reported in the description
Review-session tests not run No command execution available

Findings

Blocking

None.

Non-blocking

None.

Not verified

I did not run the test suite, mutation check, or reported audit tools. The author reports these passed on Arch Linux with GCC in a Release build. No files were excluded from the supplied changed-file listing; core/libs/prx/libc/src/Threads.cpp and core/libs/tests/GuestLibcThreads.cpp were read.

To get this to a good state

Nothing is required.

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 1835 core/libs/prx/libc/src/Threads.cpp

@Helldiverr

Helldiverr commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Windows test run of a4af382 merged onto current main: guest_libc_threads passes 3/3. main's Threads.cpp with the new test crashes with a SegFault. Of 8 source mutations, 6 are caught. The other 2 each drop one of the two _Mtx_init stores, and the remaining store still rejects the same slot.

Existing runs. PrivacyOnion ran the test and the same negative control on Linux at a4af382. The PR body reports Arch Linux runs. I found no Windows run at this head.

What this run adds. The read-only slots here come from VirtualAlloc/VirtualProtect, the Windows branch of ReadOnlyHandleSlot. This run also adds source mutations and a small coverage pin.

Code.

  • _Mtx_init (core/libs/prx/libc/src/Threads.cpp:202-218) and _Cnd_init (:318-333) clear the slot through GuestCopyOut_nid_no_patch before allocating. They store the new handle with a second checked copy, which frees the object if it fails (:213-216, :328-331).
    • In a single-threaded test, the second check can only fail if the slot's protection changes between the two copies, so its delete is unreachable here (m2).
    • Without the first check, the second check still rejects the slot and frees the object (m1). The only difference is one extra allocation, and on out-of-memory threadNomem comes back instead of the throw.
    • Dropping both checks is caught (m3, m4).
  • _Cnd_destroy (:351-365) reads the handle with GuestCopyIn_nid_no_patch, resolves it from the host copy, and clears the slot before delete.
    • Restoring the old order, which frees first and then writes, ends in a heap-corruption exit (0xc0000374). After the throw, the test keeps using the condition (core/libs/tests/GuestLibcThreads.cpp:678-681), so the test does pin the order.
  • std::__sce_v2::_Mtx_init_with_name (:869-872) clears the slot with a checked write before scePthreadMutexInit. Without the check, the unmapped slot crashes (m8).

PR body. One line is broader than the test. The body says each init function throws "for an unmapped (0x10) slot and for a slot on a read-only page". Each entry point in UnusableHandlePointers is called with only one of the two slots (GuestLibcThreads.cpp:664-671), and _Mtx_init_with_default_name_override and _Cnd_init_with_name are not called there. The code handles both slots for all of them; the pin below runs the full matrix.

Suggestion. One loop, which I added locally only, after GuestLibcThreads.cpp:671:

    for (void** const slot : {unmapped, readOnlyNull}) {
        RequireThrows<std::invalid_argument>([&] { _Mtx_init_nid_postfix(slot, plain); });
        RequireThrows<std::invalid_argument>([&] { _Mtx_init_with_name_nid_postfix(slot, plain, "slot"); });
        RequireThrows<std::invalid_argument>([&] { _Mtx_init_with_default_name_override_nid_postfix(slot, plain, "slot"); });
        RequireThrows<std::invalid_argument>([&] { _Cnd_init_nid_postfix(slot); });
        RequireThrows<std::invalid_argument>([&] { _Cnd_init_with_name_nid_postfix(slot, "slot"); });
        RequireThrows<std::invalid_argument>([&] { _Cnd_init_with_default_name_override_nid_postfix(slot, "slot"); });
        RequireThrows<std::invalid_argument>([&] { _ZNSt8__sce_v219_Mtx_init_with_nameEPP13pthread_mutexiPKc_nid_postfix(slot, plain, "slot"); });
        RequireThrows<std::invalid_argument>([&] { _ZNSt8__sce_v29_Mtx_initEPP13pthread_mutexi_nid_postfix(slot, plain); });
    }

With the loop, the merge passes 3/3. The loop catches no extra mutation. It only makes the test match the body.

Negative control and mutations. Each row is one change to Threads.cpp on the merge, run once with the head test.

change runs result
main's Threads.cpp 1 SegFault, caught
m1: ignore the result of the first _Mtx_init store (:206-207) 1 passes; equivalent apart from out-of-memory (see Code)
m2: ignore the result of the final _Mtx_init store (:213-216) 1 passes; unreachable single-threaded
m3: ignore both _Mtx_init stores 1 abort (0xc0000409), caught
m4: ignore both _Cnd_init stores (:322-323, :328-331) 1 abort (0xc0000409), caught
m5: _Cnd_destroy reads *handle directly (:355-356) 1 SegFault, caught
m6: _Cnd_destroy frees before clearing the slot (old order) 1 heap corruption (0xc0000374), caught
m7: ignore the result of the _Cnd_destroy clear (:361-362) 1 abort (0xc0000409), caught
m8: ignore the result of the __sce_v2::_Mtx_init_with_name clear (:871-872) 1 SegFault, caught

Tests.

test main merge 1 merge 2 merge 3
guest_libc_threads Passed Passed Passed Passed

On main, the test is main's own GuestLibcThreads.cpp, without UnusableHandlePointers.

On the merge, tools/check_conventions.py --base upstream/main passes with no findings, and tools/debt_fold.py --check exits 0.

  • CPU: Ryzen 9 9950X3D
  • OS: Windows 11 Pro 26300
  • Toolchain: WinLibs GCC 15.2, Release
  • Commits: head a4af382870, merged onto main 34f08a2bce as 842b7f895b

AI-assisted: yes

@maskym

maskym commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Windows result for head a4af382870, merged alone into main 2b09db6f11 (the PR's Tested section names no Windows run).

Host: Windows 11 26300, Intel i7-12700K, WinLibs GCC 15.2.0 (x86_64-ucrt-posix-seh, r6), Release, BUILD_TESTING=ON, Ninja. Build clean.

guest_libc_threads, the test this PR adds or extends, passes 3 of 3 runs. Not run on a PS5.

AI-assisted: yes (Claude Code), the runs and the numbers above are from this machine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants