fix(libc): _Mtx_trylock returns 4 for a destroyed handle and locks a pointer to a null handle #18347
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/18347"
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 xXPBSXx on 2026-11-11T10:55:10Z.
What
_Mtx_trylockthrew for the handle of a destroyed mutex and for a pointer to a null handle. On a PS5 it returns 4 (_Thrd_error) for the destroyed mutex's stale handle and 0 for a pointer to a null handle (cases 1.9 and 4.2, lines 11 and 22 of the raw output). A null pointer makes the console fault (case 4.1, line 21)._Mtx_destroynow leaves the address of a static marker in the handle, and_Mtx_trylockreturns 4 for the marker and for a handle whose tag is not a live mutex's, which is what the console returned for the destroyed one. For a pointer to a null handle in writable memory it creates a plain mutex, stores it and locks it, returning 0; a null pointer and a null handle slot that cannot be written still throw, as onmain. The handle is read with__atomic_load_nnext to the compare-exchange that publishes the new mutex (Threads.cpp,ResolveMutexand_Mtx_trylock), and the slot is opened for a guest write withGuestArena::HostWritebefore the writability check, asGuestCopyOutdoes for a write-watched guest page. The tests pin both answers, a null handle in a read-only slot and a null handle in a write-watched page, and the entry for_Mtx_trylockis in the fragmentdocs/dev/debt/changes/fix-libc-mtx-trylock-null-and-destroyed-handle.md(the entry is 964 characters with its list marker);docs/dev/debt/libc.mdis not changed.That a pointer to a null handle gets a mutex made on demand is a guess: the probe measured only the return value 0, not what the console does with the handle. The tests pin the real sequence
_Mtx_init,_Mtx_destroy,_Mtx_trylockon one handle and, with zeroed storage, a handle that is not a live mutex; a handle that points to freed memory is not tested. That_Mtx_destroyleaves a marker is an implementation choice that gives the measured return value 4: what the console leaves in the handle after the destroy is not measured. PPSA06465 imports_Mtx_trylockfrom the system library at one call site (a registry read, not a run); 14 more titles import it but ship their ownlibc.prx. Whether PPSA06465 reaches the call with a destroyed or null handle is not shown. A title process was not measured.Tested
Measured on a PS5 with firmware 11.60 (
kernel_get_fw_version0x11600005), from a homebrew payload process (ps5-payload-sdk v0.45, elfldr), on 2026-11-11 at 06:00 UTC. A title process may differ. The cases are 1.2 to 4.2, lines 4 to 22 of the raw output in the first comment.mainbefore_Mtx_trylock(&handle)of a fresh plain mutex_Mtx_trylock(&handle)of a plain mutex the caller owns_Thrd_busy) (line 5)_Mtx_trylock(&handle)of a plain mutex held by another thread_Mtx_trylock(&handle)after_Mtx_destroy(stale handle)_Mtx_initand_Mtx_destroyof the same handle, and with zeroed storage)_Mtx_trylock(&handle)withhandlenull_Mtx_trylock(NULL)SIGSEGV(line 21)On
maince111157b8b3, Linux (WSL, Release), built for the targetsguest_libc_static_importsandguest_libc_threadswithninjareturning 0 for each commit: with only the test commitguest_libc_static_importsaborts (1 of the 4 mutex tests fails), and with the fix and with the documentation commit all four pass in 3 of 3 runs each.tools/check_conventions.pypasses on each of the three commits with no warning (the changed entry was 976 characters). The probe source and its raw output are in the first comment. On Windows 10 Pro 10.0.19045 (WinLibs GCC, Ninja, Release), on 2026-11-16 between 20:23 and 20:33 UTC, the build of the test commit4a3d0cab1f1calone finished withninjareturning 0 and 3 of the 9 mutex, condition variable, pad and forwarding tests failed (guest_libc_threads,guest_libc_static_imports,guest_libc_mutex_init_with_name), and the build of82402f2dc3b2finished withninjareturning 0 and all 9 passed. The Linux runs above are from before the destroyed-handle commits. The three review follow-ups were built and run on Windows (WinLibs MinGW-W64, Ninja, Release; one machine, the logs are kept locally and are not attached) on 2026-12-02: the atomic loads (ae3502724c3, 10 lines added and 5 removed inThreads.cpp) have no red arm, because on x86 the missing atomics cannot be seen without a thread sanitizer;guest_libc_threads_tests,guest_libc_static_imports_testsandguest_libc_mutex_init_with_name_testswere built (ninja returning 0) and each returned 0 in one run, at about 03:11 UTC. For the read-only slot, the test commit0372622ede6alone ona575ba6a9ad5madeguest_libc_threads_testscrash with an unhandled exception 0xc0000005 (a write) at about 05:00 UTC, and with the fix commitac188a9baf0it returned 0 in 3 of 3 runs, and the other two tests returned 0, at about 05:01 UTC. For the write-watched page, the test commit77d67f778d8alone onac188a9baf0ended instd::invalid_argument_Mtx_trylock: null mutex handle, then terminate and abort, at about 06:31 UTC, and with the fix commit378dd39ab94, the head of this branch,guest_libc_threads_testsreturned 0 in 3 of 3 runs and the other two tests returned 0, at about 06:32 UTC. Against a freshmainfc294cbbb5(fetched on 2026-12-02):tools/debt_fold.py --checkexits with 0;tools/check_conventions.py --base upstream/mainreports no findings;git merge-treeof the head with thatmainis clean. Not tested: Linux for the destroyed-handle commits and the follow-ups, macOS, the CI runner, a title process, any other firmware, the recursive and timed mutex types, a handle that points to freed memory, and what the console does with a null handle or leaves in a destroyed handle after the call.Overlap: counted on 2026-12-02 from the 2357 open pull requests (file lists from the GitHub API, the pull requests with 100 or more files read in full through the files API; the 1386 pull requests that change
core/libs/prx/libc/src/Threads.cpp,core/libs/tests/GuestLibcMutexInitWithName.cpp,core/libs/tests/GuestLibcStaticImports.cpp,core/libs/tests/GuestLibcThreads.cpp, a file underdocs/dev/debt/or the fragment path, or have mtx or mutex in the title or branch name, had their patches of the files underdocs/dev/debt/and of the files with libc, Threads or GuestLibc in the path searched for_Mtx_trylock,_Mtx_destroy,destroyedMutexMarkerand the fragment name, from 08:08 to 09:17 UTC,mainatfc294cbbb539at the start). No other open pull request changes the fragmentdocs/dev/debt/changes/fix-libc-mtx-trylock-null-and-destroyed-handle.md, and no patch of a debt file contains a searched name, so none changes the entry for_Mtx_trylock. Of the pull requests that share a file, #27937 (feat(libs): general system-library fixes from PS4 title bring-up,Threads.cpp) and #26252 and #26224 (GuestLibcStaticImports.cpp) merge cleanly with this head, and #19434 (feat(libSceLibcInternal): forward the firmware libc-internal export surface) declares_Mtx_destroy_nid_disambig1_nid_postfixinForwards.cppand merges cleanly; #12315 and #1835 changeThreads.cppand already conflict withmainalone in as many files, so not because of this change. The merges of this head with each of the 52 pull requests that change one of the files named or have a searched name were made withgit merge-treefrom 08:08 to 09:17 UTC: 36 are clean; the other 16 already conflict withmainalone, in at least as many files as with this head, so none of them conflicts because of this change. The count was repeated for the 147 pull requests that were opened or updated since 08:08 UTC (of the 2359 open pull requests, from 09:36 to 09:41 UTC; 99 of them were patch-scanned for the same names): the only one that shares a file is #12849 (libc.md), which already conflicts withmainalone in 2 files; no new hit. Two commits have been merged tomainsince68d65e6b14a(themainthat was merged into this branch;mainatfc294cbbb539); neither changed one of the files named, and a merge of this head intomainatfc294cbbb539was checked at 09:42 UTC and is clean. This pull request does not depend on any of them (Depends on: none).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)Summary by CodeRabbit
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-12T15:37:34Z.
Review: COMMENTED
Reviewed — no blocking findings
Nothing blocks this; the points below are optional.
Reason: at head
d4a259527021aed13d66c2a7e151291654304d10the change does what the description says in the code I read, and I found no concrete defect in the changed lines.What I ran
d4a259527021aed13d66c2a7e151291654304d10, basemain. Static reading only.Threads.cppalso read at head, lines 120–230 and 262–280.Results
Commands
The output is not reproduced here.
Findings
Blocking
None.
Non-blocking
core/libs/prx/libc/src/Threads.cpp:262: the tag check reads through*handleeven when that pointer is a stale copy._Mtx_destroy(Threads.cpp:227–229) frees the mutex and nulls only the handle it was given. If the freed memory is reused for another mutex, the check passes and_Mtx_trylocklocks that other mutex.ResolveMutex(Threads.cpp:175) already reads the same field, so this is not new; the change makes that path a deliberate return. Not reproduced. Suggest saying in the debt entry that a stale copy is not detected in general.core/libs/tests/GuestLibcStaticImports.cpp:126: the "destroyed handle" test uses zeroed storage and never runs_Mtx_destroyfollowed by a trylock. It pins the tag check, not the destroy path. The description says so, but the commit subject "for a destroyed handle" reads wider. Suggest a narrower wording.Sources
ResolveMutex:github.com/boykopovar/AnyPS5@d4a2595270/core/libs/prx/libc/src/Threads.cpp (L169-L178)_Mtx_destroy:github.com/boykopovar/AnyPS5@d4a2595270/core/libs/prx/libc/src/Threads.cpp (L219-L230)github.com/boykopovar/AnyPS5@d4a2595270/core/libs/prx/libc/src/Threads.cpp (L254-L263)github.com/boykopovar/AnyPS5@d4a2595270/core/libs/tests/GuestLibcStaticImports.cpp (L123-L132)Not verified
To get this to a good state
Nothing is required. The non-blocking points above are optional.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-14T01:50:29Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: make null-handle initialization safe when multiple callers try to initialize the same handle concurrently.
What I ran
Reviewed head
4af2351fd163765f1ce78ab7395c7d82b9f9197d. Read the prepared description, commits, manifest and diff, plus the full text of all three changed files and targeted mutex implementation and test context. No commands or tests were run.Results
Findings
Blocking
core/libs/prx/libc/src/Threads.cpp:260: The null-handle initialization uses an atomic compare-and-exchange to publish a newly allocated mutex, but the check at line 255 and subsequentResolveMutexread at line 265 access the samevoid*non-atomically. Concurrent calls can therefore race with the atomic publication, which is undefined behavior in C++. The losing caller deletes its allocation and then resolves the winner’s pointer, but that does not make the mixed atomic and non-atomic accesses safe. Synchronize all accesses to this handle consistently, or otherwise avoid concurrent initialization races.Non-blocking
None.
Not verified
No tests or builds were run. Author-reported PS5 and Linux results were not independently verified.
files.jsonwas unavailable through the review reader; the manifest lists all three changed files as included, and each was read. Title-process behavior, other firmware, and the unmeasured null-handle semantics described by the author remain unverified.To get this to a good state
Make null-handle initialization safe for concurrent callers, then rerun the relevant mutex tests and build checks.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-22T11:42:23Z.
Review: COMMENTED
Reviewed — comments
No blocking defect was verified in the reviewed files; independent test execution was unavailable, so a formal approval is not justified.
What I ran
Reviewed head
82402f2dc3b2459d5bba87149cebc99d74df86f0using the prepared diff andrepo_read.py. No commands or tests were run.Results
Findings
Blocking
None verified.
Non-blocking
_Mtx_trylockdereferences any non-null handle before it can return_Thrd_errorfor an invalid tag (core/libs/prx/libc/src/Threads.cpp:269). The tests cover zeroed storage, while behavior for a handle pointing to freed or otherwise invalid memory is unverified; that case may fault instead of returning 4.Sources
Reviewed
core/libs/prx/libc/src/Threads.cpp,core/libs/tests/GuestLibcMutexInitWithName.cpp,core/libs/tests/GuestLibcStaticImports.cpp,core/libs/tests/GuestLibcThreads.cpp, anddocs/dev/debt/libc.md. The diff was read fromreview/diff.patch; no changed files were excluded inreview/manifest.json.Not verified
Tests were not run independently. Console behavior beyond the author-reported payload measurements, including handles pointing to freed memory and title-process behavior, was not verified.
To get this to a good state
Nothing is required. Optional: add a test and document the expected behavior for handles pointing to freed or otherwise invalid memory.
Imported from boykopovar/AnyPS5. Originally posted by coderabbitai[bot] on 2026-12-02T04:03:44Z.
Review: COMMENTED
Actionable comments
std::atomic_reffor the handle loads and compare-exchange.core/libs/prx/libc/src/Threads.cpp, lines203· 📐 Maintainability & Code Quality · 💤 Low valueCONTRIBUTING.mdsays to avoid non-standard extensions where standard C++ is enough. The build requires C++20, sostd::atomic_ref<void*>provides the same atomic load and compare-exchange operations. It does not change the handle layout or ABI.std::atomic_ref<void*>at each handle access. Map each existing__ATOMIC_*order to itsstd::memory_orderequivalent, and keep the same order on each operation. Apply the same change to the other handle accesses in this publication path, at lines 294, 302, and 304.74725d92-dddb-4bf5-9ea9-d6beec41a4deReviewing files that changed from the base of the PR and between
68d65e6b14anda575ba6a9a.core/libs/prx/libc/src/Threads.cppcore/libs/tests/GuestLibcMutexInitWithName.cppcore/libs/tests/GuestLibcStaticImports.cppcore/libs/tests/GuestLibcThreads.cppdocs/dev/debt/libc.mdIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-12-02T04:21:12Z.
Review: APPROVED
Reviewed — looks good
The changed code and tests support the stated behavior, with no verified blocking findings.
What I ran
Reviewed head
a575ba6a9ad527648511d532679a287f9659d9e3using the prepared diff and included file snapshots. No tests or builds were run. The pinned reader could not complete because it attempted to write a read log in the read-only run folder.Results
Negative control
Not run; no tests were run during this review.
Findings
Blocking
None.
Non-blocking
None.
Sources
Threads.cppat the reviewed headNot verified
The author-reported test and build results were not reproduced. Console behavior beyond the reported payload process measurements, title-process behavior, other firmware, and the behavior of handles pointing to freed memory were not verified. The reviewed files were
Threads.cpp,GuestLibcMutexInitWithName.cpp,GuestLibcStaticImports.cpp,GuestLibcThreads.cpp, anddocs/dev/debt/libc.md;files.jsonlists no excluded files.To get this to a good state
Nothing is required.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-12-02T05:56:50Z.
Review: COMMENTED
Reviewed — no blocking findings
The diff contains no verified blocking defect, but the null-handle behavior remains an unmeasured compatibility assumption.
What I ran
Reviewed head
ac188a9baf03ba14802da76c1bbad1a3b900e2a8against the prepared diff and targeted source excerpts. No tests or builds were run. The reader returned the first source excerpt, then could not complete further calls because its logging write was blocked by the read-only filesystem.Commands attempted:
Results
Findings
Blocking
None verified.
Non-blocking
core/libs/prx/libc/src/Threads.cpp:297). The description says the console probe measured only a return value of 0, not whether it initializes the handle this way. This behavior is therefore an acknowledged but unverified compatibility assumption. Changed code at the reviewed headSources
The four changed files were inspected through their prepared diffs:
core/libs/prx/libc/src/Threads.cpp,core/libs/tests/GuestLibcMutexInitWithName.cpp,core/libs/tests/GuestLibcStaticImports.cpp, andcore/libs/tests/GuestLibcThreads.cpp. Targeted source context was read forThreads.cppand relevant test excerpts. The excluded filedocs/dev/debt/changes/fix-libc-mtx-trylock-null-and-destroyed-handle.mdwas not read.Not verified
Author-reported test and console results were not independently run. Full source context beyond the targeted excerpts was not read. The excluded debt-fragment file was not reviewed.
To get this to a good state
Nothing is required.
Imported from boykopovar/AnyPS5. Originally posted by coderabbitai[bot] on 2026-12-02T06:03:16Z.
Review: COMMENTED
Actionable comments
57bc63ef-fd79-48f9-826d-4da675bb3543Reviewing files that changed from the base of the PR and between
a575ba6a9aandac188a9baf.core/libs/prx/libc/src/Threads.cppcore/libs/tests/GuestLibcThreads.cppdocs/dev/debt/changes/fix-libc-mtx-trylock-null-and-destroyed-handle.mdIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-12-02T07:58:08Z.
Review: COMMENTED
Reviewed — comments
A complete approval is not justified because the full text of
Threads.cppwas not reviewed; the relevant changed sections were inspected.What I ran
Reviewed head
378dd39ab94171c3a616e8625daaf294d98e34d3. Read the prepared description, commits, manifest, diff, and files; inspected the changed mutex code and relevant test sections. No tests or builds were run. The pinned reader could not be used because it failed while trying to write its read log in the read-only workspace.Results
Threads.cppreview incompleteNegative control
Not run.
Findings
Blocking
None verified in the inspected sections.
Non-blocking
None.
Sources
The prepared diff and the three included test files were reviewed. No external or commit-pinned source links were available through the reader.
Not verified
The full text of
core/libs/prx/libc/src/Threads.cppwas not read; only relevant sections were inspected.docs/dev/debt/changes/fix-libc-mtx-trylock-null-and-destroyed-handle.mdwas excluded by rule. Tests, builds, and runtime behavior were not independently verified.To get this to a good state
Complete review of
Threads.cppbefore treating this as an approval. Files read:description.md,commits.md,manifest.json,diff.patch,files.json, the relevant sections ofcore/libs/prx/libc/src/Threads.cpp, and the full text of the three included test files. Files reviewed in the manifest: all four;Threads.cppwas only partially read. Excluded:docs/dev/debt/changes/fix-libc-mtx-trylock-null-and-destroyed-handle.md.Imported from boykopovar/AnyPS5. Originally posted by coderabbitai[bot] on 2026-12-02T08:01:26Z.
Review: COMMENTED
Actionable comments
d222dbdd-0432-496c-961c-2e23fa77b715Reviewing files that changed from the base of the PR and between
ac188a9bafand378dd39ab9.core/libs/prx/libc/src/Threads.cppcore/libs/tests/GuestLibcThreads.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T11:54:28Z.
Review: COMMENTED
Compiled the changed libc thread source and ran
GuestLibcMutexInitWithName,GuestLibcStaticImports, andGuestLibcThreadsagainst the existing Linux PRXs. All three passed, including the distinct results for destroyed mutex handles and null handle slots.AI-assisted: yes.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.