fix(libkernel): wait for an in-flight file measurement before closing a watched descriptor #11125

Merged
MarcZX10 merged 4 commits from upstream-pr/11125 into main 2026-10-27 12:30:55 +00:00
MarcZX10 commented 2026-10-25 18:55:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-25T18:55:33Z.


What

KernelEqueuePrivate::MeasureFiles gives EVFILT_READ on regular files its byte count. It copies the watched descriptor numbers under the queue mutex, unlocks, and calls sceKernelFstat and sceKernelLseek(…, SEEK_CUR) on them. close_nid_postfix removes the descriptor's events through EqueueDescriptorClosed → RemoveDescriptorEvents and then closes it, without waiting for a measurement that already copied that number. A waiter can therefore fstat/lseek a descriptor while another thread closes it, or after the number has been reused by a new open. The result for the removed event is thrown away, but the host-side fstat/lseek still 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 is close at File/src/Stdio.cpp:767; the read is fstat from UnreadFileBytes (Equeue/Equeue.cpp) under MeasureFiles.

MeasureFiles now records the descriptors it is measuring in m_measuring before it unlocks, and removes them and notifies m_measured once their results are stored. RemoveDescriptorEvents waits on m_measured until no in-flight measurement holds the descriptor, so close only 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 one fstat and one lseek, so the wait is short. Kqueue.cpp calls RemoveDescriptorEvents the same way and gets the same guarantee.

Tested

  • A ThreadSanitizer build on an ubuntu-latest fork runner (with the ANYPS5_ENABLE_TSAN option, not part of this pull request) ran guest_socket_events five times without and five times with this change. Without it, 4 of 5 runs failed with ThreadSanitizer: data race ... Stdio.cpp:767 in close_nid_postfix. With it, all 5 passed.
  • A normal RelWithDebInfo build on the same runner: guest_equeue_events, guest_kqueue and guest_socket_events pass. The local x86-64 host lacks AVX2 and BMI, so the libkernel guest tests cannot start there.
  • python3 tools/check_conventions.py --base upstream/main and git diff --check upstream/main pass. tools/pr_overlap.py --branch lists only pull requests that also edit Equeue.cpp or Equeue.hpp; none of them touches MeasureFiles or RemoveDescriptorEvents. Windows and macOS were not run.

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
  • 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 (not applicable; no third-party code added)
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5007678477 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11125). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-25T18:55:33Z. --- ### What `KernelEqueuePrivate::MeasureFiles` gives `EVFILT_READ` on regular files its byte count. It copies the watched descriptor numbers under the queue mutex, unlocks, and calls `sceKernelFstat` and `sceKernelLseek(…, SEEK_CUR)` on them. `close_nid_postfix` removes the descriptor's events through `EqueueDescriptorClosed` → `RemoveDescriptorEvents` and then closes it, without waiting for a measurement that already copied that number. A waiter can therefore `fstat`/`lseek` a descriptor while another thread closes it, or after the number has been reused by a new `open`. The result for the removed event is thrown away, but the host-side `fstat`/`lseek` still 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 is `close` at `File/src/Stdio.cpp:767`; the read is `fstat` from `UnreadFileBytes` (`Equeue/Equeue.cpp`) under `MeasureFiles`. `MeasureFiles` now records the descriptors it is measuring in `m_measuring` before it unlocks, and removes them and notifies `m_measured` once their results are stored. `RemoveDescriptorEvents` waits on `m_measured` until no in-flight measurement holds the descriptor, so `close` only 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 one `fstat` and one `lseek`, so the wait is short. `Kqueue.cpp` calls `RemoveDescriptorEvents` the same way and gets the same guarantee. ### Tested - A ThreadSanitizer build on an `ubuntu-latest` fork runner (with the `ANYPS5_ENABLE_TSAN` option, not part of this pull request) ran `guest_socket_events` five times without and five times with this change. Without it, 4 of 5 runs failed with `ThreadSanitizer: data race ... Stdio.cpp:767 in close_nid_postfix`. With it, all 5 passed. - A normal RelWithDebInfo build on the same runner: `guest_equeue_events`, `guest_kqueue` and `guest_socket_events` pass. The local x86-64 host lacks AVX2 and BMI, so the libkernel guest tests cannot start there. - `python3 tools/check_conventions.py --base upstream/main` and `git diff --check upstream/main` pass. `tools/pr_overlap.py --branch` lists only pull requests that also edit `Equeue.cpp` or `Equeue.hpp`; none of them touches `MeasureFiles` or `RemoveDescriptorEvents`. Windows and macOS were not run. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [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](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source (not applicable; no third-party code 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
thepoppfish commented 2026-10-25 19:14:51 +00:00 (Migrated from github.com)

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 in m_measuring. There is a second path before unlock: growing m_measuring for a second descriptor can throw after the first has already been registered. After the exception unwinds, RemoveDescriptorEvents waits 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/sceKernelLseek adapters 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 production GetTriggeredEvents and RemoveDescriptorEvents; it does not replace the measurement or waiting algorithm.

Results (one execution of each case per variant, 14 total):

