feat(libc): copy the runtime log into a file with ANYPS5_LOG_FILE #12715

Merged
MarcZX10 merged 21 commits from upstream-pr/12715 into main 2026-10-30 04:51:35 +00:00
MarcZX10 commented 2026-10-29 04:14:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T04:14:54Z.


What

ANYPS5_LOG_FILE=<path> makes a converted executable also write its log into a file, so a user can attach it to a bug report. Unset or empty keeps today's behaviour exactly (no thread, pipe or descriptor).

Why a copy of the standard streams: the runtime log is not behind one funnel. APS5_LOG_OUT/APS5_LOG_ERR (WriteLogLine, LogSink) go to stdout and stderr, APS5_HIT and several hundred direct fprintf(stderr, ...) calls bypass it, the guest's own stdout/stderr are the host streams, and the crash/abort reporters write straight to descriptor 2 / GetStdHandle(STD_ERROR_HANDLE). A funnel would miss most of it and a plain redirect would stop the terminal output. So libc, at load, diverts descriptors 1 and 2 (the standard handles on Windows) into two pipes; one thread per pipe writes each chunk to the original stream at once and each whole line to the file under one lock (line-atomic across both streams).

Crash safety: a tee thread cannot be relied on after a fatal fault, so the crash reporters no longer write to the pipe. log_file::CrashWrite takes the lock for at most 250 ms, moves what is still in the pipes into the file, then writes the report line to the original stderr and to the file directly (atomics, read, write, nanosleep; async-signal-safe). LibcRunEndFlush and an atexit handler (after fflush(nullptr)) drain at every exit/abort path. LogFileRelease puts the real streams back before LoadExec replaces the process.

Behaviour: opened for appending (never truncated; documented, no {pid} templating), relative paths resolve against the working directory, an unopenable path ends the process at load with status 1 and ANYPS5_LOG_FILE: cannot open "<path>" for appending: <OS error>. No size cap (documented, recorded as debt). Timestamps follow APS5_LOG_TIMESTAMPS because the bytes are copied. A file that stops being writable is reported once and the terminal goes on. No terminal (closed or absent standard stream) means file only.

Commits: platform primitives; tee, session and startup; test; shutdown declarations; end/abort flush; CallTrace abort report; Windows crash report; two LoadExec/Export release sites; env table, USAGE, issue template; four debt entries.

