Write the log file before stderr, and keep a blocked console from stopping the log and the exit.

A selection in the console window of a game started directly held back the write to stderr, and with it the log
file, the exit hook and the crash report. The log file now comes first, stderr goes past the C runtime's stream lock,
and the lines of an exit, a fatal error or a crash skip stderr while another thread is stuck in it. A game run turns
the console's QuickEdit mode off, and a closed console, Ctrl+C or Ctrl+Break ends the game the way a closed window
does, with the settings and saves written and the exit logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
chrg6
2026-11-13 05:53:29 -05:00
parent 175033d49a
commit e682934bd0
7 changed files with 124 additions and 11 deletions

View File

@@ -83,6 +83,10 @@ void gfx_window_focus_changed(int in) {
// (plat_restart), and the new process waits until this one is gone (main.c) before it moves the log and opens the
// RomFS and the saves.
void gfx_window_closed(void) {
// Once. The console's close (main.c console_closed) can come beside the window's: the later caller waits here
// while the first one saves and ends the process.
static volatile int32_t closing;
if (plat_xchg32(&closing, 1)) for (;;) plat_sleep_ms(1000);
int restart = plat_cas32(&g_restart, 0, 0) != 0;
rt_log("gfx: window closed; %s", restart ? "restarting" : "exiting");
cfg_save(); // a menu change saves 400 ms later on the render thread (option_rows.cpp); closing sooner kept the old file

View File

@@ -102,6 +102,7 @@ void perf_cpu_start(void); // the process's logical processors (NX2NAVI_CACHE_
int perf_cpu_on_cache_die(void); // 1 while the process runs on the die with the largest L3 cache alone (perf.c cpu_placement)
void perf_summary_flush(void); // prints the frame-time summary of the running period (exit); the 60 s lines come from perf_present
void gfx_exit_log(void); // back end's lines for the exit summary (weak no-op in prof_win.c)
void gfx_window_closed(void); // gfx_present.c (gfx_wsys.h): the end of a closed window; does not return
void perf_gpu_wait(uint64_t t0); // a wait for a GPU fence ended (any thread; the render thread's also counts as PERF_FENCE)
// GPU side of the 60-frame perf line, filled by the graphics back end when it set perf_gpu_stats. gpu_ns: GPU busy time
// since the previous call (timestamp queries, overlaps counted once), have_gpu 0 when the device has no timestamps.

View File

@@ -1,6 +1,6 @@
// Log writes on a thread of their own.
//
// A log line was written by the thread that logged it: to stderr and to the log file (main.c log_sink). A write can
// A log line was written by the thread that logged it: to the log file and to stderr (main.c log_sink). A write can
// stall: a console that scrolls, a pipe whose reader is busy, a virus scanner, a disk that flushes; hundreds of
// milliseconds at worst. The render thread logs too, and a frame it spends in such a write is a hitch with nothing
// else to show for it.

View File

@@ -74,20 +74,50 @@ static char g_log_early[32768];
static size_t g_log_early_n;
static uint64_t g_log_bytes;
// The log's destinations. logq.c calls it: from the log thread in a game run, else from the thread that logs.
// stderr's writes (log_sink). g_log_final: rt_log_sync has run, so the process is ending: an exit, a fatal error or a
// crash report.
static PlatMutex g_err_lock = PLAT_MUTEX_INIT;
static volatile int32_t g_log_final;
// The log's destinations: the file first, then stderr. logq.c calls it: from the log thread in a game run, else from
// the thread that logs. A write to stderr can block for as long as its reader likes: a console window holds every write
// back while a selection is made in it, and the log thread then stays in that write. The file has the lines by then, and
// the lines of the process's end (rt_log_sync) skip stderr while another thread is stuck in a write to it, so the exit
// and FATAL lines still reach the file. stderr goes through plat_stderr_write, which holds no lock of the C runtime's
// stderr stream, so fflush(stderr) and plat_exit's fflush(NULL) do not wait for a stuck write either.
static void log_sink(const char *p, size_t n) {
fwrite(p, 1, n, stderr);
if (__atomic_load_n(&g_log_state, __ATOMIC_ACQUIRE) != LOG_FILE) return;
uint64_t at = __atomic_fetch_add(&g_log_bytes, n, __ATOMIC_RELAXED);
if (at + n <= LOG_CAP) {
plat_append_write(g_log_file, p, n);
} else if (at <= LOG_CAP) { // the first write past the cap says so, once
static const char cut[] = "[host] log: the file reached 64 MiB, the rest of this run goes to stderr only\n";
plat_append_write(g_log_file, cut, sizeof cut - 1);
int file = __atomic_load_n(&g_log_state, __ATOMIC_ACQUIRE) == LOG_FILE;
if (file) {
uint64_t at = __atomic_fetch_add(&g_log_bytes, n, __ATOMIC_RELAXED);
if (at + n <= LOG_CAP) {
plat_append_write(g_log_file, p, n);
} else if (at <= LOG_CAP) { // the first write past the cap says so, once
static const char cut[] = "[host] log: the file reached 64 MiB, the rest of this run goes to stderr only\n";
plat_append_write(g_log_file, cut, sizeof cut - 1);
}
}
// without the file stderr is the log (run_game.py, `2> file`), and it is waited for
if (file && __atomic_load_n(&g_log_final, __ATOMIC_ACQUIRE)) {
if (!plat_mutex_trylock(&g_err_lock)) return;
} else {
plat_mutex_lock(&g_err_lock);
}
plat_stderr_write(p, n);
plat_mutex_unlock(&g_err_lock);
}
void rt_log_sync(void) { logq_sync(); }
void rt_log_sync(void) {
__atomic_store_n(&g_log_final, 1, __ATOMIC_RELEASE);
logq_sync();
}
// The console window was closed, or Ctrl+C or Ctrl+Break pressed in it (platform.h plat_console_setup): the end of a
// closed game window, which writes the settings, the caches and the saves and logs the exit (gfx_present.c
// gfx_window_closed). Left to Windows, a closed console ended the process with nothing saved.
static void console_closed(const char *what) {
rt_log("console: %s; the game ends as when its window is closed", what);
gfx_window_closed();
}
void rt_log_raw(const char *p, size_t n) {
if (__atomic_load_n(&g_log_state, __ATOMIC_ACQUIRE) == LOG_EARLY) {
@@ -696,6 +726,9 @@ static int main_run(int argc, char **argv) {
if (cfg.seconds && mode) return usage(argv[0]);
log_open(!mode);
if (!mode) {
// the console of a game started directly: no QuickEdit to stop the log, and its close saves (console_closed)
if (plat_console_setup(console_closed))
rt_log("console: QuickEdit off; closing the console ends the game as its window does");
mem_start_note(0); // memory.c: a warning when the machine has less memory free than the game takes
cfg.boot = cfg.seconds > 0; // --seconds starts the game like --boot, with its checkpoints
vk_driver_cache_env(); // before the threads below and rt_boot's, any of which may load the Vulkan driver

View File

@@ -1884,6 +1884,21 @@ int plat_stderr_path(char *out, size_t cap) {
return 1;
}
int plat_stderr_write(const void *p, size_t n) {
for (const char *c = p; n;) {
ssize_t k = write(2, c, n);
if (k < 0 && errno == EINTR) continue;
if (k <= 0) return 0;
c += k, n -= (size_t)k;
}
return 1;
}
int plat_console_setup(void (*on_close)(const char *what)) { // a Windows console's settings only
(void)on_close;
return 0;
}
// ---- process
#ifdef NX2NAVI_PGO_GEN

View File

@@ -462,6 +462,18 @@ int plat_os_version(char *out, size_t cap);
int plat_is_wine(void); // 1 when the Windows build runs under Wine; 0 elsewhere
// The file the process's stderr (the log) goes to, as a UTF-8 path; 0 when stderr is not a file (a console, a pipe).
int plat_stderr_path(char *out, size_t cap);
// Writes the bytes to stderr's file descriptor, past the C runtime's FILE stream (on Windows with its low-level _write,
// which keeps the text mode's line ends): a write that blocks, on a console that holds its output back, then holds no
// lock of the stderr stream, and fflush(stderr) or fflush(NULL) on another thread does not wait for it. 1 when all of
// them were written.
int plat_stderr_write(const void *p, size_t n);
// When stderr is a console window (Windows): turns its QuickEdit mode off, since a selection made in the window with
// the mouse holds back every write to it until the selection ends, and passes a close of the console, Ctrl+C and
// Ctrl+Break to on_close, on a thread of the system's, with the event's name. on_close must end the process: Windows
// ends it about 5 s after a close in any case. A second Ctrl+C or Ctrl+Break while on_close runs ends the process at
// once, as without the handler. plat_exit puts QuickEdit back as it was. 1 when stderr is a console; elsewhere 0, and
// nothing is changed.
int plat_console_setup(void (*on_close)(const char *what));
// ---- desktop: the in-game menu's "Copy system info" and "Open log folder"
int plat_clipboard_set(const char *utf8); // replaces the clipboard's text; 1 on success

View File

@@ -1197,6 +1197,52 @@ __attribute__((constructor)) static void pgo_flush_start(void) {
}
#endif
// ---- the console window (plat_console_setup)
static HANDLE con_in = INVALID_HANDLE_VALUE; // the console's input, while its QuickEdit mode is off; con_mode as it was
static DWORD con_mode;
static void (*con_close)(const char *what);
static volatile LONG con_closing;
// Runs on a thread the system starts for the event. A close returns only when on_close does, which it must not.
static BOOL WINAPI con_ctrl(DWORD ev) {
const char *what = ev == CTRL_CLOSE_EVENT ? "closed" : ev == CTRL_C_EVENT ? "Ctrl+C"
: ev == CTRL_BREAK_EVENT ? "Ctrl+Break" : NULL;
// log-off and shutdown reach a process with a window as WM_ENDSESSION (gfx_window_win.c), not here; a second event
// while on_close runs takes the default path, which ends the process at once
if (!what || !con_close || InterlockedExchange(&con_closing, 1)) return FALSE;
con_close(what);
return TRUE;
}
int plat_console_setup(void (*on_close)(const char *what)) {
HANDLE err = GetStdHandle(STD_ERROR_HANDLE);
DWORD m;
if (!err || err == INVALID_HANDLE_VALUE || !GetConsoleMode(err, &m)) return 0;
// CONIN$: the console's input even when stdin was redirected. ENABLE_EXTENDED_FLAGS makes the call change the
// QuickEdit bit at all.
HANDLE in = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, 0, NULL);
if (in != INVALID_HANDLE_VALUE && GetConsoleMode(in, &con_mode) && (con_mode & ENABLE_QUICK_EDIT_MODE) &&
SetConsoleMode(in, (con_mode & ~(DWORD)ENABLE_QUICK_EDIT_MODE) | ENABLE_EXTENDED_FLAGS))
con_in = in;
else if (in != INVALID_HANDLE_VALUE)
CloseHandle(in);
con_close = on_close;
if (on_close) SetConsoleCtrlHandler(con_ctrl, TRUE);
return 1;
}
int plat_stderr_write(const void *p, size_t n) {
int fd = _fileno(stderr); // the descriptor fwrite(stderr) writes to; negative when the process has no stderr
if (fd < 0) return 0;
for (const char *c = p; n;) {
int k = _write(fd, c, n > (1u << 30) ? 1u << 30 : (unsigned)n);
if (k <= 0) return 0;
c += k, n -= (size_t)k;
}
return 1;
}
void (*plat_exit_hook)(void);
void plat_exit(int code) {
@@ -1204,6 +1250,8 @@ void plat_exit(int code) {
#ifdef NX2NAVI_PGO_GEN
__llvm_profile_dump();
#endif
// QuickEdit back on in a console that outlives the process (the one of the shell that started it)
if (con_in != INVALID_HANDLE_VALUE) SetConsoleMode(con_in, con_mode | ENABLE_EXTENDED_FLAGS);
fflush(NULL); // every open stream: nothing below runs the C runtime's own exit
// The process ends here, without the libraries' detach calls that ExitProcess makes. The callers have saved what
// is to be kept (gfx_present.c gfx_window_closed: settings, pipeline cache, profile, saves), and the game's other