Skip to content

RT-368: flush C streams on normal exit - #5221

Open
miniongk wants to merge 3 commits into
ItsNotRexed:mainfrom
miniongk:rt-368-normal-exit-flush
Open

miniongk wants to merge 3 commits into
ItsNotRexed:mainfrom
miniongk:rt-368-normal-exit-flush

Conversation

@miniongk

@miniongk miniongk commented Nov 23, 2026 •

Copy link
Copy Markdown

Claimed in the coordination issue as: RT-368 in #5156.

Depends on: #5194 (overlapping RT-368 production change; this PR's pre-cleanup regression is complementary).

What and why

A normal CRT exit flushes every open C stream. The mapped-title shim ran the title's atexit handlers but then ended the run without flushing them; the host only flushes stdout/stderr afterwards, so buffered output on an independent file stream could be lost.

  • Flush all C streams after the handlers in exit().
  • Do the same when the mapped entry point returns normally.
  • Leave _exit, quick_exit, ExitProcess and abort unchanged.
  • Extend process_cmdline_test with entry-return and exit() probes that write a temporary file without flushing or closing it. The test checks the open stream's file size before closing it, so later host cleanup cannot hide the bug.

Tested

  • git diff --check — passed.
  • Fork Runtime CI at f71b71: Windows build succeeded and process_cmdline passed. The only remaining Windows failure was d3d12_sparse_queue_family (vkCreateInstance failed); the Linux job failed in untouched vk_harness.cpp pipeline-binary declarations.
  • Baseline main Runtime CI reproduces the same Linux pipeline-binary build failure and Windows d3d12_sparse_queue_family / vkCreateInstance failure, confirming both predate this PR.
  • Independent Windows reviewers confirmed that the regression passes with this production fix and fails on main after allowing file sharing in the original fixture (see PR comments).
  • Local C++ execution was unavailable because this machine has no Visual Studio C++ tools or CMake. No GPU or driver was used for the authoring run; this is a CPU-only process-shim change.

AI-assisted: yes, Kimi Code.

Checklist

  • No game data, keys or decryption, including in logs or reports quoted here.
  • No new translator rule; the contract table is not applicable.

@Kam471 Kam471 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.

Blocking: the new flush test fails on Windows 11 in both cases.

Built and ran process_cmdline_test at 87dc24bc0 (MSVC RelWithDebInfo), twice, same result:

FAIL entry return: exit code 17 (want 17), buffered contents were not flushed
FAIL exit(): exit code 23 (want 23), buffered contents were not flushed
exit=1

The entry codes are right (17 and 23), so the entry and exit() path ran, but the parent reads an empty file after run_entry returns: the test's buffered FILE* was not flushed. The change adds std::fflush(nullptr) in game_exit and after the entry returns in game_thread; on this host that does not reach the stream the test opened before entering run_entry. git diff --check clean.

Duplicate: #5194 (trxoo-glitch, 09:11, earlier) is the same RT-368 work and its run_tiny_atexit ctest passes here (I verified it at c2efc27e5). The two branches conflict in runtime/shims/process.cpp. Recommend keeping #5194 and closing this one, or diagnosing why fflush(nullptr) does not flush the pre-entry stream in this test before re-submitting.

@thehollowedone

Copy link
Copy Markdown

I reproduced both process_cmdline failures at 87dc24bc on Windows 11 x64 build 26300 with MSVC 19.44.35230, SDK 10.0.26100.0 and RelWithDebInfo. Both synthetic files contained the expected 19 bytes after run_entry, but the fixture's _wfopen_s reader returned EACCES while the writer was still open.

I changed only the scratch test fixture to open both handles with _wfsopen(..., _SH_DENYNO). With the PR's production code, both probes read the expected text and CTest passed (1/1). With 3faac557's production code and the same adjusted fixture, the readers opened successfully but read zero bytes, so both probes failed. The entry-return and exit() codes were 17 and 23 on both builds.

Allowing sharing in the fixture preserves the read-before-close check and lets it distinguish the fix from the base on this host. CPU only. AI-assisted.

@XFlawless1

Copy link
Copy Markdown
Contributor