Files shared with open PRs: none of the listed ones (#12379, #12536, #12569) are touched; core/libs/prx/libc/CMakeLists.txt, docs/user/USAGE.md, docs/dev/ENVIRONMENT.md and docs/dev/debt/libc.md are shared with any PR editing those files.

Tested

Linux x86-64, g++ 12, throwaway archive build on a shared 8-CPU host (head bef4e7d3bf; the test results below were taken on that head, before merging the current main). New log_file (ctest, about 0.3 s) passes: both streams reach terminal and file in order, a partial line of one stream is not split by the other, six concurrent writers of 3000-byte lines never mix, long lines (300 KB and above the 1 MiB carry) and a last line without newline are whole, append and relative path, unopenable path and directory errors, unset/empty reach no factory and open no descriptor, closed/absent terminal and full disk keep the other side, crash write reaches the file in order with and without running tee threads, and child processes check terminal output, file, startup failure, _exit after flush, simulated crash report, a replacement through exec after release (no SIGPIPE), and that enabling adds exactly two threads. 40 consecutive runs of the final head pass. The concurrency case writes each stream through one writer at a time, because a pipe write is atomic only up to PIPE_BUF (512 bytes on macOS), as rooklz found on macOS; the tee's own line atomicity across the two streams is what it checks.

Existing tests, upstream/main base (319621ba2e) vs branch, identical per test: guest_standard_streams (5 variants), guest_freopen_host_standard, guest_call_trace, guest_call_trace_abort, guest_call_trace_abort_race, log_macros, log_macros_timestamps, loadexec_arguments, guest_system_exit_parameters, guest_system_exit, guest_lnc_util_load_exec_exit, guest_requested_exit, guest_quick_exit, guest_immediate_exit, guest_immediate_exit_drain, guest_nested_exit, guest_exit_finalizers_before_shutdown, guest_host_standard_error all Passed on both. Not Run on both (target not built): guest_call_trace_fixed_base_abort, guest_exit_order, guest_backtrace, agc_async_log_fatal, guest_thread_atexit, guest_system_load_exec_standard_error. The same passing tests also pass on the branch with ANYPS5_LOG_FILE set, and the abort report appears in the file.

Negative controls (broken copy of the code, new test fails at the intended case, then restored): terminal copy skipped, partial line written at once, crash write without draining the pipes, no final partial-line flush, truncate instead of append, empty value treated as set, error text without the variable name, exit handler without fflush, release that restores nothing (the replacement dies of a broken pipe), unset reaching the factory, a terminal error stopping the file. The lock: replacing Tee::lock with return true; is caught in 14 of 20 runs on this 8-CPU host. rooklz measured 20 of 20 on a multi-CPU Ubuntu and 17 of 20 on macOS arm64. NOT negative-controlled: the load-exec release call sites, the Process.cpp/CallTrace.cpp/CrashReport.cpp hook calls (covered only by the existing abort tests passing and by the manual env-set run), file-failure reporting text beyond its substring.

Static checks clean: check_conventions.py --base upstream/main, git diff --check, header audit, env_reference.py --check. A merge simulation with current upstream/main is clean; the tests were not re-run on the merged tree.

Independent Windows check by JJenkx (Windows 11, WinLibs GCC 15.2 UCRT, this head merged onto main, guest_formatting_tests with the variable set): a plain path and a path with non-ASCII characters both give exit 0, the console bytes unchanged (120 bytes as without the variable) and a log file with the start line plus all console lines at that exact path, so the variable is read as UTF-16, the path survives to CreateFileW and output is teed, not diverted. macOS: rooklz built and ran the test and found the PIPE_BUF flake fixed above; I did not run macOS.

NOT RUN or not checked: Windows unwritable or invalid path, the Windows crash report and abort() flushes, Windows LoadExec, the console/redirected/absent-handle cases beyond the plain run above, start under the loader lock beyond that run (only MinGW syntax check on my side); macOS by me. No real console title, no GUI-less run. These are recorded in docs/dev/debt/libc.md.

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:5062047614 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12715). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-29T04:14:54Z. --- ### What `ANYPS5_LOG_FILE=<path>` makes a converted executable also write its log into a file, so a user can attach it to a bug report. Unset or empty keeps today's behaviour exactly (no thread, pipe or descriptor). Why a copy of the standard streams: the runtime log is not behind one funnel. `APS5_LOG_OUT`/`APS5_LOG_ERR` (`WriteLogLine`, `LogSink`) go to stdout and stderr, `APS5_HIT` and several hundred direct `fprintf(stderr, ...)` calls bypass it, the guest's own stdout/stderr are the host streams, and the crash/abort reporters write straight to descriptor 2 / `GetStdHandle(STD_ERROR_HANDLE)`. A funnel would miss most of it and a plain redirect would stop the terminal output. So libc, at load, diverts descriptors 1 and 2 (the standard handles on Windows) into two pipes; one thread per pipe writes each chunk to the original stream at once and each whole line to the file under one lock (line-atomic across both streams). Crash safety: a tee thread cannot be relied on after a fatal fault, so the crash reporters no longer write to the pipe. `log_file::CrashWrite` takes the lock for at most 250 ms, moves what is still in the pipes into the file, then writes the report line to the original stderr and to the file directly (atomics, `read`, `write`, `nanosleep`; async-signal-safe). `LibcRunEndFlush` and an `atexit` handler (after `fflush(nullptr)`) drain at every exit/abort path. `LogFileRelease` puts the real streams back before LoadExec replaces the process. Behaviour: opened for appending (never truncated; documented, no `{pid}` templating), relative paths resolve against the working directory, an unopenable path ends the process at load with status 1 and `ANYPS5_LOG_FILE: cannot open "<path>" for appending: <OS error>`. No size cap (documented, recorded as debt). Timestamps follow `APS5_LOG_TIMESTAMPS` because the bytes are copied. A file that stops being writable is reported once and the terminal goes on. No terminal (closed or absent standard stream) means file only. Commits: platform primitives; tee, session and startup; test; shutdown declarations; end/abort flush; CallTrace abort report; Windows crash report; two LoadExec/Export release sites; env table, USAGE, issue template; four debt entries. Files shared with open PRs: none of the listed ones (#12379, #12536, #12569) are touched; `core/libs/prx/libc/CMakeLists.txt`, `docs/user/USAGE.md`, `docs/dev/ENVIRONMENT.md` and `docs/dev/debt/libc.md` are shared with any PR editing those files. ### Tested Linux x86-64, g++ 12, throwaway archive build on a shared 8-CPU host (head bef4e7d3bf; the test results below were taken on that head, before merging the current main). New `log_file` (ctest, about 0.3 s) passes: both streams reach terminal and file in order, a partial line of one stream is not split by the other, six concurrent writers of 3000-byte lines never mix, long lines (300 KB and above the 1 MiB carry) and a last line without newline are whole, append and relative path, unopenable path and directory errors, unset/empty reach no factory and open no descriptor, closed/absent terminal and full disk keep the other side, crash write reaches the file in order with and without running tee threads, and child processes check terminal output, file, startup failure, `_exit` after flush, simulated crash report, a replacement through `exec` after release (no SIGPIPE), and that enabling adds exactly two threads. 40 consecutive runs of the final head pass. The concurrency case writes each stream through one writer at a time, because a pipe write is atomic only up to PIPE_BUF (512 bytes on macOS), as rooklz found on macOS; the tee's own line atomicity across the two streams is what it checks. Existing tests, upstream/main base (319621ba2e) vs branch, identical per test: guest_standard_streams (5 variants), guest_freopen_host_standard, guest_call_trace, guest_call_trace_abort, guest_call_trace_abort_race, log_macros, log_macros_timestamps, loadexec_arguments, guest_system_exit_parameters, guest_system_exit, guest_lnc_util_load_exec_exit, guest_requested_exit, guest_quick_exit, guest_immediate_exit, guest_immediate_exit_drain, guest_nested_exit, guest_exit_finalizers_before_shutdown, guest_host_standard_error all Passed on both. Not Run on both (target not built): guest_call_trace_fixed_base_abort, guest_exit_order, guest_backtrace, agc_async_log_fatal, guest_thread_atexit, guest_system_load_exec_standard_error. The same passing tests also pass on the branch with `ANYPS5_LOG_FILE` set, and the abort report appears in the file. Negative controls (broken copy of the code, new test fails at the intended case, then restored): terminal copy skipped, partial line written at once, crash write without draining the pipes, no final partial-line flush, truncate instead of append, empty value treated as set, error text without the variable name, `exit` handler without `fflush`, release that restores nothing (the replacement dies of a broken pipe), unset reaching the factory, a terminal error stopping the file. The lock: replacing `Tee::lock` with `return true;` is caught in 14 of 20 runs on this 8-CPU host. rooklz measured 20 of 20 on a multi-CPU Ubuntu and 17 of 20 on macOS arm64. NOT negative-controlled: the load-exec release call sites, the Process.cpp/CallTrace.cpp/CrashReport.cpp hook calls (covered only by the existing abort tests passing and by the manual env-set run), file-failure reporting text beyond its substring. Static checks clean: `check_conventions.py --base upstream/main`, `git diff --check`, header audit, `env_reference.py --check`. A merge simulation with current upstream/main is clean; the tests were not re-run on the merged tree. Independent Windows check by JJenkx (Windows 11, WinLibs GCC 15.2 UCRT, this head merged onto main, `guest_formatting_tests` with the variable set): a plain path and a path with non-ASCII characters both give exit 0, the console bytes unchanged (120 bytes as without the variable) and a log file with the start line plus all console lines at that exact path, so the variable is read as UTF-16, the path survives to `CreateFileW` and output is teed, not diverted. macOS: rooklz built and ran the test and found the PIPE_BUF flake fixed above; I did not run macOS. NOT RUN or not checked: Windows unwritable or invalid path, the Windows crash report and `abort()` flushes, Windows LoadExec, the console/redirected/absent-handle cases beyond the plain run above, start under the loader lock beyond that run (only MinGW syntax check on my side); macOS by me. No real console title, no GUI-less run. These are recorded in `docs/dev/debt/libc.md`. ### Checklist - [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
rooklz commented 2026-10-29 04:54:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-29T04:54:30Z.

