fix(libc): set up streams for writing after a read as FreeBSD does on Windows #11560
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/11560"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by Ragbie on 2026-10-26T19:28:26Z.
What
On Windows a write that directly follows a read on an update stream is lost. With
0123456789openedr+b,fgetcthenfputc('X')returns'X'without the error indicator and the file is unchanged.fprintfreturns 2 and writes nothing.fwritereturns 0 andfputsreturnsEOF, both without the error indicator. Anfflushin between does not help, and ana+stream loses the write the same way. On a stream open only for reading,fputcafter 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
__swsetupthroughprepwritebefore every write:__swbufforputc,__sfvwriteforfwrite,fputsandputs, and__vfprintfandfputwsdirectly. If the stream is not open for writing, it fails withEBADFand sets__SERR. If the stream is reading, it drops the read buffer and anyungetcdata, clears__SEOFand writes at the descriptor's offset (_swrite, which seeks to the end first fora+).fwriteof zero bytes andfputs("")return beforeprepwrite.The change:
New functions.
FileStream::SwitchToWriting, andSwitchToWritingUnlockedforputc_unlocked, do the same on the UCRT stream:_IOWRITEnor_IOUPDATEset: fail withEBADFand set the error indicator._IOREADwith_IOUPDATE: set_cnt = 0and_ptr = _baseand clear_IOREADand_IOEOF, so the UCRT writes at the descriptor's offset. No seek is involved, so this also works on a stream that cannot seek./dev/randomstream (which throws as before), the functions do nothing.Callers. The switch runs before these writes:
fwrite,fputs,fputc/putc/putchar, andputc_unlocked/putchar_unlocked/putw.vfprintf/fprintf,vfprintf_s/fprintf_s/vprintf_s,fputwc/putwc/putwchar,fputws,vfwprintf/fwprintf/vwprintf,vfwprintf_sand its wrappers,wprintfandputs.printf,vprintfandprintf_s, throughPrintWindows. It now takes standard output from a newGuestStandardOutputForWriting_nid_no_patchand returns -1 when that stream is not open for writing; before, it threw.GuestStandardOutputFile_nid_no_patchand its other callers are unchanged.As in FreeBSD,
fwriteof zero bytes andfputs("")skip the switch. The formatted writers switch before formatting.Technical debt. The debt entry now records what remains:
st_blksizebytes (1 unbuffered).Tested
Windows 11 Pro, Intel Core i5-14600KF, WinLibs GCC 15.2.0, full Release build:
file_streamsgetsCheckStreamWritesAfterReads, which covers:fwrite,fputs,fputc,putc_unlocked,fprintf,fprintf_s,fputwc,fputws,fwprintf) afterfseekandfgetconr+band ona+b;fflush, and afterungetc;fputc,fwriteandfprintfafter a read on anrbstream, which must giveEOF/0/-1 withEBADFand 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 outputa+b. After anfseekandfgetc,puts,printf,vprintf,printf_sandwprintfmust each append. It then reopens itrb, and all five must fail withEBADF.Without the fix (
main's sources): both tests fail.file_streamsstops atfwrite after fgetc on an update stream, and the standard output file holds only0123456789because theputsis dropped. The case that reads every byte before writing already passes onmain, since the UCRT switches a fully consumed buffer itself; it guards against regressions.With the fix:
--repeat until-fail:3, together with therandomtests.ctestonmaind891568df:99% tests passed, 5 tests failed out of 2504.mainon this machine:agc_write_tracking_metadata_commit,agc_host_import_cut_lifetime,agc_driver_depth_plane_partial_storeandagc_driver_image_plane_address_on_line.guest_wide_formatting, fails onmainhere too:%Zgives the host's non-ASCII zone name, which #10987 addresses.check_skips.pyreports 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:
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.ctest:99% tests passed, 25 tests failed out of 2398. All 25 failures areagc_*tests, and each reports that write watching is unavailable: the container's kernel lacksUFFD_FEATURE_WP_ASYNC, and the tests run on llvmpipe.macOS: not tested.
Measured with a standalone program on the same machine, file
0123456789:r+fgetc,fputc('X')0123456789X'X', file unchanged0X23456789r+fgetc,fflush,fputc('X')0123456789X'X', file unchanged0X23456789a+fgetc,fputc('X')0123456789X'X', file unchanged0123456789Xrfgetc,fputc('X')EOF,EBADF, error'X', no errorEOF,EBADF, errorOverlaps:
Orientation(-1)call after the sameGetNativeStreamlines infputs,fputc,vfprintfandputs./dev/randomentry indocs/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
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by 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 UCRTFILE, clears its read state, and unlocks before callers enterfwrite/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.