Reproduced @thehollowedone's result independently (Windows 11 Pro 26300, MSVC 19.44, 87dc24bc merged onto main 3faac557): as written, process_cmdline fails on the PR and on main. With both opens changed to _wfsopen(..., _SH_DENYNO), it passes on the PR and fails on main.

One coordination note: #5194 fixes the same item (RT-368) in the same two places in runtime/shims/process.cpp (after the handlers in game_exit, and after a returning entry point). It also calls msvcrt.dll's fflush when that DLL is loaded, for MinGW titles. The two complement each other. #5194's check_atexit buffered mode passes on main too when run natively (see the comments there: the ExitProcess → DLL detach flush hides the bug). This PR's read-before-close check, with sharable opens, is the one that tells the fix from main on Windows. It may be worth landing one change with both the msvcrt flush and this check.

No game files. AI-assisted (Claude Code).

@trvxoo-glitch

Copy link
Copy Markdown

Tested 87dc24b on Windows 10 Pro 22H2 (19045), AMD Radeon RX 6700 XT (driver 32.0.21045.29003), MSVC 14.51.36231, Windows SDK 10.0.26100, Ninja RelWithDebInfo: fail, but the cause is in the test, not the fix.

ctest -R "atexit|exit_code|process_cmdline":

  • run_tiny_atexit: pass (8 termination paths match the Windows sequence)
  • run_tiny_game_exit_code, run_tiny_game_fixed_exit_code: pass
  • process_cmdline: fail
    FAIL entry return: exit code 17 (want 17), buffered contents were not flushed
    FAIL exit(): exit code 23 (want 23), buffered contents were not flushed
    

