fix(libc): switch update streams to reading as FreeBSD does #8226

Merged
dantdmdarealguy merged 1 commit from upstream-pr/8226 into main 2026-10-21 06:57:36 +00:00
dantdmdarealguy commented 2026-10-20 04:45:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by dantdmdarealguy on 2026-10-20T04:45:06Z.


What

An r+, w+ or a+ stream that is read directly after a write, without fflush or a seek in between, loses the write on both hosts.

  • Windows: the UCRT does not switch the stream from writing to reading. A guest fread directly after an fwrite returned bytes still sitting in the write buffer, and the next flush wrote them over the file at the wrong offset. ungetc also failed on an update stream that was not already reading.
  • Linux: glibc switches only inside __uflow/__underflow, and two paths skip that:
    • ungetc puts the byte in glibc's backup area while the stream is still writing. The AB write is lost; fgetc then gives Z and EOF (glibc 2.39), or __uflow aborts with double free or corruption (out) (glibc 2.43).
    • An fread of at least the stream buffer size resets the write pointers and reads straight from the descriptor. It drops the pending write and returns the bytes from the old offset: fwrite("AB") then fread(..., 65536) on 0123456789 returns 0123456789, and the file is unchanged.

FreeBSD switches the stream itself. __srefill (which fread calls for every refill, whatever the size) and __ungetc both act before reading from an __SRW stream: they flush pending output with __sflush, clear __SWR and set __SRD, and they return EOF if the flush fails.

  • FileStream::SwitchToReading (and an unlocked variant for getc_unlocked) does the same on both hosts. On an update stream that is not reading, it flushes pending output under the stream lock and marks the stream as reading. A failed flush fails the read, as in FreeBSD.
    • On Windows it uses _fflush_nolock and sets the UCRT's reading flag.
    • On glibc it acts only on a stream that is readable and writable and is currently writing (__freadable, __fwriting). It calls _IO_switch_to_get_mode, the step glibc's own __uflow takes before reading: it flushes, returns EOF and sets the error indicator if the flush fails, and leaves put mode. glibc has exported it since GLIBC_2.2.5. Calling fflush alone first is not enough, because the stream stays in put mode and the next read after ungetc still corrupts the heap.
  • fread, fgetc, getc, getc_unlocked, fgets, ungetc, ungetwc and fscanf call it first. ungetc(EOF) does not, because FreeBSD returns before touching the stream.
  • On Windows, writes directly after reads still go through the UCRT. That gap is recorded in docs/dev/debt/libc.md.

file_streams now runs these checks directly after an fwrite on r+:

  • fread of 3 bytes and fread of 65536 bytes (more than the stream buffer);
  • fgetc, getc_unlocked, fgets, ungetc and fscanf.

It also checks fread on w+ and fgetc on a+. Each check verifies the bytes read, the error indicator and the final file contents. Finally it checks ungetc on a fresh r+ stream and after fseek.

The test fails on main on both hosts and passes with the change:

  • Windows: abort, 0xc0000409, "fread after fwrite on an r+ stream read other bytes".
  • Linux: abort, "fread of more than the stream buffer after fwrite on an r+ stream".

Tested

Windows 11 Pro, Intel Core i9-14900K, 128 GB RAM, NVIDIA GeForce RTX 5080 (driver 32.0.16.1742), WinLibs GCC 15.2.0, Release, BUILD_TESTING=ON, rebased on main 30fda0a03:

  • file_streams: fails on main libc 3 of 3 runs ("fread after fwrite on an r+ stream read other bytes") and passes with the change.
  • ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)": 6 of 6 pass, 3 runs out of 3.
  • ctest -R 'stream|stdio|scanf|printf|guest_file|fopen|fseek|wchar|libc|ungetc|guest_fdopendir|guest_filesystem|patched_libraries': 30 of 30 pass.
  • ctest -E '^agc_|^hardware_oracle$': 916 of 916 pass (14 VideoOut tests skipped).
  • The full build stops only at agc_driver_image_array_window_past_layer_limit (alignas(65536) exceeds the MinGW object-file maximum; that is broken on main, and #8310 fixes it). Every other target builds, and so does --target libs.

Arch Linux (WSL2, kernel 6.18.54), GCC 16.1.1, glibc 2.43, Release, BUILD_TESTING=ON, built in the Linux filesystem:

  • file_streams with the PR's previous head and its test (the review's setup) aborts 3 runs out of 3 with double free or corruption (out). The abort is in __uflow under the fgetc right after the first ungetc_nid_postfix call, which is the ungetc-after-fwrite case.
  • With this change, the PR's previous test passes 3 runs out of 3.
  • The new test fails 3 runs out of 3 with main libc and with the previous head ("fread of more than the stream buffer after fwrite on an r+ stream"). It passes 3 runs out of 3 with the change.
  • A plain C program against glibc 2.43 reproduces the review's result: ungetc after fwrite gives Z, EOF, ftell -1, and the file stays 0123456789. Calling fflush first aborts with double free or corruption (out). Calling _IO_switch_to_get_mode first gives Z, 2, ftell 3 and AB23456789. fread after fwrite("AB") is correct for 3 and 4095 bytes; for 4096, 8192 and 65536 bytes it returns 0123456789 and the file stays unchanged.
  • ctest -R 'stream|stdio|...|patched_libraries' (same pattern): 23 of 23 pass (agc_driver_stream_copy skipped).
  • ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)": 6 of 6 pass.
  • Full ctest: 1702 of 1702 pass, 1242 of them skipped (WSL has no Vulkan device).