Case Current head Proposed patch
One file, fail measured allocation (16 bytes) 1 stale entry; removal remains blocked 0 stale entries; removal completes
Two files, fail measured allocation (32 bytes) 2 stale entries; removal remains blocked 0 stale entries; removal completes
Two files, fail tracking growth (8 bytes) 1 stale entry; removal remains blocked 0 stale entries; removal completes
Throw at fstat boundary Stale entry; removal remains blocked Cleanup and completion
Throw at lseek boundary Stale entry; removal remains blocked Cleanup and completion
Removal already waiting when measurement throws Still blocked after measurement thread unwinds Waiter wakes and completes
Successful measurement held at a barrier Removal waits until measurement finishes Same correct wait

The first three cases are actual std::vector allocation 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=error accepts it on this exact head. The author's unchanged head passes conventions against current main ae7d59258ea77b090c6be392e2eb2872a9744d00 and git 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
--- a/core/libs/prx/libkernel/Equeue/Equeue.cpp
+++ b/core/libs/prx/libkernel/Equeue/Equeue.cpp
@@ -167,21 +167,33 @@
     if (files.empty()) {
         return;
     }
+    std::vector<UnreadFile> measured;
+    measured.reserve(files.size());
+    m_measuring.reserve(m_measuring.size() + files.size());
     for (const auto& [file, owner] : files) {
         m_measuring.push_back(file);
     }
+    const auto releaseMeasurements = [&] {
+        for (const auto& [file, owner] : files) {
+            m_measuring.erase(std::find(m_measuring.begin(), m_measuring.end(), file));
+        }
+        m_measured.notify_all();
+    };
     lock.unlock();
