From acd67eaa75ac68d46a4c41ebbc7676572c0353a7 Mon Sep 17 00:00:00 2001 From: Merith Date: Wed, 4 Mar 2026 04:37:32 -0800 Subject: [PATCH] adress copilot reviews --- CMakeLists.txt | 6 +++-- .../Windows64/Windows64_Minecraft.cpp | 26 ++++++++++++++++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index feaf1d5c1..4b6b43b13 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,8 +62,10 @@ if(MSVC) # Docker and piped output in server mode). WinMainCRTStartup keeps the # WinMain entry point. Client mode calls FreeConsole() to detach. target_link_options(MinecraftClient PRIVATE - /SUBSYSTEM:CONSOLE /ENTRY:WinMainCRTStartup - $<$:/LTCG /INCREMENTAL:NO> + /SUBSYSTEM:CONSOLE + /ENTRY:WinMainCRTStartup + $<$:/LTCG> + $<$:/INCREMENTAL:NO> ) endif() diff --git a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp index 91a1366ca..a95fd56fc 100644 --- a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp +++ b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp @@ -228,9 +228,29 @@ static BOOL WINAPI HeadlessServerCtrlHandler(DWORD ctrlType) static void SetupHeadlessServerConsole() { - // The exe is now linked as /SUBSYSTEM:CONSOLE, so it inherits the parent's - // console automatically. We just need to re-open the CRT streams so that - // printf/scanf go through the console and set up our Ctrl handler. + // The exe is linked as /SUBSYSTEM:CONSOLE, so it normally inherits the + // parent's console. However, if launched with DETACHED_PROCESS or + // CREATE_NO_WINDOW the handles may be invalid. Verify before redirecting + // the CRT streams to avoid leaving them in a broken state. + HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); + HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); + bool hasConsole = + hStdOut != NULL && hStdOut != INVALID_HANDLE_VALUE && + hStdIn != NULL && hStdIn != INVALID_HANDLE_VALUE; + + if (!hasConsole) + { + if (!AttachConsole(ATTACH_PARENT_PROCESS)) + { + if (!AllocConsole()) + { + // No console available at all; skip stream redirection. + SetConsoleCtrlHandler(HeadlessServerCtrlHandler, TRUE); + return; + } + } + } + FILE* stream = NULL; freopen_s(&stream, "CONIN$", "r", stdin); freopen_s(&stream, "CONOUT$", "w", stdout);