fix(libc): switch update streams to reading as FreeBSD does #8226
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/8226"
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 dantdmdarealguy on 2026-10-20T04:45:06Z.
What
An
r+,w+ora+stream that is read directly after a write, withoutfflushor a seek in between, loses the write on both hosts.freaddirectly after anfwritereturned bytes still sitting in the write buffer, and the next flush wrote them over the file at the wrong offset.ungetcalso failed on an update stream that was not already reading.__uflow/__underflow, and two paths skip that:ungetcputs the byte in glibc's backup area while the stream is still writing. TheABwrite is lost;fgetcthen givesZand EOF (glibc 2.39), or__uflowaborts withdouble free or corruption (out)(glibc 2.43).freadof 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")thenfread(..., 65536)on0123456789returns0123456789, and the file is unchanged.FreeBSD switches the stream itself.
__srefill(whichfreadcalls for every refill, whatever the size) and__ungetcboth act before reading from an__SRWstream: they flush pending output with__sflush, clear__SWRand set__SRD, and they returnEOFif the flush fails.FileStream::SwitchToReading(and an unlocked variant forgetc_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._fflush_nolockand sets the UCRT's reading flag.__freadable,__fwriting). It calls_IO_switch_to_get_mode, the step glibc's own__uflowtakes before reading: it flushes, returnsEOFand sets the error indicator if the flush fails, and leaves put mode. glibc has exported it sinceGLIBC_2.2.5. Callingfflushalone first is not enough, because the stream stays in put mode and the next read afterungetcstill corrupts the heap.fread,fgetc,getc,getc_unlocked,fgets,ungetc,ungetwcandfscanfcall it first.ungetc(EOF)does not, because FreeBSD returns before touching the stream.docs/dev/debt/libc.md.file_streamsnow runs these checks directly after anfwriteonr+:freadof 3 bytes andfreadof 65536 bytes (more than the stream buffer);fgetc,getc_unlocked,fgets,ungetcandfscanf.It also checks
freadonw+andfgetcona+. Each check verifies the bytes read, the error indicator and the final file contents. Finally it checksungetcon a freshr+stream and afterfseek.The test fails on
mainon both hosts and passes with the change: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 onmain30fda0a03:file_streams: fails onmainlibc 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).agc_driver_image_array_window_past_layer_limit(alignas(65536)exceeds the MinGW object-file maximum; that is broken onmain, 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_streamswith the PR's previous head and its test (the review's setup) aborts 3 runs out of 3 withdouble free or corruption (out). The abort is in__uflowunder thefgetcright after the firstungetc_nid_postfixcall, which is theungetc-after-fwritecase.mainlibc 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.ungetcafterfwritegivesZ, EOF,ftell-1, and the file stays0123456789. Callingfflushfirst aborts withdouble free or corruption (out). Calling_IO_switch_to_get_modefirst givesZ,2,ftell3 andAB23456789.freadafterfwrite("AB")is correct for 3 and 4095 bytes; for 4096, 8192 and 65536 bytes it returns0123456789and the file stays unchanged.ctest -R 'stream|stdio|...|patched_libraries'(same pattern): 23 of 23 pass (agc_driver_stream_copyskipped).ctest -R "^(file_streams|guest_standard_streams|guest_fdopendir|guest_filesystem)": 6 of 6 pass.ctest: 1702 of 1702 pass, 1242 of them skipped (WSL has no Vulkan device).tools/check_conventions.py --base origin/mainandtools/check_test_registration.pypass. No title or homebrew run.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by 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.
main)core/libs/prx/libc/src/StandardStreams.cppL88core/libs/prx/libc/include/FileStream.hppL18, L214core/libs/prx/libc/src/StandardStreams.cppL88Some 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.
docs/dev/debt/libc.mdcore/libs/prx/libc/include/FileStream.hppcore/libs/prx/libc/src/StandardStreams.cppdocs/dev/debt/libc.mdcore/libs/tests/FileStreams.cppdocs/dev/debt/libc.mddocs/dev/debt/libc.mddocs/dev/debt/libc.mdcore/libs/prx/libc/src/FileAndHeap.cppdocs/dev/debt/libc.mdcore/libs/prx/libc/include/FileStream.hppcore/libs/prx/libc/src/FileAndHeap.cppcore/libs/prx/libc/src/StandardStreams.cppdocs/dev/debt/libc.mddocs/dev/debt/libc.mdcore/libs/prx/libc/src/StandardStreams.cppcore/libs/tests/FileStreams.cppdocs/dev/debt/libc.mddocs/dev/debt/libc.mddocs/dev/debt/libc.mdImported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-20T11:29:24Z.
The new
file_streamschecks 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
33e08f16amerged ontomain02fb1ce53(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.main,file_streamsaborts withfread 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_streamsaborts withungetc 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-fwritecase removed from the test,file_streamspasses on Linux. That coversfread,fgetc,getc_unlocked,fgets,fscanf,w+,a+, andungetcon a new stream and afterfseek.A plain C program against glibc 2.39, with no AnyPS5 code, shows the cause. The file holds
0123456789, is opened withr+b, and the program callsfwrite("AB", 1, 2, f), thenungetc('Z', f),fgetcandfgetc. It getsZ, then EOF;ftellreturns -1; and the file is still0123456789afterwards, so theABwrite is lost. FreeBSD's__ungetcflushes the pending write first, which is what the check expects:Z,2, and a file holdingAB23456789.So on Linux,
ungetcdirectly 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: makeungetc/ungetwcflush pending output on Linux too, or limit that check to Windows and record the glibc gap indebt/libc.md. ThelinuxCI job was skipped on this PR, so CI has not caught this.AI-assisted: yes (Claude Code); results above were run on this machine.
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-fwritecase is worse than on 2.39: the nextfgetcaborts in__uflowwithdouble free or corruption (out), 3 runs out of 3.I took the first option. On glibc,
SwitchToReadingnow does what FreeBSD's__ungetcand__srefilldo. On a stream that is readable and writable and currently writing (__freadableand__fwriting), it calls_IO_switch_to_get_mode, the step glibc's own__uflowtakes before a read. That flushes, fails the call (EOFand the error indicator) if the flush fails, and leaves put mode. Callingfflushalone 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
freadof at least the buffer size. Afterfwrite("AB"),fread(..., 65536)returns0123456789from offset 0, and the file is unchanged. FreeBSD'sfreadgoes through__srefillwhatever the size. The same switch fixes it, andfile_streamsnow checks a 65536-bytefreadtoo.Linux, head
fb604675bonmain30fda0a03, GCC 16.1.1, glibc 2.43, Release:file_streamsaborts 3/3 withdouble free or corruption (out)in thefgetcafter the firstungetc.mainlibc ("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 fullctestpasses (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.
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
fb604675bmerged ontomain19fcab22e(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 withMALLOC_CHECK_=3andglibc.malloc.perturb=165.main,file_streamsaborts withfread 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 withfread after fwrite on an r+ stream read other bytes.I also added a probe to
FileStreams.cppthat goes through the guest*_nid_postfixfunctions. Each case reads the file back with a separatefopenafterfclose.r+:fwrite("AB"),ungetc('Z'),fgetc×2ftell1 → 2 → 3, bytesZ,2, fileAB23456789fseek(0, SEEK_CUR),fwrite("CD")ftell5, fileAB2CD56789r+:fwrite,fgetc,fseek(END),fwrite("XY")AB23456789XYa+:fwrite("AB"),ungetc('Z'),fgetc×2ftell12,Z, then EOF with no error, file0123456789ABa+:fwrite,fseek(0),fgetc,fwrite("X")'0',ftell13, file0123456789ABXa+:fwrite,fread(65536)ftell12fwrite/fread/fgetc/ungetc/fseekcalls onr+(sizes up to 12000 bytes), checked against a model after every callMALLOC_CHECK_=3)With
mainlibc, the same probe aborts on Linux withmunmap_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 withattempting free on address which was not malloc()-edin__uflow→_IO_free_backup_area. That is the double free you saw on 2.43.Windows-only difference, not caused by this PR: after
ungetcat offset 0 and anfgetcof that byte,ftellreturns 1; Linux returns 0. The next byte is still the right one.maingives the same 1 on a newrbstream, so this comes from the UCRT.#8150 still conflicts: at
fb604675b,fgetc_nid_postfixandgetc_unlocked_nid_postfixcallGetNativeStream(stream)and thenSwitchToReading, both before the read. Merging #8150 (6a9b1285c) into this head still conflicts inStandardStreams.cpp,FileStreams.cppanddebt/libc.md.GetNativeStreamthrows on a random-device stream. So whoever resolves the conflict has to put #8150'sIsRandomDevice()check before both calls. Otherwisefgetcon/dev/urandomthrows again.AI-assisted: yes (Claude Code); results above were run on this machine.
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 currentmaincompiles under GCC 13.One small gap of the same kind:
vfscanf_nid_postfix(Formatting.cpp, whichvscanfandscanfalso go through) reads withoutSwitchToReading, whilefscanf_nid_postfixnow calls it. On Windows avfscanfdirectly after anfwriteon anr+stream still goes through the UCRT without the switch, the same asfscanfdid 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;tovfscanf_nid_postfix, plus avfscanfcase next to thefscanfone infile_streams? If you'd rather keep this PR as it is, a line indocs/dev/debt/libc.mdwould do. (fgetwc,getwcandfgetwsare already covered, since they read throughfgetc_nid_postfix.)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_postfixnow callsif (!stream->SwitchToReading()) return EOF;afterGetNativeStream, asfscanf_nid_postfixdoes.vscanfandscanfgo through it.file_streamshas avfscanfcase next to thefscanfone:fwrite("AB")on anr+stream over0123456789, thenvfscanf("%3s")through a va_list wrapper. It checks that one item was read, that it is234, that the error indicator is clear and that the file isAB23456789.mainb77bd5880: without theFormatting.cppline,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.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 theFormatting.cppline.