fix(libkernel): wait for an in-flight file measurement before closing a watched descriptor #11125
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/11125"
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 MarcZX10 on 2026-10-25T18:55:33Z.
What
KernelEqueuePrivate::MeasureFilesgivesEVFILT_READon regular files its byte count. It copies the watched descriptor numbers under the queue mutex, unlocks, and callssceKernelFstatandsceKernelLseek(…, SEEK_CUR)on them.close_nid_postfixremoves the descriptor's events throughEqueueDescriptorClosed→RemoveDescriptorEventsand then closes it, without waiting for a measurement that already copied that number. A waiter can thereforefstat/lseeka descriptor while another thread closes it, or after the number has been reused by a newopen. The result for the removed event is thrown away, but the host-sidefstat/lseekstill runs on a closed or unrelated file.ThreadSanitizer reports it in
guest_socket_events(CloseWhileWaitingOnFile, which closes watched files while a thread waits on the queue). The write iscloseatFile/src/Stdio.cpp:767; the read isfstatfromUnreadFileBytes(Equeue/Equeue.cpp) underMeasureFiles.MeasureFilesnow records the descriptors it is measuring inm_measuringbefore it unlocks, and removes them and notifiesm_measuredonce their results are stored.RemoveDescriptorEventswaits onm_measureduntil no in-flight measurement holds the descriptor, socloseonly reaches the host close after any measurement of that descriptor has finished. New measurements cannot pick the descriptor up again, because its events are already removed under the same lock. A measurement is onefstatand onelseek, so the wait is short.Kqueue.cppcallsRemoveDescriptorEventsthe same way and gets the same guarantee.Tested
ubuntu-latestfork runner (with theANYPS5_ENABLE_TSANoption, not part of this pull request) ranguest_socket_eventsfive times without and five times with this change. Without it, 4 of 5 runs failed withThreadSanitizer: data race ... Stdio.cpp:767 in close_nid_postfix. With it, all 5 passed.guest_equeue_events,guest_kqueueandguest_socket_eventspass. The local x86-64 host lacks AVX2 and BMI, so the libkernel guest tests cannot start there.python3 tools/check_conventions.py --base upstream/mainandgit diff --check upstream/mainpass.tools/pr_overlap.py --branchlists only pull requests that also editEqueue.cpporEqueue.hpp; none of them touchesMeasureFilesorRemoveDescriptorEvents. Windows and macOS were not run.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)Imported from boykopovar/AnyPS5. Originally posted by thepoppfish on 2026-10-25T19:14:51Z.
Review: DISMISSED
Reviewed exact head
d8eab026acebed55b2ce213717172b6e17b3974f. One exception-safety regression in the new in-flight tracking; I have a native reproduction and a tested cleanup patch below.If
measured.reserve(files.size())throws, all the newly registered descriptors stay inm_measuring. There is a second path before unlock: growingm_measuringfor a second descriptor can throw after the first has already been registered. After the exception unwinds,RemoveDescriptorEventswaits on those entries even though no measurement remains to erase them or notify it. If the caller catches the allocation failure, a later close/event removal can hang indefinitely. The tracking needs to be committed only after allocations succeed and retired on every exceptional exit from the unlocked measurement.On Windows 11 build 26200, GCC 16.2.0 UCRT, CMake 4.3.1/Ninja 1.13.2, I compiled the complete production Equeue.cpp and TimedWait.cpp into an external native harness. It uses actual regular files; the
sceKernelFstat/sceKernelLseekadapters delegate to_fstat64/_lseeki64. Ordinary global allocation is fault-injected inside the same statically linked C++ runtime. Socket/kqueue/vnode/trace paths outside this fixture throw if called. The test reaches productionGetTriggeredEventsandRemoveDescriptorEvents; it does not replace the measurement or waiting algorithm.Results (one execution of each case per variant, 14 total):
The first three cases are actual
std::vectorallocation failures; the I/O-boundary exceptions are additional injected unwind tests, not claims about a particular real syscall failure. In the already-waiting exception test, the closer is observed waiting before releasing the measurement barrier. The failing-head harness clears stale tracking only after recording the failed outcome, to join its helper thread safely. A normal measurement also proves the new waiting guarantee survives the patch.The patch reserves both vectors before adding entries, then reacquires the mutex, retires entries and notifies on the exceptional path before rethrowing.
git apply --check --whitespace=erroraccepts it on this exact head. The author's unchanged head passes conventions against current mainae7d59258ea77b090c6be392e2eb2872a9744d00andgit diff --check. This is a focused native review harness, not a full libkernel/guest/product build, TSAN run, Linux/macOS test, or game test. The CRT descriptor adapters do not validate guest file-mapper integration. Please include suitable regression coverage and rerun the relevant guest tests with the final change.Tested production cleanup patch
Complete standalone Windows reproduction sources
Keep the reviewed checkout unchanged at
d8eab026acebed55b2ce213717172b6e17b3974f. Save the three files below in an external scratch directory. To produceFixedEqueue.cpp, apply the patch above in a second checkout at the same head and copy itscore/libs/prx/libkernel/Equeue/Equeue.cppinto this scratch directory. Configure withcmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DREPO=C:/absolute/path/to/unchanged/checkout, build withcmake --build build, then runpython run.py. Put the MinGW UCRT runtime DLL directory on PATH. The objcopy step retains the Windows unwind section naming used by this toolchain. The runner expects the six fault cases to fail on head and all seven cases to pass with the patch; the ordinary barrier case passes on both.CMakeLists.txt:Probe.cpp:run.py:AI-assisted review and proposed patch (OpenAI Codex).
Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-25T21:45:50Z.
Review: DISMISSED
Reviewed head
d8eab026acby reading the diff and the existing review thread. I did not build or run this, so everything below is from the code, not from a test of mine.Requesting changes. I agree with thepoppfish's finding, and I think the problem is wider than the one
reservecall.What it does.
MeasureFilesrecords the descriptors it is about to measure inm_measuringbefore it drops the lock, removes them and callsnotify_allafterwards, andRemoveDescriptorEventswaits onm_measureduntil its descriptor is no longer being measured. That closes the race where a watched descriptor is closed while a measurement is reading it.Problems:
measured.reserve(files.size())throws, the descriptors registered a few lines earlier stay inm_measuringfor good. thepoppfish has a reproduction and a patch.lock.unlock()andlock.lock()that can throw (thepush_backintomeasured, the measurement itself) has the same effect. The fix should not be "movereserveearlier"; it should be an RAII guard that owns the registration and removes it (and notifies) on every exit.RemoveDescriptorEventswaits with no timeout. A stalem_measuringentry means a later close of that descriptor blocks forever. A guard fixes the cause, but a wait with no way out in a close path is worth a second look on its own.m_mutexthrough the condition variable's lock (it is released while waiting). The measurement runs outside the lock, which is good; please confirm it never needs a lock the closing thread holds. I could not tell from the diff whatMeasureFilescalls while unlocked.filesleaves two entries andstd::findremoves one per iteration, which works, but astd::multisetor a counter would say what is meant.The existing review from MarcZX10 and thepoppfish's patch are on the right track. Please apply the RAII version and add a test that forces a throw between registration and completion and then closes the descriptor.
AI-assisted: yes. Written with AI assistance and reviewed by me.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-27T03:18:02Z.
Review: CHANGES_REQUESTED
The race is real and the approach (track in-flight descriptors, wait in
RemoveDescriptorEvents) is right, but two problems need fixing before this can merge. Both were already reported in the thread and are confirmed from the diff:core/libs/prx/libkernel/Equeue/Equeue.cpp:170-177: the entries are added tom_measuringbeforelock.unlock(), but nothing removes them ifm_measuring.push_back,measured.reserveormeasured.push_back(or the measurement itself) throws. The stale entries make every laterRemoveDescriptorEventsfor that descriptor wait forever. Reserve both vectors before registering, and own the registration with a guard that removes the entries under the lock and callsm_measured.notify_all()on every exit, as @thepoppfish's patch does.Equeue.cpp:590: on Windowsdup2_nid_postfixcallsEqueueDescriptorClosed(to)while holdingFile::LockPositionedTransfer(to)(Stdio.cpp:838), and the in-flight measurement'ssceKernelLseekblocks on that same lock, sodup2onto a watched descriptor deadlocks (@wachi35676: hangs in 3/3 runs, main completes 20,000 rounds). Break the cycle, e.g. callEqueueDescriptorClosed(to)before taking the positioned lock in the Windowsdup2, and add adup2-onto-watched-descriptor case next toCloseWhileWaitingOnFile.Also please add a regression test in the tree: the TSAN result only exists in your fork run, and nothing in this diff fails without the change on a normal build.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-27T05:37:49Z.
Review: COMMENTED
ThreadSanitizer run of the new head
bef1faf9fon bare-metal Linux. This only covers the race itself; it does not address the exception-safety points from the earlier reviews.Setup: Ubuntu 26.04 x86-64 (i7-8700, not a VM), GCC 15.2,
-DANYPS5_ENABLE_TSAN=ON(the option from #11179), RelWithDebInfo,TSAN_OPTIONS=suppressions=tools/tsan-suppressions.txt. Base:mainc3ee5a425. I merged it together with #10100 and #10810 for the run. Those two touch other files and other reports.Baseline (
mainc3ee5a425):guest_socket_eventsreports the race in 10 of 10 runs, with two reports per run:close(close_nid_postfix, Stdio.cpp:811, fromCloseWhileWaitingOnFile) againstfstatinDoFstat(NativeStat.cpp:83).fstatinSharedMemoryLock(SharedMemory.cpp:718, throughFile::SeekShared).With this PR:
guest_socket_events, which includes the new dup2 case, 10 repeated runs: 0 reports, passes.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.