fix(libkernel): initialize guest rwlocks before they are shared #2275

Merged
mrk1987 merged 1 commit from upstream-pr/2275 into main 2026-10-10 04:46:25 +00:00
mrk1987 commented 2026-10-09 14:13:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by mrk1987 on 2026-10-09T14:13:51Z.


What

On Windows, guest pthread_rwlock_* locks can fail to exclude. Two threads can hold the write lock at the same time, or a reader can run during a write.

A guest rwlock is a PthreadRwlockPrivate holding a std::shared_timed_mutex, created lazily on the guest's first call. With MinGW-w64 libstdc++ that mutex wraps a winpthreads pthread_rwlock_t set to PTHREAD_RWLOCK_INITIALIZER, which winpthreads turns into a real lock on first use. That first use is not safe when it is concurrent (winpthreads rwlock.c):

  • rwlock_static_init returns EINVAL when it finds the lock already initialized. The second of two threads that both saw the initializer gets EINVAL from pthread_rwlock_wrlock/rdlock.
  • pthread_rwlock_init stores NULL before it publishes the new lock. A thread that reads it in that window also gets EINVAL.
  • libstdc++'s shared_timed_mutex::lock()/lock_shared() only __glibcxx_assert the result, so in release builds the failed lock returns as if it succeeded.

Standalone, on the project toolchain (GCC 15.2.0 x86_64-ucrt-posix-seh), with no AnyPS5 code involved:

  • Two threads racing their first pthread_rwlock_rdlock on a PTHREAD_RWLOCK_INITIALIZER lock: 19,991 of 20,000 rounds returned EINVAL.
  • Two threads racing their first lock() on a new std::shared_timed_mutex: both were inside the exclusive section in 1,732 of 20,000 rounds.

The guest rwlock is now locked and unlocked once in its constructor, on the creating thread, before any other thread can reach it, so the winpthreads lock exists before it is contended. docs/dev/TechnicalDebt.md records the winpthreads behaviour and the host std::shared_mutex objects that remain exposed.

guest_pthread_rwlock gets a case where two guest threads race their first pthread_rwlock_wrlock on a fresh lock, 500 times, and counts overlapping exclusive sections. On current main it fails (3/3 runs). With this change it passes (5/5 runs).

Tested