-    std::vector<UnreadFile> measured;
-    measured.reserve(files.size());
-    for (const auto& [file, owner] : files) {
-        measured.push_back(UnreadFileBytes(file));
+    try {
+        for (const auto& [file, owner] : files) {
+            measured.push_back(UnreadFileBytes(file));
+        }
+    } catch (...) {
+        lock.lock();
+        releaseMeasurements();
+        throw;
     }
     lock.lock();
     for (std::size_t i = 0; i < files.size(); ++i) {
         *static_cast<UnreadFile*>(files[i].second.get()) = measured[i];
-        m_measuring.erase(std::find(m_measuring.begin(), m_measuring.end(), files[i].first));
-    }
-    m_measured.notify_all();
+    }
+    releaseMeasurements();
 }
 
 void KernelEqueuePrivate::WakePollers() {
Complete standalone Windows reproduction sources

Keep the reviewed checkout unchanged at d8eab026acebed55b2ce213717172b6e17b3974f. Save the three files below in an external scratch directory. To produce FixedEqueue.cpp, apply the patch above in a second checkout at the same head and copy its core/libs/prx/libkernel/Equeue/Equeue.cpp into this scratch directory. Configure with cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DREPO=C:/absolute/path/to/unchanged/checkout, build with cmake --build build, then run python 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:

cmake_minimum_required(VERSION 3.20)
project(EqueueExceptionReview LANGUAGES CXX)
get_filename_component(DEFAULT_REPO "${CMAKE_CURRENT_LIST_DIR}/../review-11125" ABSOLUTE)
set(REPO "${DEFAULT_REPO}" CACHE PATH "Exact reviewed head")
foreach(variant IN ITEMS head fixed)
    if(variant STREQUAL head)
        set(source "${REPO}/core/libs/prx/libkernel/Equeue/Equeue.cpp")
    else()
        set(source "${CMAKE_CURRENT_LIST_DIR}/FixedEqueue.cpp")
    endif()
    add_executable(${variant}_probe Probe.cpp "${REPO}/core/libs/prx/libkernel/Time/TimedWait.cpp")
    target_compile_features(${variant}_probe PRIVATE cxx_std_20)
    target_compile_options(${variant}_probe PRIVATE -O1 -g -fno-inline -fno-lto -ffunction-sections -fdata-sections)
    target_compile_definitions(${variant}_probe PRIVATE EQUEUE_SOURCE="${source}")
    target_include_directories(${variant}_probe PRIVATE "${REPO}/core/libs" "${REPO}/core/libs/prx/libkernel/Equeue")
    target_link_options(${variant}_probe PRIVATE -static-libgcc -static-libstdc++ -Wl,--gc-sections)
    add_custom_command(TARGET ${variant}_probe POST_BUILD
        COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:${variant}_probe>" VERBATIM)
endforeach()

Probe.cpp:

#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <future>
#include <io.h>
#include <mutex>
#include <new>
#include <stdexcept>
#include <string>
#include <sys/stat.h>
#include <thread>
#include EQUEUE_SOURCE

thread_local std::size_t failSize = 0;
thread_local bool faultFired = false;
thread_local std::array<std::size_t, 64> allocationSizes{};
thread_local std::size_t allocationCount = 0;

void* operator new(std::size_t size) {
    if (failSize) {
        if (allocationCount < allocationSizes.size()) allocationSizes[allocationCount++] = size;
        if (size == failSize && !faultFired) {
            faultFired = true;
            throw std::bad_alloc();
        }
    }
    if (void* pointer = std::malloc(size ? size : 1)) return pointer;
    throw std::bad_alloc();
}
void* operator new[](std::size_t size) { return ::operator new(size); }
void operator delete(void* pointer) noexcept { std::free(pointer); }
void operator delete[](void* pointer) noexcept { std::free(pointer); }
void operator delete(void* pointer, std::size_t) noexcept { std::free(pointer); }
void operator delete[](void* pointer, std::size_t) noexcept { std::free(pointer); }

std::atomic<int> ioMode{0};
std::mutex gateMutex;
std::condition_variable gateChanged;
bool enteredFstat = false, releaseFstat = false;

[[noreturn]] void Unused(const char* name) { throw std::runtime_error(name); }

extern "C" int APS5_VABI sceKernelFstat(int descriptor, FileStat* status) {
    int expected = 1;
    if (ioMode.compare_exchange_strong(expected, 0)) throw std::bad_alloc();
    if (ioMode.load() == 3 || ioMode.load() == 4) {
        std::unique_lock lock(gateMutex);
        enteredFstat = true;
        gateChanged.notify_all();
        gateChanged.wait(lock, [] { return releaseFstat; });
        if (ioMode.load() == 4) throw std::bad_alloc();
    }
    struct _stat64 native{};
    const int result = ::_fstat64(descriptor, &native);
    if (result == 0) {
        status->st_size = native.st_size;
        status->st_mode = native.st_mode;
    }
    return result;
}
extern "C" std::int64_t APS5_VABI sceKernelLseek(int descriptor, std::int64_t offset, int whence) {
    if (ioMode.exchange(0) == 2) throw std::bad_alloc();
    return ::_lseeki64(descriptor, offset, whence);
}
extern "C" [[noreturn]] void NotImplemented_nid_no_patch(const char* name) { Unused(name); }
extern "C" void KernelTraceWait_nid_postfix(const char*, const void*, std::uint64_t, bool) { Unused("trace"); }
namespace File { bool IsHostStream(int) { Unused("host streams"); } }
namespace GuestSockets {
bool IsOpen(int) { Unused("socket open"); }
bool Listening(int) { Unused("socket listening"); }
bool Ready(int, bool, std::int64_t*, bool*) { Unused("socket ready"); }
bool PipeReadState(int, std::int64_t*, bool*) { Unused("pipe read"); }
std::uintptr_t CurrentWaker() { Unused("socket waker"); }
void Wake(std::uintptr_t) { Unused("socket wake"); }
bool WaitAny(const std::vector<Interest>&, std::uint64_t) { Unused("socket wait"); }
}
bool IsKqueueDescriptor(int) { Unused("kqueue descriptor"); }
void KqueueDescriptorClosed(int) { Unused("kqueue close"); }
std::optional<bool> KqueueReadable(int) { Unused("kqueue readable"); }
void RequireVnodeNotes(uint32_t) { Unused("vnode notes"); }
void SetVnodeNotes(KernelEqueueEvent&, uint32_t) { Unused("vnode set"); }
int AddVnodeEvent(const KernelEqueueRef&, int, uint32_t, uint16_t, void*) { Unused("vnode add"); }

template<class Tag, typename Tag::Type Member> struct Access {
    friend typename Tag::Type get(Tag) { return Member; }
};
struct TrackingTag { using Type = std::vector<int> KernelEqueuePrivate::*; friend Type get(TrackingTag); };
struct MutexTag { using Type = std::mutex KernelEqueuePrivate::*; friend Type get(MutexTag); };
struct MeasuredTag { using Type = std::condition_variable KernelEqueuePrivate::*; friend Type get(MeasuredTag); };
template struct Access<TrackingTag, &KernelEqueuePrivate::m_measuring>;
template struct Access<MutexTag, &KernelEqueuePrivate::m_mutex>;
template struct Access<MeasuredTag, &KernelEqueuePrivate::m_measured>;

std::size_t Tracking(KernelEqueuePrivate& queue, bool clear = false) {
    std::lock_guard lock(queue.*get(MutexTag{}));
    auto& tracked = queue.*get(TrackingTag{});
    const auto count = tracked.size();
    if (clear) {
        tracked.clear();
        (queue.*get(MeasuredTag{})).notify_all();
    }
    return count;
}

int main(int argc, char** argv) {
    if (argc != 3) return 20;
    const std::string scenario = argv[1];
    const bool concurrent = scenario == "normal-wait" || scenario == "waiting-throw-fstat";
    const bool multiple = scenario == "measured-two" || scenario == "tracking-two";
    std::array<FILE*, 2> files{};
    KernelEqueuePrivate queue(0);
    for (unsigned index = 0; index < (multiple ? 2u : 1u); ++index) {
        const auto path = std::string(argv[2]) + "/file" + std::to_string(index) + ".bin";
        files[index] = std::fopen(path.c_str(), "w+b");
        if (!files[index]) return 21;
        if (std::fwrite("payload", 1, 7, files[index]) != 7 || std::fflush(files[index]) != 0) return 22;
        ::_lseeki64(::_fileno(files[index]), 0, SEEK_SET);
        if (queue.AddEvent(FileEvent(::_fileno(files[index]), EVFILT_READ, EV_ADD, nullptr)) != 0) return 23;
    }
    bool caught = false;
    std::exception_ptr measurementError;
    std::thread measurer;
    if (concurrent) {
        ioMode = scenario == "normal-wait" ? 3 : 4;
        measurer = std::thread([&] {
            try { KernelEvent event{}; queue.GetTriggeredEvents(&event, 1); }
            catch (...) { measurementError = std::current_exception(); }
        });
        std::unique_lock lock(gateMutex);
        if (!gateChanged.wait_for(lock, std::chrono::seconds(3), [] { return enteredFstat; })) std::_Exit(24);
    } else {
        failSize = scenario == "measured-one" ? 16 : scenario == "measured-two" ? 32 : scenario == "tracking-two" ? 8 : 0;
        if (scenario == "throw-fstat") ioMode = 1;
        if (scenario == "throw-lseek") ioMode = 2;
        try { KernelEvent event{}; queue.GetTriggeredEvents(&event, 1); }
        catch (const std::bad_alloc&) { caught = true; }
        failSize = 0;
    }
    const auto remaining = Tracking(queue);
    const int descriptor = ::_fileno(files[0]);
    std::promise<void> closed;
    auto finished = closed.get_future();
    std::thread closer([&] { queue.RemoveDescriptorEvents(static_cast<uintptr_t>(descriptor)); closed.set_value(); });
    const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3);
    while (queue.HasEvent(static_cast<uintptr_t>(descriptor), EVFILT_READ)) {
        if (std::chrono::steady_clock::now() > deadline) std::_Exit(25);
        std::this_thread::yield();
    }
    const bool blocked = finished.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready;
    bool blockedAfterUnwind = false;
    if (concurrent) {
        { std::lock_guard lock(gateMutex); releaseFstat = true; }
        gateChanged.notify_all();
        measurer.join();
        if (measurementError) {
            try { std::rethrow_exception(measurementError); }
            catch (const std::bad_alloc&) { caught = true; }
        }
        if (scenario == "waiting-throw-fstat") {
            blockedAfterUnwind = finished.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready;
            if (Tracking(queue)) Tracking(queue, true);
        } else if (measurementError) {
            std::rethrow_exception(measurementError);
        }
    } else if (remaining) {
        Tracking(queue, true);
    }
    if (finished.wait_for(std::chrono::seconds(3)) != std::future_status::ready) std::_Exit(26);
    closer.join();
    const auto after = Tracking(queue);
    for (auto* file : files) if (file) std::fclose(file);
    const bool good = concurrent ? blocked && remaining == 1 && after == 0 && (scenario == "normal-wait" || (caught && !blockedAfterUnwind)) : caught && remaining == 0 && !blocked && after == 0;
    std::printf("{\"scenario\":\"%s\",\"caught_bad_alloc\":%s,\"allocation_fault_fired\":%s,\"tracked_after_failure_or_while_running\":%zu,\"removal_blocked\":%s,\"after_cleanup\":%zu,\"pass\":%s,\"allocation_sizes\":[",
                scenario.c_str(), caught ? "true" : "false", faultFired ? "true" : "false", remaining,
                blocked ? "true" : "false", after, good ? "true" : "false");
    for (std::size_t index = 0; index < allocationCount; ++index) std::printf("%s%zu", index ? "," : "", allocationSizes[index]);
    std::printf("],\"blocked_after_unwind\":%s}\n", blockedAfterUnwind ? "true" : "false");
    return good ? 0 : 1;
}

run.py:

import json
import os
from pathlib import Path
import subprocess
import tempfile

work = Path(__file__).resolve().parent
environment = dict(os.environ)
environment['PATH'] = environment['PATH']
results = []
for variant in ('head', 'fixed'):
    for scenario in ('measured-one', 'measured-two', 'tracking-two', 'throw-fstat', 'throw-lseek', 'normal-wait', 'waiting-throw-fstat'):
        with tempfile.TemporaryDirectory(prefix='equeue11125-', dir=work) as directory:
            result = subprocess.run([str(work / f'build/{variant}_probe.exe'), scenario, directory],
                                    capture_output=True, text=True, timeout=10, env=environment)
        record = dict(variant=variant, exit_code=result.returncode, stdout=result.stdout.strip(), stderr=result.stderr.strip())
        if result.stdout.strip():
            record['result'] = json.loads(result.stdout)
        results.append(record)
        print(json.dumps(record), flush=True)
(work / '11125-probe-results.json').write_text(json.dumps(results, indent=2) + '\n', encoding='utf-8')
for record in results:
    expected = 0 if record['variant'] == 'fixed' or record.get('result', {}).get('scenario') == 'normal-wait' else 1
    assert record['exit_code'] == expected, record
    data = record['result']
    assert data['after_cleanup'] == 0, record
    if data['scenario'] != 'normal-wait':
        assert data['caught_bad_alloc'], record
        if data['scenario'] in ('measured-one', 'measured-two', 'tracking-two'):
            assert data['allocation_fault_fired'], record
        if data['scenario'] == 'waiting-throw-fstat':
            assert data['removal_blocked'] and data['blocked_after_unwind'] == (record['variant'] == 'head'), record
        else:
            assert data['removal_blocked'] == (record['variant'] == 'head'), record
print('All 14 expected outcomes verified.')

AI-assisted review and proposed patch (OpenAI Codex).

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5644830647 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11125#pullrequestreview-5644830647). Originally posted by [thepoppfish](https://github.com/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 in `m_measuring`. There is a second path before unlock: growing `m_measuring` for a second descriptor can throw after the first has already been registered. After the exception unwinds, `RemoveDescriptorEvents` waits 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`/`sceKernelLseek` adapters 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 production `GetTriggeredEvents` and `RemoveDescriptorEvents`; it does not replace the measurement or waiting algorithm. Results (one execution of each case per variant, 14 total): | Case | Current head | Proposed patch | | --- | --- | --- | | One file, fail measured allocation (16 bytes) | 1 stale entry; removal remains blocked | 0 stale entries; removal completes | | Two files, fail measured allocation (32 bytes) | 2 stale entries; removal remains blocked | 0 stale entries; removal completes | | Two files, fail tracking growth (8 bytes) | 1 stale entry; removal remains blocked | 0 stale entries; removal completes | | Throw at fstat boundary | Stale entry; removal remains blocked | Cleanup and completion | | Throw at lseek boundary | Stale entry; removal remains blocked | Cleanup and completion | | Removal already waiting when measurement throws | Still blocked after measurement thread unwinds | Waiter wakes and completes | | Successful measurement held at a barrier | Removal waits until measurement finishes | Same correct wait | The first three cases are actual `std::vector` allocation 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=error` accepts it on this exact head. The author's unchanged head passes conventions against current main `ae7d59258ea77b090c6be392e2eb2872a9744d00` and `git 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. <details><summary>Tested production cleanup patch</summary> ```diff --- a/core/libs/prx/libkernel/Equeue/Equeue.cpp +++ b/core/libs/prx/libkernel/Equeue/Equeue.cpp @@ -167,21 +167,33 @@ if (files.empty()) { return; } + std::vector<UnreadFile> measured; + measured.reserve(files.size()); + m_measuring.reserve(m_measuring.size() + files.size()); for (const auto& [file, owner] : files) { m_measuring.push_back(file); } + const auto releaseMeasurements = [&] { + for (const auto& [file, owner] : files) { + m_measuring.erase(std::find(m_measuring.begin(), m_measuring.end(), file)); + } + m_measured.notify_all(); + }; lock.unlock(); - std::vector<UnreadFile> measured; - measured.reserve(files.size()); - for (const auto& [file, owner] : files) { - measured.push_back(UnreadFileBytes(file)); + try { + for (const auto& [file, owner] : files) { + measured.push_back(UnreadFileBytes(file)); + } + } catch (...) { + lock.lock(); + releaseMeasurements(); + throw; } lock.lock(); for (std::size_t i = 0; i < files.size(); ++i) { *static_cast<UnreadFile*>(files[i].second.get()) = measured[i]; - m_measuring.erase(std::find(m_measuring.begin(), m_measuring.end(), files[i].first)); - } - m_measured.notify_all(); + } + releaseMeasurements(); } void KernelEqueuePrivate::WakePollers() { ``` </details> <details><summary>Complete standalone Windows reproduction sources</summary> Keep the reviewed checkout unchanged at `d8eab026acebed55b2ce213717172b6e17b3974f`. Save the three files below in an external scratch directory. To produce `FixedEqueue.cpp`, apply the patch above in a second checkout at the same head and copy its `core/libs/prx/libkernel/Equeue/Equeue.cpp` into this scratch directory. Configure with `cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DREPO=C:/absolute/path/to/unchanged/checkout`, build with `cmake --build build`, then run `python 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`: ```cmake cmake_minimum_required(VERSION 3.20) project(EqueueExceptionReview LANGUAGES CXX) get_filename_component(DEFAULT_REPO "${CMAKE_CURRENT_LIST_DIR}/../review-11125" ABSOLUTE) set(REPO "${DEFAULT_REPO}" CACHE PATH "Exact reviewed head") foreach(variant IN ITEMS head fixed) if(variant STREQUAL head) set(source "${REPO}/core/libs/prx/libkernel/Equeue/Equeue.cpp") else() set(source "${CMAKE_CURRENT_LIST_DIR}/FixedEqueue.cpp") endif() add_executable(${variant}_probe Probe.cpp "${REPO}/core/libs/prx/libkernel/Time/TimedWait.cpp") target_compile_features(${variant}_probe PRIVATE cxx_std_20) target_compile_options(${variant}_probe PRIVATE -O1 -g -fno-inline -fno-lto -ffunction-sections -fdata-sections) target_compile_definitions(${variant}_probe PRIVATE EQUEUE_SOURCE="${source}") target_include_directories(${variant}_probe PRIVATE "${REPO}/core/libs" "${REPO}/core/libs/prx/libkernel/Equeue") target_link_options(${variant}_probe PRIVATE -static-libgcc -static-libstdc++ -Wl,--gc-sections) add_custom_command(TARGET ${variant}_probe POST_BUILD COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:${variant}_probe>" VERBATIM) endforeach() ``` `Probe.cpp`: ```cpp #include <array> #include <atomic> #include <chrono> #include <condition_variable> #include <cstdlib> #include <cstdio> #include <cstring> #include <future> #include <io.h> #include <mutex> #include <new> #include <stdexcept> #include <string> #include <sys/stat.h> #include <thread> #include EQUEUE_SOURCE thread_local std::size_t failSize = 0; thread_local bool faultFired = false; thread_local std::array<std::size_t, 64> allocationSizes{}; thread_local std::size_t allocationCount = 0; void* operator new(std::size_t size) { if (failSize) { if (allocationCount < allocationSizes.size()) allocationSizes[allocationCount++] = size; if (size == failSize && !faultFired) { faultFired = true; throw std::bad_alloc(); } } if (void* pointer = std::malloc(size ? size : 1)) return pointer; throw std::bad_alloc(); } void* operator new[](std::size_t size) { return ::operator new(size); } void operator delete(void* pointer) noexcept { std::free(pointer); } void operator delete[](void* pointer) noexcept { std::free(pointer); } void operator delete(void* pointer, std::size_t) noexcept { std::free(pointer); } void operator delete[](void* pointer, std::size_t) noexcept { std::free(pointer); } std::atomic<int> ioMode{0}; std::mutex gateMutex; std::condition_variable gateChanged; bool enteredFstat = false, releaseFstat = false; [[noreturn]] void Unused(const char* name) { throw std::runtime_error(name); } extern "C" int APS5_VABI sceKernelFstat(int descriptor, FileStat* status) { int expected = 1; if (ioMode.compare_exchange_strong(expected, 0)) throw std::bad_alloc(); if (ioMode.load() == 3 || ioMode.load() == 4) { std::unique_lock lock(gateMutex); enteredFstat = true; gateChanged.notify_all(); gateChanged.wait(lock, [] { return releaseFstat; }); if (ioMode.load() == 4) throw std::bad_alloc(); } struct _stat64 native{}; const int result = ::_fstat64(descriptor, &native); if (result == 0) { status->st_size = native.st_size; status->st_mode = native.st_mode; } return result; } extern "C" std::int64_t APS5_VABI sceKernelLseek(int descriptor, std::int64_t offset, int whence) { if (ioMode.exchange(0) == 2) throw std::bad_alloc(); return ::_lseeki64(descriptor, offset, whence); } extern "C" [[noreturn]] void NotImplemented_nid_no_patch(const char* name) { Unused(name); } extern "C" void KernelTraceWait_nid_postfix(const char*, const void*, std::uint64_t, bool) { Unused("trace"); } namespace File { bool IsHostStream(int) { Unused("host streams"); } } namespace GuestSockets { bool IsOpen(int) { Unused("socket open"); } bool Listening(int) { Unused("socket listening"); } bool Ready(int, bool, std::int64_t*, bool*) { Unused("socket ready"); } bool PipeReadState(int, std::int64_t*, bool*) { Unused("pipe read"); } std::uintptr_t CurrentWaker() { Unused("socket waker"); } void Wake(std::uintptr_t) { Unused("socket wake"); } bool WaitAny(const std::vector<Interest>&, std::uint64_t) { Unused("socket wait"); } } bool IsKqueueDescriptor(int) { Unused("kqueue descriptor"); } void KqueueDescriptorClosed(int) { Unused("kqueue close"); } std::optional<bool> KqueueReadable(int) { Unused("kqueue readable"); } void RequireVnodeNotes(uint32_t) { Unused("vnode notes"); } void SetVnodeNotes(KernelEqueueEvent&, uint32_t) { Unused("vnode set"); } int AddVnodeEvent(const KernelEqueueRef&, int, uint32_t, uint16_t, void*) { Unused("vnode add"); } template<class Tag, typename Tag::Type Member> struct Access { friend typename Tag::Type get(Tag) { return Member; } }; struct TrackingTag { using Type = std::vector<int> KernelEqueuePrivate::*; friend Type get(TrackingTag); }; struct MutexTag { using Type = std::mutex KernelEqueuePrivate::*; friend Type get(MutexTag); }; struct MeasuredTag { using Type = std::condition_variable KernelEqueuePrivate::*; friend Type get(MeasuredTag); }; template struct Access<TrackingTag, &KernelEqueuePrivate::m_measuring>; template struct Access<MutexTag, &KernelEqueuePrivate::m_mutex>; template struct Access<MeasuredTag, &KernelEqueuePrivate::m_measured>; std::size_t Tracking(KernelEqueuePrivate& queue, bool clear = false) { std::lock_guard lock(queue.*get(MutexTag{})); auto& tracked = queue.*get(TrackingTag{}); const auto count = tracked.size(); if (clear) { tracked.clear(); (queue.*get(MeasuredTag{})).notify_all(); } return count; } int main(int argc, char** argv) { if (argc != 3) return 20; const std::string scenario = argv[1]; const bool concurrent = scenario == "normal-wait" || scenario == "waiting-throw-fstat"; const bool multiple = scenario == "measured-two" || scenario == "tracking-two"; std::array<FILE*, 2> files{}; KernelEqueuePrivate queue(0); for (unsigned index = 0; index < (multiple ? 2u : 1u); ++index) { const auto path = std::string(argv[2]) + "/file" + std::to_string(index) + ".bin"; files[index] = std::fopen(path.c_str(), "w+b"); if (!files[index]) return 21; if (std::fwrite("payload", 1, 7, files[index]) != 7 || std::fflush(files[index]) != 0) return 22; ::_lseeki64(::_fileno(files[index]), 0, SEEK_SET); if (queue.AddEvent(FileEvent(::_fileno(files[index]), EVFILT_READ, EV_ADD, nullptr)) != 0) return 23; } bool caught = false; std::exception_ptr measurementError; std::thread measurer; if (concurrent) { ioMode = scenario == "normal-wait" ? 3 : 4; measurer = std::thread([&] { try { KernelEvent event{}; queue.GetTriggeredEvents(&event, 1); } catch (...) { measurementError = std::current_exception(); } }); std::unique_lock lock(gateMutex); if (!gateChanged.wait_for(lock, std::chrono::seconds(3), [] { return enteredFstat; })) std::_Exit(24); } else { failSize = scenario == "measured-one" ? 16 : scenario == "measured-two" ? 32 : scenario == "tracking-two" ? 8 : 0; if (scenario == "throw-fstat") ioMode = 1; if (scenario == "throw-lseek") ioMode = 2; try { KernelEvent event{}; queue.GetTriggeredEvents(&event, 1); } catch (const std::bad_alloc&) { caught = true; } failSize = 0; } const auto remaining = Tracking(queue); const int descriptor = ::_fileno(files[0]); std::promise<void> closed; auto finished = closed.get_future(); std::thread closer([&] { queue.RemoveDescriptorEvents(static_cast<uintptr_t>(descriptor)); closed.set_value(); }); const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3); while (queue.HasEvent(static_cast<uintptr_t>(descriptor), EVFILT_READ)) { if (std::chrono::steady_clock::now() > deadline) std::_Exit(25); std::this_thread::yield(); } const bool blocked = finished.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready; bool blockedAfterUnwind = false; if (concurrent) { { std::lock_guard lock(gateMutex); releaseFstat = true; } gateChanged.notify_all(); measurer.join(); if (measurementError) { try { std::rethrow_exception(measurementError); } catch (const std::bad_alloc&) { caught = true; } } if (scenario == "waiting-throw-fstat") { blockedAfterUnwind = finished.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready; if (Tracking(queue)) Tracking(queue, true); } else if (measurementError) { std::rethrow_exception(measurementError); } } else if (remaining) { Tracking(queue, true); } if (finished.wait_for(std::chrono::seconds(3)) != std::future_status::ready) std::_Exit(26); closer.join(); const auto after = Tracking(queue); for (auto* file : files) if (file) std::fclose(file); const bool good = concurrent ? blocked && remaining == 1 && after == 0 && (scenario == "normal-wait" || (caught && !blockedAfterUnwind)) : caught && remaining == 0 && !blocked && after == 0; std::printf("{\"scenario\":\"%s\",\"caught_bad_alloc\":%s,\"allocation_fault_fired\":%s,\"tracked_after_failure_or_while_running\":%zu,\"removal_blocked\":%s,\"after_cleanup\":%zu,\"pass\":%s,\"allocation_sizes\":[", scenario.c_str(), caught ? "true" : "false", faultFired ? "true" : "false", remaining, blocked ? "true" : "false", after, good ? "true" : "false"); for (std::size_t index = 0; index < allocationCount; ++index) std::printf("%s%zu", index ? "," : "", allocationSizes[index]); std::printf("],\"blocked_after_unwind\":%s}\n", blockedAfterUnwind ? "true" : "false"); return good ? 0 : 1; } ``` `run.py`: ```python import json import os from pathlib import Path import subprocess import tempfile work = Path(__file__).resolve().parent environment = dict(os.environ) environment['PATH'] = environment['PATH'] results = [] for variant in ('head', 'fixed'): for scenario in ('measured-one', 'measured-two', 'tracking-two', 'throw-fstat', 'throw-lseek', 'normal-wait', 'waiting-throw-fstat'): with tempfile.TemporaryDirectory(prefix='equeue11125-', dir=work) as directory: result = subprocess.run([str(work / f'build/{variant}_probe.exe'), scenario, directory], capture_output=True, text=True, timeout=10, env=environment) record = dict(variant=variant, exit_code=result.returncode, stdout=result.stdout.strip(), stderr=result.stderr.strip()) if result.stdout.strip(): record['result'] = json.loads(result.stdout) results.append(record) print(json.dumps(record), flush=True) (work / '11125-probe-results.json').write_text(json.dumps(results, indent=2) + '\n', encoding='utf-8') for record in results: expected = 0 if record['variant'] == 'fixed' or record.get('result', {}).get('scenario') == 'normal-wait' else 1 assert record['exit_code'] == expected, record data = record['result'] assert data['after_cleanup'] == 0, record if data['scenario'] != 'normal-wait': assert data['caught_bad_alloc'], record if data['scenario'] in ('measured-one', 'measured-two', 'tracking-two'): assert data['allocation_fault_fired'], record if data['scenario'] == 'waiting-throw-fstat': assert data['removal_blocked'] and data['blocked_after_unwind'] == (record['variant'] == 'head'), record else: assert data['removal_blocked'] == (record['variant'] == 'head'), record print('All 14 expected outcomes verified.') ``` </details> AI-assisted review and proposed patch (OpenAI Codex).
klosixgaming-arch commented 2026-10-25 21:45:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-25T21:45:50Z.

Review: DISMISSED


Reviewed head d8eab026ac by 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 reserve call.

What it does. MeasureFiles records the descriptors it is about to measure in m_measuring before it drops the lock, removes them and calls notify_all afterwards, and RemoveDescriptorEvents waits on m_measured until its descriptor is no longer being measured. That closes the race where a watched descriptor is closed while a measurement is reading it.

Problems:

  1. Exception safety (the reported one). If measured.reserve(files.size()) throws, the descriptors registered a few lines earlier stay in m_measuring for good. thepoppfish has a reproduction and a patch.
  2. It is the same for every throw in the unlocked region. Anything between lock.unlock() and lock.lock() that can throw (the push_back into measured, the measurement itself) has the same effect. The fix should not be "move reserve earlier"; it should be an RAII guard that owns the registration and removes it (and notifies) on every exit.
  3. The consequence is a hang, not a leak. RemoveDescriptorEvents waits with no timeout. A stale m_measuring entry 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.
  4. Lock-order check. The close path now waits for a measurement while it holds m_mutex through 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 what MeasureFiles calls while unlocked.
  5. A duplicate descriptor in files leaves two entries and std::find removes one per iteration, which works, but a std::multiset or 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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5645480095 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11125#pullrequestreview-5645480095). Originally posted by [klosixgaming-arch](https://github.com/klosixgaming-arch) on 2026-10-25T21:45:50Z. **Review:** DISMISSED --- Reviewed head `d8eab026ac` by 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 `reserve` call.** **What it does.** `MeasureFiles` records the descriptors it is about to measure in `m_measuring` before it drops the lock, removes them and calls `notify_all` afterwards, and `RemoveDescriptorEvents` waits on `m_measured` until its descriptor is no longer being measured. That closes the race where a watched descriptor is closed while a measurement is reading it. **Problems:** 1. **Exception safety (the reported one).** If `measured.reserve(files.size())` throws, the descriptors registered a few lines earlier stay in `m_measuring` for good. thepoppfish has a reproduction and a patch. 2. **It is the same for every throw in the unlocked region.** Anything between `lock.unlock()` and `lock.lock()` that can throw (the `push_back` into `measured`, the measurement itself) has the same effect. The fix should not be "move `reserve` earlier"; it should be an RAII guard that owns the registration and removes it (and notifies) on every exit. 3. **The consequence is a hang, not a leak.** `RemoveDescriptorEvents` waits with no timeout. A stale `m_measuring` entry 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. 4. **Lock-order check.** The close path now waits for a measurement while it holds `m_mutex` through 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 what `MeasureFiles` calls while unlocked. 5. A duplicate descriptor in `files` leaves two entries and `std::find` removes one per iteration, which works, but a `std::multiset` or 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.
adriadam10 commented 2026-10-27 03:18:02 +00:00 (Migrated from github.com)

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 to m_measuring before lock.unlock(), but nothing removes them if m_measuring.push_back, measured.reserve or measured.push_back (or the measurement itself) throws. The stale entries make every later RemoveDescriptorEvents for that descriptor wait forever. Reserve both vectors before registering, and own the registration with a guard that removes the entries under the lock and calls m_measured.notify_all() on every exit, as @thepoppfish's patch does.
  • Equeue.cpp:590: on Windows dup2_nid_postfix calls EqueueDescriptorClosed(to) while holding File::LockPositionedTransfer(to) (Stdio.cpp:838), and the in-flight measurement's sceKernelLseek blocks on that same lock, so dup2 onto a watched descriptor deadlocks (@wachi35676: hangs in 3/3 runs, main completes 20,000 rounds). Break the cycle, e.g. call EqueueDescriptorClosed(to) before taking the positioned lock in the Windows dup2, and add a dup2-onto-watched-descriptor case next to CloseWhileWaitingOnFile.

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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5661829955 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11125#pullrequestreview-5661829955). Originally posted by [adriadam10](https://github.com/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 to `m_measuring` before `lock.unlock()`, but nothing removes them if `m_measuring.push_back`, `measured.reserve` or `measured.push_back` (or the measurement itself) throws. The stale entries make every later `RemoveDescriptorEvents` for that descriptor wait forever. Reserve both vectors before registering, and own the registration with a guard that removes the entries under the lock and calls `m_measured.notify_all()` on every exit, as @thepoppfish's patch does. - `Equeue.cpp:590`: on Windows `dup2_nid_postfix` calls `EqueueDescriptorClosed(to)` while holding `File::LockPositionedTransfer(to)` (Stdio.cpp:838), and the in-flight measurement's `sceKernelLseek` blocks on that same lock, so `dup2` onto a watched descriptor deadlocks (@wachi35676: hangs in 3/3 runs, main completes 20,000 rounds). Break the cycle, e.g. call `EqueueDescriptorClosed(to)` before taking the positioned lock in the Windows `dup2`, and add a `dup2`-onto-watched-descriptor case next to `CloseWhileWaitingOnFile`. 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.
jotitadev commented 2026-10-27 05:37:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-27T05:37:49Z.

Review: COMMENTED


ThreadSanitizer run of the new head bef1faf9f on 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: main c3ee5a425. I merged it together with #10100 and #10810 for the run. Those two touch other files and other reports.

Baseline (main c3ee5a425): guest_socket_events reports the race in 10 of 10 runs, with two reports per run:

  • close (close_nid_postfix, Stdio.cpp:811, from CloseWhileWaitingOnFile) against fstat in DoFstat (NativeStat.cpp:83).
  • The same close against fstat in SharedMemoryLock (SharedMemory.cpp:718, through File::SeekShared).

With this PR:

  • guest_socket_events, which includes the new dup2 case, 10 repeated runs: 0 reports, passes.
  • Full non-GPU suite: no Equeue or descriptor report left and no new report in any test.

Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5662691827 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11125#pullrequestreview-5662691827). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-27T05:37:49Z. **Review:** COMMENTED --- ThreadSanitizer run of the new head `bef1faf9f` on 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: `main` `c3ee5a425`. I merged it together with #10100 and #10810 for the run. Those two touch other files and other reports. **Baseline (`main` `c3ee5a425`):** `guest_socket_events` reports the race in 10 of 10 runs, with two reports per run: - `close` (`close_nid_postfix`, Stdio.cpp:811, from `CloseWhileWaitingOnFile`) against `fstat` in `DoFstat` (NativeStat.cpp:83). - The same close against `fstat` in `SharedMemoryLock` (SharedMemory.cpp:718, through `File::SeekShared`). **With this PR:** - `guest_socket_events`, which includes the new dup2 case, 10 repeated runs: 0 reports, passes. - Full non-GPU suite: no Equeue or descriptor report left and no new report in any test. Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
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!11125
No description provided.