fix(libc): set up streams for writing after a read as FreeBSD does on Windows #11560

Merged
Ragbie merged 1 commit from upstream-pr/11560 into main 2026-10-27 08:27:49 +00:00
Ragbie commented 2026-10-26 19:28:26 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Ragbie on 2026-10-26T19:28:26Z.


What

On Windows a write that directly follows a read on an update stream is lost. With 0123456789 opened r+b, fgetc then fputc('X') returns 'X' without the error indicator and the file is unchanged. fprintf returns 2 and writes nothing. fwrite returns 0 and fputs returns EOF, both without the error indicator. An fflush in between does not help, and an a+ stream loses the write the same way. On a stream open only for reading, fputc after a read returns the character instead of failing. The UCRT keeps such a stream in read mode and puts the bytes into its read buffer. The libc technical debt records this gap; #8226 fixed the opposite direction, reads after writes.

FreeBSD 11.4 runs __swsetup through prepwrite before every write: __swbuf for putc, __sfvwrite for fwrite, fputs and puts, and __vfprintf and fputws directly. If the stream is not open for writing, it fails with EBADF and sets __SERR. If the stream is reading, it drops the read buffer and any ungetc data, clears __SEOF and writes at the descriptor's offset (_swrite, which seeks to the end first for a+). fwrite of zero bytes and fputs("") return before prepwrite.

The change:

  • New functions. FileStream::SwitchToWriting, and SwitchToWritingUnlocked for putc_unlocked, do the same on the UCRT stream:

    • Neither _IOWRITE nor _IOUPDATE set: fail with EBADF and set the error indicator.
    • _IOREAD with _IOUPDATE: set _cnt = 0 and _ptr = _base and clear _IOREAD and _IOEOF, so the UCRT writes at the descriptor's offset. No seek is involved, so this also works on a stream that cannot seek.
    • On other hosts, and on a /dev/random stream (which throws as before), the functions do nothing.
  • Callers. The switch runs before these writes:

    • fwrite, fputs, fputc/putc/putchar, and putc_unlocked/putchar_unlocked/putw.
    • vfprintf/fprintf, vfprintf_s/fprintf_s/vprintf_s, fputwc/putwc/putwchar, fputws, vfwprintf/fwprintf/vwprintf, vfwprintf_s and its wrappers, wprintf and puts.
    • printf, vprintf and printf_s, through PrintWindows. It now takes standard output from a new GuestStandardOutputForWriting_nid_no_patch and returns -1 when that stream is not open for writing; before, it threw. GuestStandardOutputFile_nid_no_patch and its other callers are unchanged.

    As in FreeBSD, fwrite of zero bytes and fputs("") skip the switch. The formatted writers switch before formatting.

  • Technical debt. The debt entry now records what remains:

    • The write lands past the UCRT's read-ahead (4096 bytes by default, 2 unbuffered), where the console reads st_blksize bytes (1 unbuffered).
    • Linux glibc writes at the stream position instead. Matching FreeBSD there needs the stream to track whether it was positioned since its last read, which this PR does not do.

Tested