tools/check_conventions.py --base origin/main and tools/check_test_registration.py pass. No title or homebrew 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
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes, some AI assistance was used
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4931128694 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8226). Originally posted by [dantdmdarealguy](https://github.com/dantdmdarealguy) on 2026-10-20T04:45:06Z. --- ### What An `r+`, `w+` or `a+` stream that is read directly after a write, without `fflush` or a seek in between, loses the write on both hosts. - **Windows:** the UCRT does not switch the stream from writing to reading. A guest `fread` directly after an `fwrite` returned bytes still sitting in the write buffer, and the next flush wrote them over the file at the wrong offset. `ungetc` also failed on an update stream that was not already reading. - **Linux:** glibc switches only inside `__uflow`/`__underflow`, and two paths skip that: - `ungetc` puts the byte in glibc's backup area while the stream is still writing. The `AB` write is lost; `fgetc` then gives `Z` and EOF (glibc 2.39), or `__uflow` aborts with `double free or corruption (out)` (glibc 2.43). - An `fread` of at least the stream buffer size resets the write pointers and reads straight from the descriptor. It drops the pending write and returns the bytes from the old offset: `fwrite("AB")` then `fread(..., 65536)` on `0123456789` returns `0123456789`, and the file is unchanged. FreeBSD switches the stream itself. [`__srefill`](https://github.com/freebsd/freebsd-src/blob/d106002967eff712894ab8b5337bbbff106ce5e0/lib/libc/stdio/refill.c) (which [`fread`](https://github.com/freebsd/freebsd-src/blob/d106002967eff712894ab8b5337bbbff106ce5e0/lib/libc/stdio/fread.c#L100-L106) calls for every refill, whatever the size) and [`__ungetc`](https://github.com/freebsd/freebsd-src/blob/d106002967eff712894ab8b5337bbbff106ce5e0/lib/libc/stdio/ungetc.c#L113-L128) both act before reading from an `__SRW` stream: they flush pending output with `__sflush`, clear `__SWR` and set `__SRD`, and they return `EOF` if the flush fails. - `FileStream::SwitchToReading` (and an unlocked variant for `getc_unlocked`) does the same on both hosts. On an update stream that is not reading, it flushes pending output under the stream lock and marks the stream as reading. A failed flush fails the read, as in FreeBSD. - On Windows it uses `_fflush_nolock` and sets the UCRT's reading flag. - On glibc it acts only on a stream that is readable and writable and is currently writing (`__freadable`, `__fwriting`). It calls `_IO_switch_to_get_mode`, the step glibc's own `__uflow` takes before reading: it flushes, returns `EOF` and sets the error indicator if the flush fails, and leaves put mode. glibc has exported it since `GLIBC_2.2.5`. Calling `fflush` alone first is not enough, because the stream stays in put mode and the next read after `ungetc` still corrupts the heap. - `fread`, `fgetc`, `getc`, `getc_unlocked`, `fgets`, `ungetc`, `ungetwc` and `fscanf` call it first. `ungetc(EOF)` does not, because FreeBSD returns before touching the stream. - On Windows, writes directly after reads still go through the UCRT. That gap is recorded in `docs/dev/debt/libc.md`. `file_streams` now runs these checks directly after an `fwrite` on `r+`: - `fread` of 3 bytes and `fread` of 65536 bytes (more than the stream buffer); - `fgetc`, `getc_unlocked`, `fgets`, `ungetc` and `fscanf`. It also checks `fread` on `w+` and `fgetc` on `a+`. Each check verifies the bytes read, the error indicator and the final file contents. Finally it checks `ungetc` on a fresh `r+` stream and after `fseek`. The test fails on `main` on both hosts and passes with the change: - Windows: abort, 0xc0000409, "fread after fwrite on an r+ stream read other bytes". - Linux: abort, "fread of more than the stream buffer after fwrite on an r+ stream". ### Tested Windows 11 Pro, Intel Core i9-14900K, 128 GB RAM, NVIDIA GeForce RTX 5080 (driver 32.0.16.1742), WinLibs GCC 15.2.0, Release, `BUILD_TESTING=ON`, rebased on `main` `30fda0a03`: - `file_streams`: fails on `main` libc 3 of 3 runs ("fread after fwrite on an r+ stream read other bytes") and passes with the change. - `ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)"`: 6 of 6 pass, 3 runs out of 3. - `ctest -R 'stream|stdio|scanf|printf|guest_file|fopen|fseek|wchar|libc|ungetc|guest_fdopendir|guest_filesystem|patched_libraries'`: 30 of 30 pass. - `ctest -E '^agc_|^hardware_oracle$'`: 916 of 916 pass (14 VideoOut tests skipped). - The full build stops only at `agc_driver_image_array_window_past_layer_limit` (`alignas(65536)` exceeds the MinGW object-file maximum; that is broken on `main`, and #8310 fixes it). Every other target builds, and so does `--target libs`. Arch Linux (WSL2, kernel 6.18.54), GCC 16.1.1, glibc 2.43, Release, `BUILD_TESTING=ON`, built in the Linux filesystem: - `file_streams` with the PR's previous head and its test (the review's setup) aborts 3 runs out of 3 with `double free or corruption (out)`. The abort is in `__uflow` under the `fgetc` right after the first `ungetc_nid_postfix` call, which is the `ungetc`-after-`fwrite` case. - With this change, the PR's previous test passes 3 runs out of 3. - The new test fails 3 runs out of 3 with `main` libc and with the previous head ("fread of more than the stream buffer after fwrite on an r+ stream"). It passes 3 runs out of 3 with the change. - A plain C program against glibc 2.43 reproduces the review's result: `ungetc` after `fwrite` gives `Z`, EOF, `ftell` -1, and the file stays `0123456789`. Calling `fflush` first aborts with `double free or corruption (out)`. Calling `_IO_switch_to_get_mode` first gives `Z`, `2`, `ftell` 3 and `AB23456789`. `fread` after `fwrite("AB")` is correct for 3 and 4095 bytes; for 4096, 8192 and 65536 bytes it returns `0123456789` and the file stays unchanged. - `ctest -R 'stream|stdio|...|patched_libraries'` (same pattern): 23 of 23 pass (`agc_driver_stream_copy` skipped). - `ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)"`: 6 of 6 pass. - Full `ctest`: 1702 of 1702 pass, 1242 of them skipped (WSL has no Vulkan device). `tools/check_conventions.py --base origin/main` and `tools/check_test_registration.py` pass. No title or homebrew 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 - [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, some AI assistance was used
github-actions[bot] commented 2026-10-20 04:59:38 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-20T04:59:38Z.


Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 4627 core/libs/prx/libc/src/StandardStreams.cpp L88
PR 8550 core/libs/prx/libc/include/FileStream.hpp L18, L214
PR 8658 core/libs/prx/libc/src/StandardStreams.cpp L88

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

Pull request Shared files not compared
PR 3965 docs/dev/debt/libc.md
PR 5021 core/libs/prx/libc/include/FileStream.hpp
core/libs/prx/libc/src/StandardStreams.cpp
docs/dev/debt/libc.md
PR 6044 core/libs/tests/FileStreams.cpp
PR 6226 docs/dev/debt/libc.md
PR 6469 docs/dev/debt/libc.md
PR 6819 docs/dev/debt/libc.md
PR 7081 core/libs/prx/libc/src/FileAndHeap.cpp
docs/dev/debt/libc.md
PR 7201 core/libs/prx/libc/include/FileStream.hpp
core/libs/prx/libc/src/FileAndHeap.cpp
core/libs/prx/libc/src/StandardStreams.cpp
PR 7648 docs/dev/debt/libc.md
PR 7715 docs/dev/debt/libc.md
PR 8150 core/libs/prx/libc/src/StandardStreams.cpp
core/libs/tests/FileStreams.cpp
docs/dev/debt/libc.md
PR 8520 docs/dev/debt/libc.md
PR 8711 docs/dev/debt/libc.md
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6283755655 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8226#issuecomment-6283755655). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-20T04:59:38Z. --- <!-- pr-overlap --> Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in **Depends on**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | [PR 4627](https://www.github.com/boykopovar/AnyPS5/pull/4627) | `core/libs/prx/libc/src/StandardStreams.cpp` [L88](https://github.com/boykopovar/AnyPS5/blob/eb9f904d32ece402660286aed2cecf465094da07/core/libs/prx/libc/src/StandardStreams.cpp#L88) | | | | [PR 8550](https://www.github.com/boykopovar/AnyPS5/pull/8550) | `core/libs/prx/libc/include/FileStream.hpp` [L18](https://github.com/boykopovar/AnyPS5/blob/eb9f904d32ece402660286aed2cecf465094da07/core/libs/prx/libc/include/FileStream.hpp#L18), [L214](https://github.com/boykopovar/AnyPS5/blob/eb9f904d32ece402660286aed2cecf465094da07/core/libs/prx/libc/include/FileStream.hpp#L214) | | | | [PR 8658](https://www.github.com/boykopovar/AnyPS5/pull/8658) | `core/libs/prx/libc/src/StandardStreams.cpp` [L88](https://github.com/boykopovar/AnyPS5/blob/eb9f904d32ece402660286aed2cecf465094da07/core/libs/prx/libc/src/StandardStreams.cpp#L88) | | | Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap. | Pull request | Shared files not compared | |---|---| | [PR 3965](https://www.github.com/boykopovar/AnyPS5/pull/3965) | `docs/dev/debt/libc.md` | | [PR 5021](https://www.github.com/boykopovar/AnyPS5/pull/5021) | `core/libs/prx/libc/include/FileStream.hpp`<br>`core/libs/prx/libc/src/StandardStreams.cpp`<br>`docs/dev/debt/libc.md` | | [PR 6044](https://www.github.com/boykopovar/AnyPS5/pull/6044) | `core/libs/tests/FileStreams.cpp` | | [PR 6226](https://www.github.com/boykopovar/AnyPS5/pull/6226) | `docs/dev/debt/libc.md` | | [PR 6469](https://www.github.com/boykopovar/AnyPS5/pull/6469) | `docs/dev/debt/libc.md` | | [PR 6819](https://www.github.com/boykopovar/AnyPS5/pull/6819) | `docs/dev/debt/libc.md` | | [PR 7081](https://www.github.com/boykopovar/AnyPS5/pull/7081) | `core/libs/prx/libc/src/FileAndHeap.cpp`<br>`docs/dev/debt/libc.md` | | [PR 7201](https://www.github.com/boykopovar/AnyPS5/pull/7201) | `core/libs/prx/libc/include/FileStream.hpp`<br>`core/libs/prx/libc/src/FileAndHeap.cpp`<br>`core/libs/prx/libc/src/StandardStreams.cpp` | | [PR 7648](https://www.github.com/boykopovar/AnyPS5/pull/7648) | `docs/dev/debt/libc.md` | | [PR 7715](https://www.github.com/boykopovar/AnyPS5/pull/7715) | `docs/dev/debt/libc.md` | | [PR 8150](https://www.github.com/boykopovar/AnyPS5/pull/8150) | `core/libs/prx/libc/src/StandardStreams.cpp`<br>`core/libs/tests/FileStreams.cpp`<br>`docs/dev/debt/libc.md` | | [PR 8520](https://www.github.com/boykopovar/AnyPS5/pull/8520) | `docs/dev/debt/libc.md` | | [PR 8711](https://www.github.com/boykopovar/AnyPS5/pull/8711) | `docs/dev/debt/libc.md` |
wachi35676 commented 2026-10-20 11:29:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-20T11:29:24Z.


The new file_streams checks fail on Linux. The description leaves Linux out ("glibc already switches"), but the checks are not under #ifdef _WIN32, so they run there too.

Head 33e08f16a merged onto main 02fb1ce53 (clean merge).

Windows 11 (10.0.26300), Ryzen 5 9600X, WinLibs GCC 15.2.0 UCRT, Release, BUILD_TESTING=ON:

  • ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)": 6 of 6 pass, 3 runs out of 3.
  • With the four changed libc sources reverted to main, file_streams aborts with fread after fwrite on an r+ stream read other bytes, as the description says.

Ubuntu 24.04 (WSL2), GCC 13.3, glibc 2.39, Release, BUILD_TESTING=ON, same merge:

  • file_streams aborts with ungetc after fwrite on an r+ stream pushed back other bytes, 3 runs out of 3. It fails the same way with the libc sources reverted, so the cause is glibc's behaviour, not this change.

  • With only that ungetc-after-fwrite case removed from the test, file_streams passes on Linux. That covers fread, fgetc, getc_unlocked, fgets, fscanf, w+, a+, and ungetc on a new stream and after fseek.

A plain C program against glibc 2.39, with no AnyPS5 code, shows the cause. The file holds 0123456789, is opened with r+b, and the program calls fwrite("AB", 1, 2, f), then ungetc('Z', f), fgetc and fgetc. It gets Z, then EOF; ftell returns -1; and the file is still 0123456789 afterwards, so the AB write is lost. FreeBSD's __ungetc flushes the pending write first, which is what the check expects: Z, 2, and a file holding AB23456789.

So on Linux, ungetc directly after a write drops the buffered output. That is the same class of bug this PR fixes on Windows, and glibc does not handle it. Two ways forward: make ungetc/ungetwc flush pending output on Linux too, or limit that check to Windows and record the glibc gap in debt/libc.md. The linux CI job was skipped on this PR, so CI has not caught this.

AI-assisted: yes (Claude Code); results above were run on this machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6289839337 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8226#issuecomment-6289839337). Originally posted by [wachi35676](https://github.com/wachi35676) on 2026-10-20T11:29:24Z. --- The new `file_streams` checks fail on Linux. The description leaves Linux out ("glibc already switches"), but the checks are not under `#ifdef _WIN32`, so they run there too. Head `33e08f16a` merged onto `main` `02fb1ce53` (clean merge). **Windows 11 (10.0.26300), Ryzen 5 9600X, WinLibs GCC 15.2.0 UCRT, Release, `BUILD_TESTING=ON`:** - `ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)"`: 6 of 6 pass, 3 runs out of 3. - With the four changed libc sources reverted to `main`, `file_streams` aborts with `fread after fwrite on an r+ stream read other bytes`, as the description says. **Ubuntu 24.04 (WSL2), GCC 13.3, glibc 2.39, Release, `BUILD_TESTING=ON`, same merge:** - `file_streams` aborts with `ungetc after fwrite on an r+ stream pushed back other bytes`, 3 runs out of 3. It fails the same way with the libc sources reverted, so the cause is glibc's behaviour, not this change. - With only that `ungetc`-after-`fwrite` case removed from the test, `file_streams` passes on Linux. That covers `fread`, `fgetc`, `getc_unlocked`, `fgets`, `fscanf`, `w+`, `a+`, and `ungetc` on a new stream and after `fseek`. A plain C program against glibc 2.39, with no AnyPS5 code, shows the cause. The file holds `0123456789`, is opened with `r+b`, and the program calls `fwrite("AB", 1, 2, f)`, then `ungetc('Z', f)`, `fgetc` and `fgetc`. It gets `Z`, then EOF; `ftell` returns -1; and the file is still `0123456789` afterwards, so the `AB` write is lost. FreeBSD's `__ungetc` flushes the pending write first, which is what the check expects: `Z`, `2`, and a file holding `AB23456789`. So on Linux, `ungetc` directly after a write drops the buffered output. That is the same class of bug this PR fixes on Windows, and glibc does not handle it. Two ways forward: make `ungetc`/`ungetwc` flush pending output on Linux too, or limit that check to Windows and record the glibc gap in `debt/libc.md`. The `linux` CI job was skipped on this PR, so CI has not caught this. AI-assisted: yes (Claude Code); results above were run on this machine.
dantdmdarealguy commented 2026-10-20 13:39:15 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by dantdmdarealguy on 2026-10-20T13:39:15Z.


Thanks, reproduced on Arch Linux (WSL2, glibc 2.43). There the ungetc-after-fwrite case is worse than on 2.39: the next fgetc aborts in __uflow with double free or corruption (out), 3 runs out of 3.

I took the first option. On glibc, SwitchToReading now does what FreeBSD's __ungetc and __srefill do. On a stream that is readable and writable and currently writing (__freadable and __fwriting), it calls _IO_switch_to_get_mode, the step glibc's own __uflow takes before a read. That flushes, fails the call (EOF and the error indicator) if the flush fails, and leaves put mode. Calling fflush alone is not enough: the stream stays in put mode, and your plain C program then aborts with the same double free.

While checking this I found that glibc also drops a pending write on an fread of at least the buffer size. After fwrite("AB"), fread(..., 65536) returns 0123456789 from offset 0, and the file is unchanged. FreeBSD's fread goes through __srefill whatever the size. The same switch fixes it, and file_streams now checks a 65536-byte fread too.

Linux, head fb604675b on main 30fda0a03, GCC 16.1.1, glibc 2.43, Release:

  • Before (previous head with its test): file_streams aborts 3/3 with double free or corruption (out) in the fgetc after the first ungetc.
  • After: the previous test passes 3/3 and the new test passes 3/3. The new test fails 3/3 with main libc ("fread of more than the stream buffer after fwrite on an r+ stream").
  • ^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem): 6/6 pass. The full ctest passes (no Vulkan device in WSL, so GPU tests skip).

Windows (same commit): your set passes 6/6, 3 runs out of 3.