Cause: _wfopen_s opens files with _SH_SECURE, so a file opened for writing is not shared. While g_flush_stream is still open, the second _wfopen_s(&copy, path, L"r") fails, contents stays empty, and the check reports "not flushed" whether or not the flush happened. I switched both opens to _wfsopen(..., _SH_DENYNO) (and added #include <share.h>), leaving everything else unchanged:

  • with this PR's process.cpp: process_cmdline passes
  • with main's process.cpp (3faac55): it fails with the same two lines

So the fix works, and once the test can read the file it catches the bug.

Optional, not needed for RT-368:

  • game_exit flushes even when take_exit_lock() fails, i.e. on the second thread that is waiting for the first exit. It's harmless, but putting the flush inside the if would follow the CRT's order more closely.
  • A MinGW title that uses msvcrt.dll keeps its streams in that DLL, so fflush(nullptr) doesn't reach them. Calling msvcrt.dll's own fflush(nullptr) when it's loaded would cover that case. This isn't tested here.
  • For reference, an end-to-end tiny_atexit variant that writes a fully buffered file and never closes it passes on unpatched main too, because gta6rt's own CRT exit flushes the shared UCRT. A unit test like yours is the right regression test.

AI-assisted comment.

@Kam471 Kam471 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.

Correction to my earlier blocker, based on the two independent reproductions in the comments (thehollowedone and XFlawless1):

The process_cmdline_test failures are in the test fixture, not the production change. Both probes write the expected 19 bytes, but the parent's _wfopen_s reader gets EACCES while the writer handle is still open; opening both with _wfsopen(..., _SH_DENYNO) makes the test pass on this PR and fail on main 3faac557, which is the differential the test wants.

So: product code is fine; the fixture needs the shared-open change before the test can be trusted. Still the same RT-368 work as #5194 (the branches conflict in runtime/shims/process.cpp), so one of the two should land — this PR additionally covers the returning-entry flush and the process_cmdline probe.

@gertify

gertify commented Nov 23, 2026

Copy link
Copy Markdown

Tested 87dc24b on Intel UHD 770, driver 32.0.101.7088, Windows 11, MSVC 19.44, with a fresh native build (gta6rt.exe and process_cmdline_test.exe deleted and rebuilt): process_cmdline fails. ctest prints "Test #37: process_cmdline ... ***Failed 0.68 sec" and "0% tests passed, 1 tests failed out of 1", and running process_cmdline_test.exe directly exits 1 with "FAIL entry return: exit code 17 (want 17), buffered contents were not flushed" and "FAIL exit(): exit code 23 (want 23), buffered contents were not flushed". On main 3faac55, built fresh the same way, the same ctest entry passes ("Test #37: process_cmdline ... Passed 1.67 sec") and the direct run exits 0. The two new probes exist only in this PR's test, so the main pass shows the rest of the test passes there, not that the probes pass. I did not look into the cause. An RTX 4080 run of the same head fails the same two probes.

AI-assisted.

@Kam471 Kam471 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.

Root cause confirmed on Windows 11 (MSVC 19.44, RelWithDebInfo): the production flush works; the test cannot read its own file.

  • dumpbin /disasm shows call [__imp_fflush] in game_exit, game_cexit and game_thread, and the EXE imports fflush from the host ucrtbase.
  • With a temporary probe reading the writer's own handle (_get_osfhandle + GetFileSizeEx) immediately after run_entry: 19 bytes with the flush, 0 with std::fflush(nullptr) removed (while ftell still showed 19 buffered). So the data is written and the flush is what writes it.
  • The failure is a Windows sharing violation: _wfopen_s opens with _SH_SECURE (UCRT fopen.cpp:80), whose share mode is FILE_SHARE_READ for a reader; the writer still holds GENERIC_WRITE, so the read returns 13/EACCES and contents stays empty. Even a CreateFileW with READ|WRITE|DELETE sharing fails against the writer's share mode.
  • Opening both sides with _wfsopen(..., _SH_DENYNO) and asserting the read open succeeded makes the test pass (contents="buffered C stream\n", exit 0) with this PR's production code, while the same adjusted fixture fails on 3faac557. That is the differential the test wants.

So no production change is needed for this failure; the fixture needs the shared-open fix (and should fail loudly if the read open fails, so a sharing problem cannot look like a flush problem again). The PR still overlaps #5194's RT-368 change; either can land once this test is fixed.

@thehollowedone

Copy link
Copy Markdown

Rechecked f71b71dfc4792dca3cdf9ed02b7abc4d10512864 on 3faac557. The published process_cmdline test now passes as written (1/1, zero skips). Windows 11 x64 build 26300, MSVC 19.44.35230, Windows SDK 10.0.26100.0, RelWithDebInfo.

The updated fixture checks the still-open writer handle with GetFileSizeEx before closing and reopening for the content check. With only process.cpp restored to base, both probes fail: entry return and exit() still return 17 and 23, but the live file size is 0 instead of 18 bytes. Both files contain the expected text after fclose. That confirms the published fixture distinguishes the flush from final stream cleanup on this host.

CPU only, synthetic files. AI-assisted.

@Koro4e

Koro4e commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested f71b71d on RTX 3060, driver 617.14, Windows 11, MSVC 14.44 RelWithDebInfo: pass

  • Built process_cmdline_test, gta6rt and the shim/fixture targets; process.cpp recompiles clean at /W4 (0 warnings).
  • ctest: process_cmdline (with the new exit-flush cases), run_tiny_atexit, run_tiny_game, run_tiny_game_fixed, both _exit_code, _console_paths, _dir, _tls, _eh, _async, _gdk_load, _bundled_load, run_tiny_frame — 14/14 passed; neighbour shim area xmem, file_system, winhttp_offline, xgameruntime_* — 12/12 passed, 0 failed.
  • Both paths (exit(23) and return 17) flush the buffered fputs before exit; the test checks the file size before fclose, so cleanup can't fake it.

AI-assisted.

@Kam471 Kam471 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.

Retested at head f71b71d (was 87dc24b), base main 3faac55, Windows 11 / PowerShell, worktree under %TEMP%\opencode.

Fixture sharing fix: present, but not as _wfsopen(_SH_DENYNO). The writer is still _wfopen_s(..., L"wb"), which is non-sharable; I confirmed a concurrent read open returns errno 13 (EACCES). The fixture now closes the writer before the reader opens, and preserves the anti-cleanup property by checking GetFileSizeEx(_get_osfhandle(_fileno(stream))) on the still-open stream before fclose. The read open itself is not separately asserted, but a failed open leaves contents empty and fails contents_match, so it cannot false-pass. Equivalent fix.

Head results (vcvars64 + Ninja):

  • ninja process_cmdline_test
  • LEONIDA_VK_DEVICE='RTX 5070 Ti' process_cmdline_test.exe — exit 0, 0 FAIL lines (the binary prints one summary line and no per-check PASS lines, so pass = exit 0). Both new probes (entry-return 17, exit() 23) ran and passed.
  • ctest -R '^run_tiny_atexit$' --output-on-failure — 1/1 Passed (0.85 s).
  • Configure used: -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_TESTING=ON -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON -DVulkan_INCLUDE_DIR=C:/VulkanSDK/1.4.363.0/Include -DVulkan_LIBRARY=C:/VulkanSDK/1.4.363.0/Lib/vulkan-1.lib

Negative control (main 3faac55, only this test file copied in): exit 1, both probes fail:

FAIL entry return: exit code 17 (want 17), stream size 0 (want 18), contents match
FAIL exit(): exit code 23 (want 23), stream size 0 (want 18), contents match

(contents match only because fclose in test cleanup flushed afterwards — the pre-close size check is what catches it.)

git diff --check: clean, working tree and 3faac557b..HEAD.

Verdict: PASS — differential confirmed (head passes both probes, main fails both), RT-368 ctest passes, no whitespace issues. Minor non-blocking nit: the reader-open failure is only reported as "contents differ".

@miniongk

Copy link
Copy Markdown
Author

Verification update at f71b71:

  • PR-branch Runtime CI: Windows build succeeded; process_cmdline and both new normal-exit flush probes passed.
  • Baseline main Runtime CI: the same Linux vk_harness.cpp pipeline-binary build errors and Windows d3d12_sparse_queue_family / vkCreateInstance failure reproduce without this PR. The full workflow remains red for those pre-existing issues, not for the RT-368 regression.
  • git diff --check passes; the local branch is synchronized with f71b71 and clean.

Overlap with #5194 is now explicit in Depends on. Its broader production change includes msvcrt.dll; this PR adds the independently reviewed pre-cleanup regression. If #5194 lands first, the duplicate production lines can be dropped on rebase.

@milas6669

Copy link
Copy Markdown

Tested f71b71df on Windows 11 with MSVC 14.44 — CPU only, no GPU, no game data.

cmake --build runtime/build --target process_cmdline_test
ctest --test-dir runtime/build -R process --output-on-failure
  Test #37: process_cmdline ... Passed  0.03 sec
  100% tests passed out of 1

Negative control. On main 3faac557, with this branch's runtime/test/process_cmdline_test.cpp but main's runtime/shims/process.cpp:

FAIL entry return: exit code 17 (want 17), stream size 0 (want 18), contents match
FAIL exit():      exit code 23 (want 23), stream size 0 (want 18), contents match
exit 1

So both halves of the check — the buffered stream reaching disk, and the exit code surviving — fail before the change and pass after it, on this machine. The test writes only to a temp file it creates and deletes.

I did not test the stated dependency (#5194); this is only the pre-cleanup regression on its own base.

AI-assisted. No game data.

@gertify

gertify commented Nov 23, 2026

Copy link
Copy Markdown

process_cmdline_test is flaky at f71b71d on Intel UHD 770, driver 32.0.101.7088, Windows 11. Running the test binary from a clean tree: of 200 runs, 196 exited 0 with the test's result line, and 4 ended before the test finished with no output at all, 3 with exit code 23 and 1 with exit code 17. A further 100 runs exited 0 every time, so it is intermittent, but ctest is affected too: a loop of ctest over this test reported ***Failed for test 37 process_cmdline on iteration 3, with no output from the test. With the main test file and this head's production code, 100 runs exited 0 every time, and on main 3faac55 100 runs also exited 0 every time. Expected: every run reaches the test's result line and exits 0. AI-assisted.

@itsonlysimbo

Copy link
Copy Markdown
Contributor

Tested f71b71df merged onto main 561b65a8 (merges cleanly) on RTX 4070, NVIDIA 621.14, Windows 11 (10.0.26300), MSVC 19.44, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363: pass.

AI-assisted (Claude Code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants