Skip to content

Restore the console output code page on exit#77

Closed
enesilhaydin wants to merge 1 commit into
microsoft:mainfrom
enesilhaydin:fix/restore-console-output-cp
Closed

Restore the console output code page on exit#77
enesilhaydin wants to merge 1 commit into
microsoft:mainfrom
enesilhaydin:fix/restore-console-output-cp

Conversation

@enesilhaydin

Copy link
Copy Markdown
Contributor

The console output code page is switched to UTF-8 at startup but never restored.

set_console_cp_utf8() returns a RestoreConsoleCp whose Drop impl is supposed to put the original code page back. That destructor never runs: main ends every path with process::exit(...), and std::process::exit terminates the process without unwinding the stack, so the guard is never dropped.

The practical effect is that running any util once leaves the console on code page 65001 for the rest of the session. Programs run afterwards that emit OEM/ANSI-encoded output then render as mojibake until the user runs chcp manually.

This swaps the Drop guard for an atexit handler. std::process::exit calls the CRT exit(), which does run atexit handlers, so the original code page is restored on every exit path. The handler uses an atomic swap so it only restores once, and set_console_cp_utf8() is a no-op when the page is already UTF-8 or can't be queried.

set_console_cp_utf8() relied on a Drop guard to restore the original
code page, but main always terminates via process::exit, which skips
destructors. Register the restore as an atexit handler instead, since
the CRT runs those during exit().
@enesilhaydin

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

@lhecker

lhecker commented Jun 8, 2026

Copy link
Copy Markdown
Member

std::process::exit calls the CRT exit()

That's only true on Linux and macOS and some other *nix. On Windows the stdlib calls ExitProcess. 😔

@lhecker lhecker closed this Jun 8, 2026
@enesilhaydin enesilhaydin deleted the fix/restore-console-output-cp branch June 8, 2026 18:34
@lhecker

lhecker commented Jun 8, 2026

Copy link
Copy Markdown
Member

I have given you credit in #65, because it adopts the atexit() approach for ntsort.

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.

2 participants