Description updated with Linux in What and Tested.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6292205778 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8226#issuecomment-6292205778). Originally posted by [dantdmdarealguy](https://github.com/dantdmdarealguy) on 2026-10-20T13:39:15Z. --- Thanks, reproduced on Arch Linux (WSL2, glibc 2.43). There the `ungetc`-after-`fwrite` case is worse than on 2.39: the next `fgetc` aborts in `__uflow` with `double free or corruption (out)`, 3 runs out of 3. I took the first option. On glibc, `SwitchToReading` now does what FreeBSD's `__ungetc` and `__srefill` do. On a stream that is readable and writable and currently writing (`__freadable` and `__fwriting`), it calls `_IO_switch_to_get_mode`, the step glibc's own `__uflow` takes before a read. That flushes, fails the call (`EOF` and the error indicator) if the flush fails, and leaves put mode. Calling `fflush` alone is not enough: the stream stays in put mode, and your plain C program then aborts with the same double free. While checking this I found that glibc also drops a pending write on an `fread` of at least the buffer size. After `fwrite("AB")`, `fread(..., 65536)` returns `0123456789` from offset 0, and the file is unchanged. FreeBSD's `fread` goes through `__srefill` whatever the size. The same switch fixes it, and `file_streams` now checks a 65536-byte `fread` too. Linux, head `fb604675b` on `main` `30fda0a03`, GCC 16.1.1, glibc 2.43, Release: - Before (previous head with its test): `file_streams` aborts 3/3 with `double free or corruption (out)` in the `fgetc` after the first `ungetc`. - After: the previous test passes 3/3 and the new test passes 3/3. The new test fails 3/3 with `main` libc ("fread of more than the stream buffer after fwrite on an r+ stream"). - `^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)`: 6/6 pass. The full `ctest` passes (no Vulkan device in WSL, so GPU tests skip). Windows (same commit): your set passes 6/6, 3 runs out of 3. Description updated with Linux in What and Tested.
wachi35676 commented 2026-10-20 14:07:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-20T14:07:45Z.


Confirmed on glibc 2.39 as well. The Linux failure from my earlier comment is gone at fb604675b.

Head fb604675b merged onto main 19fcab22e (clean merge). Release, BUILD_TESTING=ON, no warnings in either build log.

Ubuntu 24.04 (WSL2), GCC 13.3, glibc 2.39:

  • ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)": 6 of 6 pass, 3 runs out of 3. They also pass with MALLOC_CHECK_=3 and glibc.malloc.perturb=165.
  • Negative control: with the four libc sources set back to main, file_streams aborts with fread of more than the stream buffer after fwrite on an r+ stream.

Windows 11, WinLibs GCC 15.2.0 UCRT: the same 6 of 6 pass, 3 runs out of 3. With the libc sources set back to main, the test aborts with fread after fwrite on an r+ stream read other bytes.

I also added a probe to FileStreams.cpp that goes through the guest *_nid_postfix functions. Each case reads the file back with a separate fopen after fclose.

Case Linux Windows
r+: fwrite("AB"), ungetc('Z'), fgetc ×2 ftell 1 → 2 → 3, bytes Z, 2, file AB23456789 same
same, then fseek(0, SEEK_CUR), fwrite("CD") ftell 5, file AB2CD56789 same
r+: fwrite, fgetc, fseek(END), fwrite("XY") file AB23456789XY same
a+: fwrite("AB"), ungetc('Z'), fgetc ×2 ftell 12, Z, then EOF with no error, file 0123456789AB same
a+: fwrite, fseek(0), fgetc, fwrite("X") '0', ftell 13, file 0123456789ABX same
a+: fwrite, fread(65536) 0 bytes, EOF, ftell 12 same
20 seeded runs of 3000 mixed fwrite/fread/fgetc/ungetc/fseek calls on r+ (sizes up to 12000 bytes), checked against a model after every call all match, 3 runs out of 3 (Linux with MALLOC_CHECK_=3) all match

With main libc, the same probe aborts on Linux with munmap_chunk(): invalid pointer. On Windows it fails 29 checks.

Memory errors: valgrind is not installed in my WSL, so I used AddressSanitizer and UBSan instead. I built a standalone program that makes the same glibc calls as SwitchToReading (__freadable, __fwriting, _IO_switch_to_get_mode) before every read and ran the same cases with them. It reports no errors, 3 runs out of 3. Without the switch, ASan stops in the first case with attempting free on address which was not malloc()-ed in __uflow → _IO_free_backup_area. That is the double free you saw on 2.43.

Windows-only difference, not caused by this PR: after ungetc at offset 0 and an fgetc of that byte, ftell returns 1; Linux returns 0. The next byte is still the right one. main gives the same 1 on a new rb stream, so this comes from the UCRT.

#8150 still conflicts: at fb604675b, fgetc_nid_postfix and getc_unlocked_nid_postfix call GetNativeStream(stream) and then SwitchToReading, both before the read. Merging #8150 (6a9b1285c) into this head still conflicts in StandardStreams.cpp, FileStreams.cpp and debt/libc.md. GetNativeStream throws on a random-device stream. So whoever resolves the conflict has to put #8150's IsRandomDevice() check before both calls. Otherwise fgetc on /dev/urandom throws again.

AI-assisted: yes (Claude Code); results above were run on this machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6292794595 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8226#issuecomment-6292794595). Originally posted by [wachi35676](https://github.com/wachi35676) on 2026-10-20T14:07:45Z. --- Confirmed on glibc 2.39 as well. The Linux failure from my earlier comment is gone at `fb604675b`. Head `fb604675b` merged onto `main` `19fcab22e` (clean merge). Release, `BUILD_TESTING=ON`, no warnings in either build log. **Ubuntu 24.04 (WSL2), GCC 13.3, glibc 2.39:** - `ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)"`: 6 of 6 pass, 3 runs out of 3. They also pass with `MALLOC_CHECK_=3` and `glibc.malloc.perturb=165`. - Negative control: with the four libc sources set back to `main`, `file_streams` aborts with `fread of more than the stream buffer after fwrite on an r+ stream`. **Windows 11, WinLibs GCC 15.2.0 UCRT:** the same 6 of 6 pass, 3 runs out of 3. With the libc sources set back to `main`, the test aborts with `fread after fwrite on an r+ stream read other bytes`. I also added a probe to `FileStreams.cpp` that goes through the guest `*_nid_postfix` functions. Each case reads the file back with a separate `fopen` after `fclose`. | Case | Linux | Windows | |---|---|---| | `r+`: `fwrite("AB")`, `ungetc('Z')`, `fgetc` ×2 | `ftell` 1 → 2 → 3, bytes `Z`, `2`, file `AB23456789` | same | | same, then `fseek(0, SEEK_CUR)`, `fwrite("CD")` | `ftell` 5, file `AB2CD56789` | same | | `r+`: `fwrite`, `fgetc`, `fseek(END)`, `fwrite("XY")` | file `AB23456789XY` | same | | `a+`: `fwrite("AB")`, `ungetc('Z')`, `fgetc` ×2 | `ftell` 12, `Z`, then EOF with no error, file `0123456789AB` | same | | `a+`: `fwrite`, `fseek(0)`, `fgetc`, `fwrite("X")` | `'0'`, `ftell` 13, file `0123456789ABX` | same | | `a+`: `fwrite`, `fread(65536)` | 0 bytes, EOF, `ftell` 12 | same | | 20 seeded runs of 3000 mixed `fwrite`/`fread`/`fgetc`/`ungetc`/`fseek` calls on `r+` (sizes up to 12000 bytes), checked against a model after every call | all match, 3 runs out of 3 (Linux with `MALLOC_CHECK_=3`) | all match | With `main` libc, the same probe aborts on Linux with `munmap_chunk(): invalid pointer`. On Windows it fails 29 checks. **Memory errors:** valgrind is not installed in my WSL, so I used AddressSanitizer and UBSan instead. I built a standalone program that makes the same glibc calls as `SwitchToReading` (`__freadable`, `__fwriting`, `_IO_switch_to_get_mode`) before every read and ran the same cases with them. It reports no errors, 3 runs out of 3. Without the switch, ASan stops in the first case with `attempting free on address which was not malloc()-ed` in `__uflow` → `_IO_free_backup_area`. That is the double free you saw on 2.43. **Windows-only difference, not caused by this PR:** after `ungetc` at offset 0 and an `fgetc` of that byte, `ftell` returns 1; Linux returns 0. The next byte is still the right one. `main` gives the same 1 on a new `rb` stream, so this comes from the UCRT. **#8150 still conflicts:** at `fb604675b`, `fgetc_nid_postfix` and `getc_unlocked_nid_postfix` call `GetNativeStream(stream)` and then `SwitchToReading`, both before the read. Merging #8150 (`6a9b1285c`) into this head still conflicts in `StandardStreams.cpp`, `FileStreams.cpp` and `debt/libc.md`. `GetNativeStream` throws on a random-device stream. So whoever resolves the conflict has to put #8150's `IsRandomDevice()` check before both calls. Otherwise `fgetc` on `/dev/urandom` throws again. AI-assisted: yes (Claude Code); results above were run on this machine.
oneandonlydean commented 2026-10-21 06:27:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-21T06:27:24Z.


@dantdmdarealguy thanks, the switch looks right to me. I checked the production and test changes against fb604675b (byte-identical, so the earlier Linux and Windows runs and their negative controls carry over), and the merge with current main compiles under GCC 13.

One small gap of the same kind: vfscanf_nid_postfix (Formatting.cpp, which vscanf and scanf also go through) reads without SwitchToReading, while fscanf_nid_postfix now calls it. On Windows a vfscanf directly after an fwrite on an r+ stream still goes through the UCRT without the switch, the same as fscanf did before this change. On glibc its reads go through __uflow, so Linux is not affected there.

Could you add the same if (!stream->SwitchToReading()) return EOF; to vfscanf_nid_postfix, plus a vfscanf case next to the fscanf one in file_streams? If you'd rather keep this PR as it is, a line in docs/dev/debt/libc.md would do. (fgetwc, getwc and fgetws are already covered, since they read through fgetc_nid_postfix.)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6309599750 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8226#issuecomment-6309599750). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-21T06:27:24Z. --- @dantdmdarealguy thanks, the switch looks right to me. I checked the production and test changes against `fb604675b` (byte-identical, so the earlier Linux and Windows runs and their negative controls carry over), and the merge with current `main` compiles under GCC 13. One small gap of the same kind: `vfscanf_nid_postfix` (`Formatting.cpp`, which `vscanf` and `scanf` also go through) reads without `SwitchToReading`, while `fscanf_nid_postfix` now calls it. On Windows a `vfscanf` directly after an `fwrite` on an `r+` stream still goes through the UCRT without the switch, the same as `fscanf` did before this change. On glibc its reads go through `__uflow`, so Linux is not affected there. Could you add the same `if (!stream->SwitchToReading()) return EOF;` to `vfscanf_nid_postfix`, plus a `vfscanf` case next to the `fscanf` one in `file_streams`? If you'd rather keep this PR as it is, a line in `docs/dev/debt/libc.md` would do. (`fgetwc`, `getwc` and `fgetws` are already covered, since they read through `fgetc_nid_postfix`.)
dantdmdarealguy commented 2026-10-21 08:24:08 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by dantdmdarealguy on 2026-10-21T08:24:08Z.


Thanks. Since this one is merged, the vfscanf switch is in #8982: vfscanf_nid_postfix now calls if (!stream->SwitchToReading()) return EOF; after GetNativeStream, as fscanf_nid_postfix does. vscanf and scanf go through it. file_streams has a vfscanf case next to the fscanf one: fwrite("AB") on an r+ stream over 0123456789, then vfscanf("%3s") through a va_list wrapper. It checks that one item was read, that it is 234, that the error indicator is clear and that the file is AB23456789.

  • Windows 11, WinLibs GCC 15.2.0, Release, on main b77bd5880: without the Formatting.cpp line, ctest -R "^file_streams$" fails 3/3 (0xc0000409, "vfscanf after fwrite on an r+ stream read other bytes"). With it, it passes 3/3. ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)": 6/6, 3 runs out of 3.
  • Arch Linux (WSL2), GCC 16.1.1, glibc 2.43: ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)" 6/6, 3 runs out of 3. As you said, glibc is not affected: the new case also passes 3/3 without the Formatting.cpp line.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6311489559 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8226#issuecomment-6311489559). Originally posted by [dantdmdarealguy](https://github.com/dantdmdarealguy) on 2026-10-21T08:24:08Z. --- Thanks. Since this one is merged, the vfscanf switch is in #8982: `vfscanf_nid_postfix` now calls `if (!stream->SwitchToReading()) return EOF;` after `GetNativeStream`, as `fscanf_nid_postfix` does. `vscanf` and `scanf` go through it. `file_streams` has a `vfscanf` case next to the `fscanf` one: `fwrite("AB")` on an `r+` stream over `0123456789`, then `vfscanf("%3s")` through a va_list wrapper. It checks that one item was read, that it is `234`, that the error indicator is clear and that the file is `AB23456789`. - Windows 11, WinLibs GCC 15.2.0, Release, on `main` `b77bd5880`: without the `Formatting.cpp` line, `ctest -R "^file_streams$"` fails 3/3 (0xc0000409, "vfscanf after fwrite on an r+ stream read other bytes"). With it, it passes 3/3. `ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)"`: 6/6, 3 runs out of 3. - Arch Linux (WSL2), GCC 16.1.1, glibc 2.43: `ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)"` 6/6, 3 runs out of 3. As you said, glibc is not affected: the new case also passes 3/3 without the `Formatting.cpp` line.
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!8226
No description provided.