Windows 11, MinGW-w64 GCC 15.2.0, Release/Ninja on upstream main d70b8998.

  • guest_pthread_rwlock as above.
  • Full ctest: 507/507 pass (1 skipped: guest_video_out_wqhd_detection_no_vulkan).
  • tools/check_conventions.py and git diff --check pass.
  • A retail Unreal Engine title crashed nondeterministically in its worker threads during loading. A 32-way sharded map protected by pthread_rwlock was read while another thread inserted into it. CDB showed the lock's winpthreads handle as NULL while a thread was inside its write section. With this change that crash no longer occurs (0 of 2 runs; it had occurred in every run that reached that point).

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; no silent stubs added
  • No notes, investigation 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
  • AI-assisted: yes. The investigation, code, tests and this description were written by Claude (Claude Code), reviewed and run on my machine.

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4801622452 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2275). Originally posted by [mrk1987](https://github.com/mrk1987) on 2026-10-09T14:13:51Z. --- ### What On Windows, guest `pthread_rwlock_*` locks can fail to exclude. Two threads can hold the write lock at the same time, or a reader can run during a write. A guest rwlock is a `PthreadRwlockPrivate` holding a `std::shared_timed_mutex`, created lazily on the guest's first call. With MinGW-w64 libstdc++ that mutex wraps a winpthreads `pthread_rwlock_t` set to `PTHREAD_RWLOCK_INITIALIZER`, which winpthreads turns into a real lock on first use. That first use is not safe when it is concurrent ([winpthreads `rwlock.c`](https://github.com/mingw-w64/mingw-w64/blob/master/mingw-w64-libraries/winpthreads/src/rwlock.c)): - `rwlock_static_init` returns `EINVAL` when it finds the lock already initialized. The second of two threads that both saw the initializer gets `EINVAL` from `pthread_rwlock_wrlock`/`rdlock`. - `pthread_rwlock_init` stores `NULL` before it publishes the new lock. A thread that reads it in that window also gets `EINVAL`. - libstdc++'s `shared_timed_mutex::lock()`/`lock_shared()` only `__glibcxx_assert` the result, so in release builds the failed lock returns as if it succeeded. Standalone, on the project toolchain (GCC 15.2.0 `x86_64-ucrt-posix-seh`), with no AnyPS5 code involved: - Two threads racing their first `pthread_rwlock_rdlock` on a `PTHREAD_RWLOCK_INITIALIZER` lock: 19,991 of 20,000 rounds returned `EINVAL`. - Two threads racing their first `lock()` on a new `std::shared_timed_mutex`: both were inside the exclusive section in 1,732 of 20,000 rounds. The guest rwlock is now locked and unlocked once in its constructor, on the creating thread, before any other thread can reach it, so the winpthreads lock exists before it is contended. `docs/dev/TechnicalDebt.md` records the winpthreads behaviour and the host `std::shared_mutex` objects that remain exposed. `guest_pthread_rwlock` gets a case where two guest threads race their first `pthread_rwlock_wrlock` on a fresh lock, 500 times, and counts overlapping exclusive sections. On current `main` it fails (3/3 runs). With this change it passes (5/5 runs). ### Tested Windows 11, MinGW-w64 GCC 15.2.0, Release/Ninja on upstream main `d70b8998`. - `guest_pthread_rwlock` as above. - Full `ctest`: 507/507 pass (1 skipped: `guest_video_out_wqhd_detection_no_vulkan`). - `tools/check_conventions.py` and `git diff --check` pass. - A retail Unreal Engine title crashed nondeterministically in its worker threads during loading. A 32-way sharded map protected by `pthread_rwlock` was read while another thread inserted into it. CDB showed the lock's winpthreads handle as `NULL` while a thread was inside its write section. With this change that crash no longer occurs (0 of 2 runs; it had occurred in every run that reached that point). ### 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; no silent stubs added - [x] No notes, investigation 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] AI-assisted: yes. The investigation, code, tests and this description were written by Claude (Claude Code), reviewed and run on my machine. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Dextroid17 commented 2026-10-09 14:50:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Dextroid17 on 2026-10-09T14:50:06Z.

Review: COMMENTED


First, the bar this has to clear: a libkernel change is merged when a title and the log line where that title goes wrong are shown — and this body names no title. If the impact is genuinely universal rather than one title's (any Windows title that shares a guest rwlock between threads), say that explicitly and show the measurement: the project has merged universal-impact changes on exactly that basis, with an occurrence count or a backtrace. Right now the strongest available framing is unwritten.

Your cited mechanism is accurate — I checked it against the linked source rather than taking it on trust. In winpthreads rwlock.c:

/* rwlock_static_init */
if (*rw != PTHREAD_RWLOCK_INITIALIZER) { pthread_spin_unlock(&cond_locked); return EINVAL; }
r = pthread_rwlock_init (rw, NULL);

/* pthread_rwlock_init */
*rwlock_ = (pthread_rwlock_t)NULL;     /* before the new lock is published */
if ((rwlock = calloc(1, sizeof(*rwlock))) == NULL) return ENOMEM;

So the second of two threads that both see the initializer does get EINVAL, and the NULL store happens before publication. Both halves of the description check out.

What I measured on Linux (build clean, fresh test binary — I removed it first, since a stale one would have made this meaningless):

  • Arm A (PR head): guest_pthread_rwlock_tests passes (exit 0).
  • Arm B (only Pthread.hpp reverted to main, test kept): also passes (exit 0).

That is not a gap in the test — it is the shape of the defect. The test's assertion (overlaps == 0) is real, but on Linux the path under it cannot fail: the race is in winpthreads' static-init, which glibc's pthreads does not have. So the honest reading of my run is "no regression on Linux", not "the fix works" — the discriminating run is a Windows one, and there isn't one here.

Which also means I cannot confirm the TechnicalDebt.md entry removal from this box: it is justified exactly as far as the Windows fix is real.

Two notes that may help it land: the eager lock(); unlock(); in the constructor is the right place for it (the lock object is constructed before it can be shared, so no thread can observe an uninitialized shared_timed_mutex), and that is worth one sentence in the body — it is the part a reviewer will want to see argued rather than inferred.

Not verified here: the Windows symptom itself, and whether the winpthreads version bundled by the project's MinGW-w64 is the one this file describes.

Written with AI assistance.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5471653137 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2275#pullrequestreview-5471653137). Originally posted by [Dextroid17](https://github.com/Dextroid17) on 2026-10-09T14:50:06Z. **Review:** COMMENTED --- **First, the bar this has to clear:** a `libkernel` change is merged when a title and the log line where that title goes wrong are shown — and this body names no title. If the impact is genuinely universal rather than one title's (any Windows title that shares a guest rwlock between threads), say that explicitly and show the measurement: the project has merged universal-impact changes on exactly that basis, with an occurrence count or a backtrace. Right now the strongest available framing is unwritten. **Your cited mechanism is accurate** — I checked it against the linked source rather than taking it on trust. In winpthreads `rwlock.c`: ```c /* rwlock_static_init */ if (*rw != PTHREAD_RWLOCK_INITIALIZER) { pthread_spin_unlock(&cond_locked); return EINVAL; } r = pthread_rwlock_init (rw, NULL); /* pthread_rwlock_init */ *rwlock_ = (pthread_rwlock_t)NULL; /* before the new lock is published */ if ((rwlock = calloc(1, sizeof(*rwlock))) == NULL) return ENOMEM; ``` So the second of two threads that both see the initializer does get `EINVAL`, and the `NULL` store happens before publication. Both halves of the description check out. **What I measured on Linux** (build clean, fresh test binary — I removed it first, since a stale one would have made this meaningless): - Arm A (PR head): `guest_pthread_rwlock_tests` **passes** (exit 0). - Arm B (only `Pthread.hpp` reverted to `main`, test kept): **also passes** (exit 0). That is not a gap in the test — it is the shape of the defect. The test's assertion (`overlaps == 0`) is real, but on Linux the path under it cannot fail: the race is in winpthreads' static-init, which glibc's pthreads does not have. So the honest reading of my run is **"no regression on Linux"**, not "the fix works" — the discriminating run is a Windows one, and there isn't one here. Which also means I cannot confirm the `TechnicalDebt.md` entry removal from this box: it is justified exactly as far as the Windows fix is real. Two notes that may help it land: the eager `lock(); unlock();` in the constructor is the right place for it (the lock object is constructed before it can be shared, so no thread can observe an uninitialized `shared_timed_mutex`), and that is worth one sentence in the body — it is the part a reviewer will want to see argued rather than inferred. Not verified here: the Windows symptom itself, and whether the winpthreads version bundled by the project's MinGW-w64 is the one this file describes. Written with AI assistance.
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!2275
No description provided.