Review: COMMENTED


I ran the new log_file test on macOS, which the body does not cover. On macOS it fails about half the time. The cause is the test, not the tee.

What I ran. I built LogFile.cpp, LogFilePlatform.cpp and tests/LogFile.cpp at 3b74c0f9a2 on their own with clang, ASan and UBSan. They link with no shim.

host runs failures
macOS 26 arm64 20 11
macOS 26 x86_64 (Rosetta) 20 9
macOS arm64, a further 30 runs 30 28
Ubuntu 24.04 g++ 13.3 / glibc 2.39 (amd64 container) 20 0

Every failure is the same message: a line of the file mixes bytes of two writers (ConcurrentWriters, L147).

Cause. ConcurrentWriters runs three threads per pipe. Each thread write()s a 3,0xx-byte line straight into the source pipe (Rig::Write, then WriteAll). POSIX only promises that a pipe write is atomic up to PIPE_BUF. On macOS PIPE_BUF and fpathconf(_PC_PIPE_BUF) are both 512. Linux gives 4096, and 3 KB fits under that. So on macOS two writers on the same pipe interleave inside the pipe, before the tee ever reads the bytes. I printed the writer letters found in each mixed line over 15 runs. Every mix paired two writers of the same parity, which means the same stream: a+c, a+e, c+e, b+f, d+f. No mixed line paired stdout with stderr, so the tee's line-atomicity holds.

Two controls back this up:

  • Shrinking the payload to 400 bytes (under 512): 0 failures in 30 runs.
  • Serialising writers per pipe in the rig: 0 failures in 40 runs on arm64 and 0 in 40 on x86_64. The suite runs in about 0.55 s.

Suggested fix (test only). Lock writes per pipe in the rig. This keeps the 3,000-byte lines and the cross-stream race the test exists to check:

 #include <string>
+#include <mutex>
 #include <thread>
@@ struct Rig {
+    std::mutex outputWrites;
+    std::mutex errorWrites;
+
     void Write(int standard, const std::string& text) {
+        const std::lock_guard<std::mutex> hold(standard == StandardOutput ? outputWrites : errorWrites);
         Require(WriteAll(standard == StandardOutput ? output.write : errors.write, text.data(), text.size()), "source write");
     }

The lock you did not negative-control. I replaced Tee::lock with return true;:

  • With the fix above on macOS arm64, the test catches it in 17 of 20 runs.
  • With your unchanged test on Ubuntu 24.04 glibc 2.39 (amd64, several CPUs), it catches it in 20 of 20 runs.

So the concurrency row does detect a missing lock once more than one CPU is available. The "not detected" result in the body may come from the 1-CPU host.

Related wording. USAGE says "Lines are written to the file whole", and the debt entry says each stream is kept in order. Both hold only per write() call. Two threads of a title writing lines longer than PIPE_BUF to the same stream can still interleave inside that stream's pipe, and that is 512 bytes on macOS. A terminal shows the same interleaving, so this is not a regression. Still, a clause such as "a line one write call produced" would match what the code guarantees.

Also checked: conventions (--head) pass, and git merge-tree against upstream main 52c09d567d is clean. I did not run the Windows path or the full guest build.

AI-assisted: yes

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5693027934 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12715#pullrequestreview-5693027934). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-29T04:54:30Z. **Review:** COMMENTED --- I ran the new `log_file` test on macOS, which the body does not cover. On macOS it fails about half the time. The cause is the test, not the tee. **What I ran.** I built `LogFile.cpp`, `LogFilePlatform.cpp` and `tests/LogFile.cpp` at 3b74c0f9a2 on their own with clang, ASan and UBSan. They link with no shim. | host | runs | failures | |---|---|---| | macOS 26 arm64 | 20 | 11 | | macOS 26 x86_64 (Rosetta) | 20 | 9 | | macOS arm64, a further 30 runs | 30 | 28 | | Ubuntu 24.04 g++ 13.3 / glibc 2.39 (amd64 container) | 20 | 0 | Every failure is the same message: `a line of the file mixes bytes of two writers` (`ConcurrentWriters`, L147). **Cause.** `ConcurrentWriters` runs three threads per pipe. Each thread `write()`s a 3,0xx-byte line straight into the source pipe (`Rig::Write`, then `WriteAll`). POSIX only promises that a pipe write is atomic up to `PIPE_BUF`. On macOS `PIPE_BUF` and `fpathconf(_PC_PIPE_BUF)` are both **512**. Linux gives 4096, and 3 KB fits under that. So on macOS two writers on the *same* pipe interleave inside the pipe, before the tee ever reads the bytes. I printed the writer letters found in each mixed line over 15 runs. Every mix paired two writers of the same parity, which means the same stream: `a+c`, `a+e`, `c+e`, `b+f`, `d+f`. No mixed line paired stdout with stderr, so the tee's line-atomicity holds. Two controls back this up: - Shrinking the payload to 400 bytes (under 512): 0 failures in 30 runs. - Serialising writers per pipe in the rig: 0 failures in 40 runs on arm64 and 0 in 40 on x86_64. The suite runs in about 0.55 s. **Suggested fix (test only).** Lock writes per pipe in the rig. This keeps the 3,000-byte lines and the cross-stream race the test exists to check: ```diff #include <string> +#include <mutex> #include <thread> @@ struct Rig { + std::mutex outputWrites; + std::mutex errorWrites; + void Write(int standard, const std::string& text) { + const std::lock_guard<std::mutex> hold(standard == StandardOutput ? outputWrites : errorWrites); Require(WriteAll(standard == StandardOutput ? output.write : errors.write, text.data(), text.size()), "source write"); } ``` **The lock you did not negative-control.** I replaced `Tee::lock` with `return true;`: - With the fix above on macOS arm64, the test catches it in 17 of 20 runs. - With your unchanged test on Ubuntu 24.04 glibc 2.39 (amd64, several CPUs), it catches it in 20 of 20 runs. So the concurrency row does detect a missing lock once more than one CPU is available. The "not detected" result in the body may come from the 1-CPU host. **Related wording.** USAGE says "Lines are written to the file whole", and the debt entry says each stream is kept in order. Both hold only per `write()` call. Two threads of a title writing lines longer than `PIPE_BUF` to the same stream can still interleave inside that stream's pipe, and that is 512 bytes on macOS. A terminal shows the same interleaving, so this is not a regression. Still, a clause such as "a line one `write` call produced" would match what the code guarantees. Also checked: conventions (`--head`) pass, and `git merge-tree` against upstream main 52c09d567d is clean. I did not run the Windows path or the full guest build. AI-assisted: yes
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!12715
No description provided.