fix(libc): reopen a closed stream in freopen instead of aborting #9763

Merged
rooklz merged 2 commits from upstream-pr/9763 into main 2026-10-28 00:48:51 +00:00
rooklz commented 2026-10-22 13:27:00 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-22T13:27:00Z.


What

freopen on a stream that had been closed aborted the process: FileStream::Reopen starts with GetHandle(), which throws FileStream: closed stream when the handle is gone. PPSA99630 (OpenMW, the Morrowind port in the homebrew catalog, v1.0.1, bring-up thread #9762) does that when /download0 cannot be used: its first freopen of stdout fails and leaves the stream closed, and a later freopen of it dies on main before the title prints anything:

[libc] unhandled exception 'St13runtime_error' thrown from 0x7ffff5d4ddda
terminate called after throwing an instance of 'std::runtime_error'
  what():  FileStream: closed stream

(0x35dda into libc.prx, freopen_nid_postfix.) FreeBSD's freopen keeps a closed FILE and reopens it: with fp->_flags == 0 it "holds on to it", opens the path on a new descriptor and makes fp that stream (freopen.c, releng/11.4). A failed open leaves it closed, with the open's errno.

Reopen now does the same for a closed stream: it opens the path through the caller's opener and adopts the handle, or fails with the open's error (ENOENT for an empty path, as open("") gives there). A path the resolver rejects before any open (an overlong name, an unavailable mount) used to reach Close() on the closed stream and throw the same way; freopen now closes only a stream that is open there and returns the resolver's error. A null filename on a closed stream answers EBADF, as a PS5 does (an open stream keeps answering ENOTSUP, since mode-only reopening is not supported here). The guest state reset and descriptor bookkeeping that the open-stream path did at its end moved into Adopt, which both paths use. A closed stream whose reopen fails keeps answering EBADF, as before. Only the standard streams can reach this, since a dynamic stream is freed by its fclose.

The debt entry records the differences from the console: the new descriptor is whatever the host hands out, where a PS5 takes the lowest free one, and a write to the closed stream answers EBADF here (as on main), where the console's fputs/fputc leave errno unchanged and its fprintf gives EINVAL.

Tested

  • PS5 (payload on the console's libc): after fclose(stdout) or fclose(stderr), freopen into a missing directory and of "" gives ENOENT, of a 320-byte path ENAMETOOLONG, of a null filename EBADF; a good path returns the same FILE* on the lowest free descriptor and reads back what was written. Verify run on 144298bfca: guest_standard_streams* pass; its AGC failures are main's on that runner.
  • Linux x86-64 container (Ubuntu 24.04, GCC 13.3, Release, llvmpipe): PPSA99630 on main a6dcea9279 with no usable /download0 dies with the lines above; with this change it runs through to its own data check and exits 0, as it does when /download0 works (details on #9762). With a complete package the title doesn't reach this path, so this is Unblocks: none; the trace is the title's, the behaviour is FreeBSD's.
  • guest_standard_streams gains CheckClosedStreamReopen (a closed tmpfile stream: a failed reopen into a missing directory gives ENOENT, one with a 300-byte name gives ENAMETOOLONG from the resolver, a null filename gives EINVAL, the stream stays EBADF after each; then a reopen for writing, a write, a reopen for reading and a read, and the file holds the text) and the --reopen-closed-stdout case (fclose(stdout), printf fails with EBADF, the overlong reopen fails with ENAMETOOLONG and printf still EBADF, freopen returns stdout, printf and puts land in the file). Hosted Linux runner: the first verify run passed those tests on the diff before the resolver fix; the run on 1c2eed30a2 passes them too (Ubuntu 24.04, GCC, Release).
  • macOS 26.2, Apple M5, Apple clang 21, x86-64 under Rosetta 2, on @mugurc's ci/macos-series-2 integration tree: --reopen-closed-stdout (with the overlong-path check), --closed-stdout and --exclusive-stdout pass; the plain case runs CheckClosedStreamReopen and then stops at that tree's pre-existing CheckFlushWhileReading failure (an fflush on a reading stream changes the next read there, before and after this change; noted for #1).
  • Windows 11, MinGW-w64 GCC 15.2 (UCRT), Release, by @Dom3005 on 1c2eed30a2 merged onto main 11f976b27c: the four guest_standard_streams* tests pass 5 of 5, including the new case and CheckClosedStreamReopen; with FileStream.hpp and FileAndHeap.cpp restored from main the two closed-stream cases abort with what(): FileStream: closed stream. The full suite passes 1887 of 1895, the 8 failures being AGC tests that fail on that machine's AMD GPU on main (#7451, #9056, #8310).
  • check_conventions.py passes. pr_overlap.py reports no conflicting lines; the shared files it could not compare belong to PRs that conflict with main.

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:4968167924 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9763). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-22T13:27:00Z. --- ### What `freopen` on a stream that had been closed aborted the process: `FileStream::Reopen` starts with `GetHandle()`, which throws `FileStream: closed stream` when the handle is gone. PPSA99630 (OpenMW, the Morrowind port in the homebrew catalog, `v1.0.1`, bring-up thread #9762) does that when `/download0` cannot be used: its first `freopen` of `stdout` fails and leaves the stream closed, and a later `freopen` of it dies on `main` before the title prints anything: ``` [libc] unhandled exception 'St13runtime_error' thrown from 0x7ffff5d4ddda terminate called after throwing an instance of 'std::runtime_error' what(): FileStream: closed stream ``` (`0x35dda` into `libc.prx`, `freopen_nid_postfix`.) FreeBSD's `freopen` keeps a closed `FILE` and reopens it: with `fp->_flags == 0` it "holds on to it", opens the path on a new descriptor and makes `fp` that stream ([freopen.c](https://github.com/freebsd/freebsd-src/blob/releng/11.4/lib/libc/stdio/freopen.c), releng/11.4). A failed open leaves it closed, with the open's `errno`. `Reopen` now does the same for a closed stream: it opens the path through the caller's opener and adopts the handle, or fails with the open's error (`ENOENT` for an empty path, as `open("")` gives there). A path the resolver rejects before any open (an overlong name, an unavailable mount) used to reach `Close()` on the closed stream and throw the same way; `freopen` now closes only a stream that is open there and returns the resolver's error. A null filename on a closed stream answers `EBADF`, as a PS5 does (an open stream keeps answering `ENOTSUP`, since mode-only reopening is not supported here). The guest state reset and descriptor bookkeeping that the open-stream path did at its end moved into `Adopt`, which both paths use. A closed stream whose reopen fails keeps answering `EBADF`, as before. Only the standard streams can reach this, since a dynamic stream is freed by its `fclose`. The debt entry records the differences from the console: the new descriptor is whatever the host hands out, where a PS5 takes the lowest free one, and a write to the closed stream answers `EBADF` here (as on `main`), where the console's `fputs`/`fputc` leave `errno` unchanged and its `fprintf` gives `EINVAL`. ### Tested - PS5 (payload on the console's libc): after `fclose(stdout)` or `fclose(stderr)`, `freopen` into a missing directory and of `""` gives `ENOENT`, of a 320-byte path `ENAMETOOLONG`, of a null filename `EBADF`; a good path returns the same `FILE*` on the lowest free descriptor and reads back what was written. [Verify run on `144298bfca`](https://github.com/rooklz/AnyPS5/actions/runs/40139181967): `guest_standard_streams*` pass; its AGC failures are `main`'s on that runner. - Linux x86-64 container (Ubuntu 24.04, GCC 13.3, Release, llvmpipe): PPSA99630 on `main` `a6dcea9279` with no usable `/download0` dies with the lines above; with this change it runs through to its own data check and exits 0, as it does when `/download0` works (details on #9762). With a complete package the title doesn't reach this path, so this is `Unblocks: none`; the trace is the title's, the behaviour is FreeBSD's. - `guest_standard_streams` gains `CheckClosedStreamReopen` (a closed `tmpfile` stream: a failed reopen into a missing directory gives `ENOENT`, one with a 300-byte name gives `ENAMETOOLONG` from the resolver, a null filename gives `EINVAL`, the stream stays `EBADF` after each; then a reopen for writing, a write, a reopen for reading and a read, and the file holds the text) and the `--reopen-closed-stdout` case (`fclose(stdout)`, `printf` fails with `EBADF`, the overlong reopen fails with `ENAMETOOLONG` and `printf` still `EBADF`, `freopen` returns `stdout`, `printf` and `puts` land in the file). Hosted Linux runner: the [first verify run](https://github.com/rooklz/AnyPS5/actions/runs/39785404193) passed those tests on the diff before the resolver fix; the [run on `1c2eed30a2`](https://github.com/rooklz/AnyPS5/actions/runs/39806954271) passes them too (Ubuntu 24.04, GCC, Release). - macOS 26.2, Apple M5, Apple clang 21, x86-64 under Rosetta 2, on @mugurc's `ci/macos-series-2` integration tree: `--reopen-closed-stdout` (with the overlong-path check), `--closed-stdout` and `--exclusive-stdout` pass; the plain case runs `CheckClosedStreamReopen` and then stops at that tree's pre-existing `CheckFlushWhileReading` failure (an `fflush` on a reading stream changes the next read there, before and after this change; noted for #1). - Windows 11, MinGW-w64 GCC 15.2 (UCRT), Release, by @Dom3005 on `1c2eed30a2` merged onto `main` `11f976b27c`: the four `guest_standard_streams*` tests pass 5 of 5, including the new case and `CheckClosedStreamReopen`; with `FileStream.hpp` and `FileAndHeap.cpp` restored from `main` the two closed-stream cases abort with `what(): FileStream: closed stream`. The full suite passes 1887 of 1895, the 8 failures being AGC tests that fail on that machine's AMD GPU on `main` (#7451, #9056, #8310). - `check_conventions.py` passes. `pr_overlap.py` reports no conflicting lines; the shared files it could not compare belong to PRs that conflict with `main`. <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> ### 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 <!-- #PR, or none --> - [x] Fixes: none <!-- issue it closes as Fixes #N, or none --> - [x] Unblocks: none <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> - [x] GPUs tested: n/a <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> - [x] AI-assisted: yes <!-- yes / no -->
rooklz commented 2026-10-22 13:34:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-22T13:34:42Z.


Rebased onto current main (8b3e39832a): head a783c27f41, same diff.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6342083279 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9763#issuecomment-6342083279). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-22T13:34:42Z. --- Rebased onto current `main` (`8b3e39832a`): head `a783c27f41`, same diff.
harisibrar1 commented 2026-10-22 13:40:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by harisibrar1 on 2026-10-22T13:40:44Z.

Review: COMMENTED


Checked against main 8b3e39832a and FreeBSD 11.4 lib/libc/stdio/freopen.c:

  • This merges cleanly, and main still throws from Reopen → GetHandle() on a closed stream, so it isn't duplicated. The new branch matches FreeBSD's _flags == 0 path: it opens on a new descriptor, and on failure the stream stays free with the open's errno.
  • One abort remains on the same path. When ResolvePathError_nid_no_patch fails, freopen_nid_postfix (FileAndHeap.cpp:365-367) calls stream->Close() for anything that isn't IsHostStandard(). A closed stream has a null handle, so it lands there, and Close() → GetHandle() throws FileStream: closed stream. For example, after fclose(stdout), freopen(<1024-byte path>, "w", stdout) still terminates, and so does a path under a blocked mount such as an unavailable /download0. FreeBSD returns NULL with ENAMETOOLONG/ENOENT and leaves fp free. Guarding that branch with stream->IsOpen() and adding the case to CheckClosedStreamReopen would close it.
  • Optional, pre-existing: for a NULL filename, FreeBSD answers EINVAL when fp is closed, where main returns 45 before looking at the stream.

Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5615145616 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9763#pullrequestreview-5615145616). Originally posted by [harisibrar1](https://github.com/harisibrar1) on 2026-10-22T13:40:44Z. **Review:** COMMENTED --- Checked against main 8b3e39832a and FreeBSD 11.4 lib/libc/stdio/freopen.c: - This merges cleanly, and main still throws from `Reopen` → `GetHandle()` on a closed stream, so it isn't duplicated. The new branch matches FreeBSD's `_flags == 0` path: it opens on a new descriptor, and on failure the stream stays free with the open's errno. - One abort remains on the same path. When `ResolvePathError_nid_no_patch` fails, `freopen_nid_postfix` (FileAndHeap.cpp:365-367) calls `stream->Close()` for anything that isn't `IsHostStandard()`. A closed stream has a null handle, so it lands there, and `Close()` → `GetHandle()` throws `FileStream: closed stream`. For example, after `fclose(stdout)`, `freopen(<1024-byte path>, "w", stdout)` still terminates, and so does a path under a blocked mount such as an unavailable `/download0`. FreeBSD returns NULL with `ENAMETOOLONG`/`ENOENT` and leaves `fp` free. Guarding that branch with `stream->IsOpen()` and adding the case to `CheckClosedStreamReopen` would close it. - Optional, pre-existing: for a NULL filename, FreeBSD answers `EINVAL` when `fp` is closed, where main returns 45 before looking at the stream. Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.
MarcZX10 commented 2026-10-22 14:48:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T14:48:36Z.

Review: CHANGES_REQUESTED


The closed-stream reopen path still has a failure case on the current head. I verified the control flow against this commit; the existing test covers an open failure after path resolution, but not a path-resolution error.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5616121713 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9763#pullrequestreview-5616121713). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-22T14:48:36Z. **Review:** CHANGES_REQUESTED --- The closed-stream reopen path still has a failure case on the current head. I verified the control flow against this commit; the existing test covers an open failure after path resolution, but not a path-resolution error.
MarcZX10 commented 2026-10-22 17:01:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T17:01:45Z.

Review: COMMENTED


The latest head 1c2eed30a2d18862352c02b79f6fc7046349fb47 addresses both issues I raised: path-resolution failure only closes an open stream, and a null filename on a closed stream returns EINVAL. The new ordinary-stream and stdout tests cover resolver errors, ENAMETOOLONG, failed writes, successful subsequent reopen, and retained host stdout behavior. The author reports the focused Linux suite passing on this head; current hosted relinker/register-context/write-watch checks also pass, while product Windows is skipped. Current-main conventions, diff-check and merge-tree pass. This branch is based on 8b3e39832a, 32 commits behind current main (11f976b27c16ed91633f00039dba5dfd97dd7cc1); please refresh and rerun the stream tests before merge. I did not rerun them locally.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5617916562 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9763#pullrequestreview-5617916562). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-22T17:01:45Z. **Review:** COMMENTED --- The latest head `1c2eed30a2d18862352c02b79f6fc7046349fb47` addresses both issues I raised: path-resolution failure only closes an open stream, and a null filename on a closed stream returns `EINVAL`. The new ordinary-stream and stdout tests cover resolver errors, `ENAMETOOLONG`, failed writes, successful subsequent reopen, and retained host stdout behavior. The author reports the focused Linux suite passing on this head; current hosted relinker/register-context/write-watch checks also pass, while product Windows is skipped. Current-main conventions, diff-check and merge-tree pass. This branch is based on `8b3e39832a`, 32 commits behind current `main` (`11f976b27c16ed91633f00039dba5dfd97dd7cc1`); please refresh and rerun the stream tests before merge. I did not rerun them locally.
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!9763
No description provided.