Windows 11 Pro, Intel Core i5-14600KF, WinLibs GCC 15.2.0, full Release build:

  • file_streams gets CheckStreamWritesAfterReads, which covers:

    • nine writers (fwrite, fputs, fputc, putc_unlocked, fprintf, fprintf_s, fputwc, fputws, fwprintf) after fseek and fgetc on r+b and on a+b;
    • a write after reading every byte, after fflush, and after ungetc;
    • fputc, fwrite and fprintf after a read on an rb stream, which must give EOF/0/-1 with EBADF and the error indicator and leave the file unchanged.

    The expected contents follow FreeBSD, except the two Linux results the debt entry records.

  • guest_standard_streams_update_stdout (new) reopens standard output a+b. After an fseek and fgetc, puts, printf, vprintf, printf_s and wprintf must each append. It then reopens it rb, and all five must fail with EBADF.

  • Without the fix (main's sources): both tests fail. file_streams stops at fwrite after fgetc on an update stream, and the standard output file holds only 0123456789 because the puts is dropped. The case that reads every byte before writing already passes on main, since the UCRT switches a fully consumed buffer itself; it guards against regressions.

  • With the fix:

    • Both tests pass with --repeat until-fail:3, together with the random tests.
    • Full ctest on main d891568df: 99% tests passed, 5 tests failed out of 2504.
      • Four of the failures also fail on main on this machine: agc_write_tracking_metadata_commit, agc_host_import_cut_lifetime, agc_driver_depth_plane_partial_store and agc_driver_image_plane_address_on_line.
      • The fifth, guest_wide_formatting, fails on main here too: %Z gives the host's non-ASCII zone name, which #10987 addresses.
      • check_skips.py reports one skip, guest_fopen_errors. It skips itself on this machine because creating symbolic links needs Developer Mode.

Linux (Ubuntu 24.04 container, GCC 13.3.0), where the change does nothing:

  • 61 tests match stream|stdio|printf|wide|format|fopen|freopen|fclose|fwrite|fread|putw|getw|ungetc|gets|scanf|puts|libc|random. All pass with --repeat until-fail:3, including the new cases, which expect glibc's results.
  • Full ctest: 99% tests passed, 25 tests failed out of 2398. All 25 failures are agc_* tests, and each reports that write watching is unavailable: the container's kernel lacks UFFD_FEATURE_WP_ASYNC, and the tests run on llvmpipe.

macOS: not tested.

Measured with a standalone program on the same machine, file 0123456789:

Sequence FreeBSD 11.4 (source) Windows UCRT Linux glibc 2.39
r+ fgetc, fputc('X') 0123456789X returns 'X', file unchanged 0X23456789
r+ fgetc, fflush, fputc('X') 0123456789X returns 'X', file unchanged 0X23456789
a+ fgetc, fputc('X') 0123456789X returns 'X', file unchanged 0123456789X
r fgetc, fputc('X') EOF, EBADF, error returns 'X', no error EOF, EBADF, error

Overlaps:

  • #10324 adds an Orientation(-1) call after the same GetNativeStream lines in fputs, fputc, vfprintf and puts.
  • #10620 edits the neighbouring /dev/random entry in docs/dev/debt/libc.md.

Both are textual only. Whichever lands second keeps both changes; in FreeBSD's order the orientation comes before the write setup.

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
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5023406758 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11560). Originally posted by [Ragbie](https://github.com/Ragbie) on 2026-10-26T19:28:26Z. --- ### What On Windows a write that directly follows a read on an update stream is lost. With `0123456789` opened `r+b`, `fgetc` then `fputc('X')` returns `'X'` without the error indicator and the file is unchanged. `fprintf` returns 2 and writes nothing. `fwrite` returns 0 and `fputs` returns `EOF`, both without the error indicator. An `fflush` in between does not help, and an `a+` stream loses the write the same way. On a stream open only for reading, `fputc` after a read returns the character instead of failing. The UCRT keeps such a stream in read mode and puts the bytes into its read buffer. The libc technical debt records this gap; #8226 fixed the opposite direction, reads after writes. FreeBSD 11.4 runs [`__swsetup`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/libc/stdio/wsetup.c#L59-L74) through `prepwrite` before every write: `__swbuf` for `putc`, `__sfvwrite` for `fwrite`, `fputs` and `puts`, and `__vfprintf` and `fputws` directly. If the stream is not open for writing, it fails with `EBADF` and sets `__SERR`. If the stream is reading, it drops the read buffer and any `ungetc` data, clears `__SEOF` and writes at the descriptor's offset ([`_swrite`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/libc/stdio/stdio.c#L104-L129), which seeks to the end first for `a+`). `fwrite` of zero bytes and `fputs("")` return before `prepwrite`. The change: - **New functions.** `FileStream::SwitchToWriting`, and `SwitchToWritingUnlocked` for `putc_unlocked`, do the same on the UCRT stream: - Neither `_IOWRITE` nor `_IOUPDATE` set: fail with `EBADF` and set the error indicator. - `_IOREAD` with `_IOUPDATE`: set `_cnt = 0` and `_ptr = _base` and clear `_IOREAD` and `_IOEOF`, so the UCRT writes at the descriptor's offset. No seek is involved, so this also works on a stream that cannot seek. - On other hosts, and on a `/dev/random` stream (which throws as before), the functions do nothing. - **Callers.** The switch runs before these writes: - `fwrite`, `fputs`, `fputc`/`putc`/`putchar`, and `putc_unlocked`/`putchar_unlocked`/`putw`. - `vfprintf`/`fprintf`, `vfprintf_s`/`fprintf_s`/`vprintf_s`, `fputwc`/`putwc`/`putwchar`, `fputws`, `vfwprintf`/`fwprintf`/`vwprintf`, `vfwprintf_s` and its wrappers, `wprintf` and `puts`. - `printf`, `vprintf` and `printf_s`, through `PrintWindows`. It now takes standard output from a new `GuestStandardOutputForWriting_nid_no_patch` and returns -1 when that stream is not open for writing; before, it threw. `GuestStandardOutputFile_nid_no_patch` and its other callers are unchanged. As in FreeBSD, `fwrite` of zero bytes and `fputs("")` skip the switch. The formatted writers switch before formatting. - **Technical debt.** The debt entry now records what remains: - The write lands past the UCRT's read-ahead (4096 bytes by default, 2 unbuffered), where the console reads `st_blksize` bytes (1 unbuffered). - Linux glibc writes at the stream position instead. Matching FreeBSD there needs the stream to track whether it was positioned since its last read, which this PR does not do. ### Tested Windows 11 Pro, Intel Core i5-14600KF, WinLibs GCC 15.2.0, full Release build: - `file_streams` gets `CheckStreamWritesAfterReads`, which covers: - nine writers (`fwrite`, `fputs`, `fputc`, `putc_unlocked`, `fprintf`, `fprintf_s`, `fputwc`, `fputws`, `fwprintf`) after `fseek` and `fgetc` on `r+b` and on `a+b`; - a write after reading every byte, after `fflush`, and after `ungetc`; - `fputc`, `fwrite` and `fprintf` after a read on an `rb` stream, which must give `EOF`/0/-1 with `EBADF` and the error indicator and leave the file unchanged. The expected contents follow FreeBSD, except the two Linux results the debt entry records. - `guest_standard_streams_update_stdout` (new) reopens standard output `a+b`. After an `fseek` and `fgetc`, `puts`, `printf`, `vprintf`, `printf_s` and `wprintf` must each append. It then reopens it `rb`, and all five must fail with `EBADF`. - **Without the fix (`main`'s sources):** both tests fail. `file_streams` stops at `fwrite after fgetc on an update stream`, and the standard output file holds only `0123456789` because the `puts` is dropped. The case that reads every byte before writing already passes on `main`, since the UCRT switches a fully consumed buffer itself; it guards against regressions. - **With the fix:** - Both tests pass with `--repeat until-fail:3`, together with the `random` tests. - Full `ctest` on `main` `d891568df`: `99% tests passed, 5 tests failed out of 2504`. - Four of the failures also fail on `main` on this machine: `agc_write_tracking_metadata_commit`, `agc_host_import_cut_lifetime`, `agc_driver_depth_plane_partial_store` and `agc_driver_image_plane_address_on_line`. - The fifth, `guest_wide_formatting`, fails on `main` here too: `%Z` gives the host's non-ASCII zone name, which #10987 addresses. - `check_skips.py` reports one skip, `guest_fopen_errors`. It skips itself on this machine because creating symbolic links needs Developer Mode. Linux (Ubuntu 24.04 container, GCC 13.3.0), where the change does nothing: - 61 tests match `stream|stdio|printf|wide|format|fopen|freopen|fclose|fwrite|fread|putw|getw|ungetc|gets|scanf|puts|libc|random`. All pass with `--repeat until-fail:3`, including the new cases, which expect glibc's results. - Full `ctest`: `99% tests passed, 25 tests failed out of 2398`. All 25 failures are `agc_*` tests, and each reports that write watching is unavailable: the container's kernel lacks `UFFD_FEATURE_WP_ASYNC`, and the tests run on llvmpipe. macOS: not tested. Measured with a standalone program on the same machine, file `0123456789`: | Sequence | FreeBSD 11.4 (source) | Windows UCRT | Linux glibc 2.39 | |---|---|---|---| | `r+` `fgetc`, `fputc('X')` | `0123456789X` | returns `'X'`, file unchanged | `0X23456789` | | `r+` `fgetc`, `fflush`, `fputc('X')` | `0123456789X` | returns `'X'`, file unchanged | `0X23456789` | | `a+` `fgetc`, `fputc('X')` | `0123456789X` | returns `'X'`, file unchanged | `0123456789X` | | `r` `fgetc`, `fputc('X')` | `EOF`, `EBADF`, error | returns `'X'`, no error | `EOF`, `EBADF`, error | **Overlaps:** - #10324 adds an `Orientation(-1)` call after the same `GetNativeStream` lines in `fputs`, `fputc`, `vfprintf` and `puts`. - #10620 edits the neighbouring `/dev/random` entry in `docs/dev/debt/libc.md`. Both are textual only. Whichever lands second keeps both changes; in FreeBSD's order the orientation comes before the write setup. ### 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
MarcZX10 commented 2026-10-27 00:20:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-27T00:20:22Z.

Review: CHANGES_REQUESTED


The write-side setup and the actual stdio write are not protected by one stream lock. SwitchToWriting() locks the UCRT FILE, clears its read state, and unlocks before callers enter fwrite/fputc/the formatting functions. A second thread can legally enter a read operation in that gap, reestablish UCRT read mode, and consume data; the first thread's subsequent write then runs without the new setup and can reproduce the dropped-write behavior this change fixes. The stdio routines serialize their own individual calls, but that does not cover this two-step transition.

Please keep the stream lock held from the state transition through the corresponding write (including the Windows formatting paths), or use an equivalent helper that makes the transition and write one locked operation. Add a focused interleaving regression test if feasible. I have not run the Windows-specific test suite, so this is a code-path finding rather than a runtime reproduction.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5660807822 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11560#pullrequestreview-5660807822). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-27T00:20:22Z. **Review:** CHANGES_REQUESTED --- The write-side setup and the actual stdio write are not protected by one stream lock. `SwitchToWriting()` locks the UCRT `FILE`, clears its read state, and unlocks before callers enter `fwrite`/`fputc`/the formatting functions. A second thread can legally enter a read operation in that gap, reestablish UCRT read mode, and consume data; the first thread's subsequent write then runs without the new setup and can reproduce the dropped-write behavior this change fixes. The stdio routines serialize their own individual calls, but that does not cover this two-step transition. Please keep the stream lock held from the state transition through the corresponding write (including the Windows formatting paths), or use an equivalent helper that makes the transition and write one locked operation. Add a focused interleaving regression test if feasible. I have not run the Windows-specific test suite, so this is a code-path finding rather than a runtime reproduction.
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!11560
No description provided.