Skip to content

fix(libc): fail fputs, fputc and fprintf on a closed stream as a PS5 does - #22047

Merged
oneandonlydean merged 3 commits into
boykopovar:mainfrom
brajankw:fix/libc-closed-stream-write-errors
Dec 3, 2026
Merged

oneandonlydean merged 3 commits into
boykopovar:mainfrom
brajankw:fix/libc-closed-stream-write-errors

Conversation

@brajankw

@brajankw brajankw commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What

A write to a stream that fclose or a failed freopen closed set errno to EBADF in fputs, fputc and fprintf. On a PS5 fputs and fputc return -1 and leave errno unchanged, and fprintf fails with EINVAL (#9763; the freopen of a closed stream entry in docs/dev/debt/libc.md).

  • Those three now do the same; putc, putchar and __swbuf forward to fputc and follow it.
  • The other stream writes (fwrite, puts, printf and the wide forms) were not measured and keep EBADF; the debt entry says so.
  • GuestStandardStreams.cpp and GuestFreopenHostStandard.cpp check the measured results where they checked EBADF before.

Tested

Linux (Debian 13, GCC 14.2.0, Release), on main ec7369ecb8.

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • 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

Summary by CodeRabbit

  • Bug Fixes
    • Failed writes to closed streams now preserve the existing error value for select operations. Formatted output still sets an error when the stream cannot be opened.
  • Documentation
    • Added notes describing closed-stream behavior, including file reopening and write errors.

…does

A write to a stream that fclose or a failed freopen closed set errno to
EBADF in fputs, fputc and fprintf. On a PS5 fputs and fputc return -1
and leave errno unchanged, and fprintf fails with EINVAL (boykopovar#9763). Those
three now do the same; putc, putchar and __swbuf forward to fputc and
follow it. The other stream writes, which were not measured, keep
EBADF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 117239034b:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_freopen_host_standard_tests, guest_standard_stream_tests built cleanly.
  • CTest (guest_standard_streams, guest_standard_streams_closed_stdout, guest_standard_streams_exclusive_stdout, guest_standard_streams_reopen_closed_stdout, guest_standard_streams_update_stdout, guest_freopen_host_standard):
    1/6 Test #1253: guest_standard_streams_closed_stdout ..........   Passed    0.02 sec
    2/6 Test #1255: guest_standard_streams_reopen_closed_stdout ...   Passed    0.04 sec
    3/6 Test #1254: guest_standard_streams_exclusive_stdout .......   Passed    0.02 sec
    4/6 Test #1256: guest_standard_streams_update_stdout ..........   Passed    0.02 sec
    5/6 Test #1260: guest_freopen_host_standard ...................   Passed    0.02 sec
    6/6 Test #1252: guest_standard_streams ........................   Passed    0.22 sec
    100% tests passed, 0 tests failed out of 6
    
  • Negative control: with core/libs/prx/libc/src/FileAndHeap.cpp, core/libs/prx/libc/src/Formatting.cpp, core/libs/prx/libc/src/StandardStreams.cpp reverted to main and the new tests kept, the suite fails:
    1/6 Test #1255: guest_standard_streams_reopen_closed_stdout ...   Passed    0.02 sec
    2/6 Test #1252: guest_standard_streams ........................Subprocess aborted***Exception:   0.42 sec
    3/6 Test #1260: guest_freopen_host_standard ...................Subprocess aborted***Exception:   0.48 sec
    4/6 Test #1254: guest_standard_streams_exclusive_stdout .......   Passed    0.02 sec
    5/6 Test #1256: guest_standard_streams_update_stdout ..........   Passed    0.02 sec
    6/6 Test #1253: guest_standard_streams_closed_stdout ..........Subprocess aborted***Exception:   0.45 sec
    50% tests passed, 3 tests failed out of 6
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified core/libs/prx/libc/src/FileAndHeap.cpp fputs_nid_postfix correctly returns -1 without setting errno when stream is non-null and closed (!stream->IsOpen()).
    • Verified core/libs/prx/libc/src/StandardStreams.cpp fputc_nid_postfix correctly returns -1 without modifying errno when stream is closed (!stream->IsOpen()), and that forwarding functions putc, putchar, and __swbuf follow this behavior.
    • Verified core/libs/prx/libc/src/Formatting.cpp fprintf_nid_postfix correctly sets errno = 22 (EINVAL) and returns -1 before argument parsing or buffer formatting when stream is closed.
    • Verified technical debt documentation fragment in docs/dev/debt/changes/fix-libc-closed-stream-write-errors.md conforms to AGENTS.md conventions and accurately documents the measured console behavior.
    • Verified guest_standard_streams and guest_freopen_host_standard test suites verify that errno remains untouched (errno == 77) across fputs/fputc on closed streams and is set to 22 on fprintf.

Looks Good To Me

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

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 9087 core/libs/prx/libc/src/Formatting.cpp
PR 12682 core/libs/prx/libc/src/FileAndHeap.cpp
PR 12688 core/libs/prx/libc/src/FileAndHeap.cpp
PR 12700 core/libs/prx/libc/src/FileAndHeap.cpp
PR 12965 core/libs/prx/libc/src/FileAndHeap.cpp

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — no blocking findings

The changed behavior is consistent with the stated closed-stream errno results in the inspected implementation and tests.

What I ran

Reviewed head 117239034be43795aa9f157cb58a35e87de74dcc. No commands or tests were run; the reader exposes file reads only.

Results

Check Result Note
Diff and changed code passed Six changed files inspected
Tests not run Author-reported results only

Findings

Blocking

None.

Non-blocking

None.

Not verified

The prepared bundle marks all six changed files as included, but reads using review/files/<path> were not served by the reader. I inspected the complete diff and targeted ranges in the three implementation files and GuestStandardStreams.cpp; full contents of GuestFreopenHostStandard.cpp and the debt note, and the rest of the changed files, were not read. files.json was not available. Tests and author-reported environment/results were not independently verified. The inspected files were FileAndHeap.cpp, Formatting.cpp, StandardStreams.cpp, and GuestStandardStreams.cpp; no files were excluded by rule according to the manifest.

To get this to a good state

Nothing is required.

This was referenced Nov 21, 2026
@kiwe147

kiwe147 commented Nov 21, 2026

Copy link
Copy Markdown

Tested head 117239034b, applied with git apply (with -C1, context shifted) on main fd4aeed483 together with the other 25 PRs of one batch (#24107, #24132, #24238, #15143, #22088, #22685, #23739, #24032, #16054, #20001, #20344, #24170, #24396, #16856, #17298, #20497, #23347, #24426, #24554, #24598, #21376, #21556, #22082, #14124, #18476). All applied without conflicts and the whole tree built.

Setup: Windows 11 Pro 10.0.26200, Ryzen 7 9800X3D, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. GPUs: NVIDIA GeForce RTX 3080 (driver 621.24) and the AMD Radeon iGPU of the CPU (gfx1036, driver 32.0.21036.18). No validation layer. iGPU run: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 ANYPS5_GPU="AMD Radeon", agc_/video tests only.

tests RTX 3080 iGPU
guest_freopen_host_standard, guest_standard_streams, guest_standard_streams_closed_stdout and 3 more (6 tests, matched by name to the test file this PR changes) all pass outside the iGPU subset

Whole batch: the full ctest -j 12 (6524 tests) on the RTX 3080 has 8 failing tests; the 4 that also fail on main fd4aeed483 are agc_driver_stencil_plane_memory, agc_driver_msaa_dcc_unwatch, agc_storage_write_back_host_retile, and pr_overlap_names, which needs a newer Python than my 3.10. Intermittent in this run (pass when rerun alone, or known flaky): agc_driver_store_over_untracked. Traced to other PRs of the batch, each by reverting it and testing again: #21556 (guest_json_allocator), #16856 (guest_kernel_sys_module_internal), #15143 (guest_math_exact); none is in this PR's area. Failing tests I could not trace to a single PR (reverting the likely candidates did not clear them): public_headers. The 2127 agc_/video tests on the iGPU have 2 failing: agc_driver_stencil_plane_memory, agc_driver_store_over_untracked (agc_driver_stencil_plane_memory also fails on main).

This is one combined tree, not a run of this PR alone.

AI-assisted: yes (Claude Code)

brajankw and others added 2 commits November 28, 2026 16:17
# Conflicts:
#	core/libs/prx/libc/src/FileAndHeap.cpp
#	core/libs/prx/libc/src/StandardStreams.cpp
…unchanged

On a closed stream fputc returns -1 without setting errno, as measured on a PS5. The fcloseall test asserted EBADF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@brajankw

Copy link
Copy Markdown
Contributor Author

Merged current main (bb89b8a) into this branch (328b4bf + 1d3137c).

  • Conflict in fputs and fputc. feat(libc): implement fcloseall with tracked stream lifetimes #11831 put both behind FileStreamOperation_nid_no_patch. The resolution keeps that lease and lock and drops only errno = 9, so a closed stream still returns -1 with errno unchanged, as measured.
  • fprintf. Its closed-stream check (EINVAL) now takes the same FileStreamOperation, instead of calling stream->IsOpen() on a stream that may already be retired.
  • file_streams test. feat(libc): implement fcloseall with tracked stream lifetimes #11831's fcloseall case asserted errno == 9 after fputc on a stream that fcloseall had closed. That contradicts the closed-stream measurement this PR is based on, so 1d3137c expects errno unchanged there (errno != 0 fails).

Tests on Linux (Debian 13, GCC 14.2, Release), all passing: guest_standard_streams and its 4 *_stdout variants, file_streams, guest_freopen_host_standard (7/7). check_conventions.py and debt_fold.py --check pass.

@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Changes: Closed-stream writes

Layer / File(s) Summary
Write function errno behavior
core/libs/prx/libc/src/FileAndHeap.cpp, core/libs/prx/libc/src/StandardStreams.cpp, core/libs/prx/libc/src/Formatting.cpp
fputs and fputc return -1 for a non-open stream without setting errno to 9. fprintf attempts to open a stream operation and sets errno to 22 if opening fails for a non-null stream.
Closed-stream behavior checks and notes
core/libs/tests/FileStreams.cpp, core/libs/tests/GuestFreopenHostStandard.cpp, core/libs/tests/GuestStandardStreams.cpp, docs/dev/debt/changes/fix-libc-closed-stream-write-errors.md
Tests check errno preservation for fputs and fputc, errno 22 for fprintf, and the existing errno 9 behavior for fwrite. The change note records closed-stream freopen and write behavior.

Possibly related PRs

  • boykopovar/AnyPS5#11831: Introduces the tracked stream lifetimes and FileStreamOperation_nid_no_patch lease used by closed-stream writes.

Suggested reviewers: b-howell, babyhuey

Change: Bug fix

Merge Risk: Minimal · up to 1d313

This change makes closed-stream fputs and fputc leave errno unchanged and makes fprintf set EINVAL, matching the reported PS5 behavior. Tests and a change note are updated to match, and no concrete merge-blocking risk was found.

Security architecture risk: Minimal · up to 1d313

Closed-stream writes still fail without writing. The change matches the reported PS5 error behavior without granting callers access to new files or streams.

Retained concerns
No architecture-level concerns identified.

Security review details

Trust Boundaries and Controls

  • observed — The closed-stream checks reject non-null streams that cannot be leased or are not open before reaching host I/O. On the accepted path, fprintf still delegates formatting and writing to vfprintf; it adds no new host write destination.

Resilience and Maintainability Implications

  • inferred — The outer fprintf lease keeps the same recursive gate held between validation and the existing vfprintf operation, so a close or reopen using that gate cannot interleave between the checks. Scoped guards release the added lock and pin on return or unwind; the new rejection path exits before variadic argument setup.
Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5dc474a6-a902-48e2-8323-d62339dec452
Commits

Reviewing files that changed from the base of the PR and between bb89b8a and 1d3137c.

Files selected for processing: 7

  • core/libs/prx/libc/src/FileAndHeap.cpp
  • core/libs/prx/libc/src/Formatting.cpp
  • core/libs/prx/libc/src/StandardStreams.cpp
  • core/libs/tests/FileStreams.cpp
  • core/libs/tests/GuestFreopenHostStandard.cpp
  • core/libs/tests/GuestStandardStreams.cpp
  • docs/dev/debt/changes/fix-libc-closed-stream-write-errors.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — looks good

The reviewed code changes the closed stream behavior of fputs, fputc, and fprintf and updates tests to assert the documented errno results; I found no verified blocking defect.

What I ran

Read the prepared diff and all six changed source and test files plus the new debt note at head 1d3137ca095f599251679fdb1825c3af71473cbf, using repo_read.py.

No commands or tests were run. The test and negative control results in the PR description are author reported.

Results

Check Result Note
Diff and changed files passed All seven changed files read
Tests and negative control not run Results supplied by author
Cross platform behavior not run Windows and macOS not tested

Findings

Blocking

None.

Non-blocking

None.

Not verified

I read every file listed in the manifest; none were excluded. I did not independently verify the PS5 measurements, run tests, or inspect callers beyond the changed functions and tests. The author reports Linux test results and says Windows and macOS were not tested.

To get this to a good state

Nothing is required.

@brajankw

Copy link
Copy Markdown
Contributor Author

The one red check, relinker (macos-latest, clang++), is not caused by this PR. 1025 of its 1026 tests pass. The failing one is frame_capture_minimize_replay, which runs the Python script tools/tests/test_frame_capture_minimize_replay.py against tools/frame_capture_minimize.py. This PR changes only libc stream code, its tests and a debt fragment, nothing under tools/. The same test also fails, with nothing else failing, in the same macOS job on #28102 (shader recompiler only) and failed there on #27590 (libkernel memory only). A rerun needs maintainer rights.

AI-assisted: yes.

@brajankw

Copy link
Copy Markdown
Contributor Author

Update on the red macOS check: main now has the fix for frame_capture_minimize_replay. #27860 ("wait for macOS replay process groups to disappear") merged on 2026-11-30. A rerun of the old job reuses its original merge commit, so the check only turns green after main is merged into this branch. I'm leaving the branch alone so the approvals stay valid; say if you'd like me to merge main.

AI-assisted: yes.

@ligmaSec ligmaSec left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Built the submitted stream and formatting sources and ran all three Linux fixtures. FileStreams, GuestFreopenHostStandard, and GuestStandardStreams passed. The new cases check the return and errno behavior for fputs, fputc and fprintf on closed streams.

AI-assisted: yes.

@oneandonlydean
oneandonlydean merged commit 484e8e6 into boykopovar:main Dec 3, 2026
22 of 25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants