{"thread":{"id":"65754","subject":"[PATCH 0/2] mingw: terminate child processes in a gentler way","startedAt":"2026-06-04T16:24:23Z","lastAt":"2026-06-04T16:24:26Z","messageCount":3,"participants":["Johannes Schindelin via GitGitGadget"],"isPatch":true,"patchVersion":1,"patchTotal":2},"messages":[{"id":"544749","messageId":"pull.2130.git.1780590261.gitgitgadget@gmail.com","threadId":"65754","inReplyTo":null,"subject":"[PATCH 0/2] mingw: terminate child processes in a gentler way","fromName":"Johannes Schindelin via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-06-04T16:24:18Z","receivedAt":"2026-06-04T16:24:23Z","isPatch":true,"body":"This patch series consists of two patches that have been carried in Git for\nWindows since 2017 an 2018, respectively.\n\nThe problem they work around is a fundamental mismatch between Git's\nunderstanding how processes can be terminated and Windows' multi-threading\ncentric world view (where multi-process architectures are quite, quite\nrare), where processes do not tell other processes to terminate gently\n(meaning: giving them a chance to run their atexit() handlers).\n\nAs such, Git thinks that it can send processes signals to terminate or\nforce-stop (\"kill\") them. There are no signals in the Unix sense on Windows,\nthough. So we try to emulate them. At present, in vanilla Git that means\nthat we use the TerminateProcess() Win32 API functions, which is most\nsimilar to Unix' SIGKILL and is typically frowned upon because it does not\nallow an orderly shutdown of multi-threaded applications. That's definitely\nnot what Git wants to do: If it wants to terminate a child process, it wants\nthat child process to clean up any .lock files, for example. And therefore\nit wants to send a SIGTERM.\n\nBut the SIGTERM signal does not really have any equivalent on Windows. The\nclosest is to somehow get the target process to call the ExitProcess() Win32\nAPI function. There is a trick that we employ here to do precisely that: we\ncreate a remote thread in the target process, and specify the ExitProcess()\nfunction as the callee. This works because that function matches the\nfunction signature of thread functions enough that we can get away with it,\nand because the address of that function is identical between processes\nmatching the same CPU architecture. Read: This approach does not work when\ntrying to terminate i686 processes from an x86_64 git.exe. But since it is\nrare to mix and match processes of different CPU architectures on Windows\n(certainly in Git scenarios), we kind of resort to this best effort that\nworks often enough to make it worthwhile.\n\nIt's a different story for SIGINT: That signal matches most closely what\nWindows calls a ConsoleCtrlEvent. It is different, though, in that a\nConsoleCtrlEvent is not sent to a process, but to a Console, and is handled\nby all processes that are attached to said Console. In the MSYS2 runtime\nthat provides the POSIX emulation layer required by the Bash distributed\nwith Git for Windows, we work around that by using a similar trick as the\nSIGTERM/ExitProcess() injection: a thread is injected into the remote\nprocess, passing the address of the (undocumented) kernel32!CtrlRoutine.\nThis is quite hacky and requires spawning a separate process to just to\nfigure out the address of said function, which only works in the MSYS2\nruntime because it acquires that address once, and then remembers it for the\nrest of its lifetime. Git also simply has no business emulating a Ctrl+C and\ninstead sends child processes SIGTERM. Therefore, there is no support for\nsending SIGINT in this patch series. But patch number 2 implements reacting\nto the emulated SIGINT \"sent\" by the MSYS2 runtime.\n\nJohannes Schindelin (2):\n  mingw: kill child processes in a gentler way\n  mingw: really handle SIGINT\n\n compat/mingw.c              |  38 +++++++--\n compat/win32/exit-process.h | 165 ++++++++++++++++++++++++++++++++++++\n 2 files changed, 195 insertions(+), 8 deletions(-)\n create mode 100644 compat/win32/exit-process.h\n\n\nbase-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0\nPublished-As: https://github.com/gitgitgadget/git/releases/tag/pr-2130%2Fdscho%2Fmingw-kill-gentle-v1\nFetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2130/dscho/mingw-kill-gentle-v1\nPull-Request: https://github.com/gitgitgadget/git/pull/2130\n-- \ngitgitgadget\n"},{"id":"544750","messageId":"8d6f16406415ab08aa3b188ae67ec03159928bfa.1780590261.git.gitgitgadget@gmail.com","threadId":"65754","inReplyTo":"pull.2130.git.1780590261.gitgitgadget@gmail.com","subject":"[PATCH 1/2] mingw: kill child processes in a gentler way","fromName":"Johannes Schindelin via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-06-04T16:24:19Z","receivedAt":"2026-06-04T16:24:25Z","isPatch":true,"body":"From: Johannes Schindelin <johannes.schindelin@gmx.de>\n\nThe TerminateProcess() function does not actually leave the child\nprocesses any chance to perform any cleanup operations. This is bad\ninsofar as Git itself expects its signal handlers to run.\n\nA symptom is e.g. a left-behind .lock file that would not be left behind\nif the same operation was run, say, on Linux.\n\nTo remedy this situation, we use an obscure trick: we inject a thread\ninto the process that needs to be killed and to let that thread run the\nExitProcess() function with the desired exit status. Thanks J Wyman for\ndescribing this trick.\n\nThe advantage is that the ExitProcess() function lets the atexit\nhandlers run. While this is still different from what Git expects (i.e.\nrunning a signal handler), in practice Git sets up signal handlers and\natexit handlers that call the same code to clean up after itself.\n\nIn case that the gentle method to terminate the process failed, we still\nfall back to calling TerminateProcess(), but in that case we now also\nmake sure that processes spawned by the spawned process are terminated;\nTerminateProcess() does not give the spawned process a chance to do so\nitself.\n\nPlease note that this change only affects how Git for Windows tries to\nterminate processes spawned by Git's own executables. Third-party\nsoftware that *calls* Git and wants to terminate it *still* need to make\nsure to imitate this gentle method, otherwise this patch will not have\nany effect.\n\nSigned-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>\n---\n compat/mingw.c              |  29 +++++--\n compat/win32/exit-process.h | 165 ++++++++++++++++++++++++++++++++++++\n 2 files changed, 186 insertions(+), 8 deletions(-)\n create mode 100644 compat/win32/exit-process.h\n\ndiff --git a/compat/mingw.c b/compat/mingw.c\nindex 2023c16db6..973049ffe3 100644\n--- a/compat/mingw.c\n+++ b/compat/mingw.c\n@@ -13,6 +13,7 @@\n #include \"symlinks.h\"\n #include \"trace2.h\"\n #include \"win32.h\"\n+#include \"win32/exit-process.h\"\n #include \"win32/lazyload.h\"\n #include \"wrapper.h\"\n #include <aclapi.h>\n@@ -2208,16 +2209,28 @@ int mingw_execvp(const char *cmd, char *const *argv)\n int mingw_kill(pid_t pid, int sig)\n {\n \tif (pid > 0 && sig == SIGTERM) {\n-\t\tHANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);\n-\n-\t\tif (TerminateProcess(h, -1)) {\n+\t\tHANDLE h = OpenProcess(PROCESS_CREATE_THREAD |\n+\t\t\t\t       PROCESS_QUERY_INFORMATION |\n+\t\t\t\t       PROCESS_VM_OPERATION | PROCESS_VM_WRITE |\n+\t\t\t\t       PROCESS_VM_READ | PROCESS_TERMINATE,\n+\t\t\t\t       FALSE, pid);\n+\t\tint ret;\n+\n+\t\tif (h)\n+\t\t\tret = exit_process(h, 128 + sig);\n+\t\telse {\n+\t\t\th = OpenProcess(PROCESS_TERMINATE, FALSE, pid);\n+\t\t\tif (!h) {\n+\t\t\t\terrno = err_win_to_posix(GetLastError());\n+\t\t\t\treturn -1;\n+\t\t\t}\n+\t\t\tret = terminate_process_tree(h, 128 + sig);\n+\t\t}\n+\t\tif (ret) {\n+\t\t\terrno = err_win_to_posix(GetLastError());\n \t\t\tCloseHandle(h);\n-\t\t\treturn 0;\n \t\t}\n-\n-\t\terrno = err_win_to_posix(GetLastError());\n-\t\tCloseHandle(h);\n-\t\treturn -1;\n+\t\treturn ret;\n \t} else if (pid > 0 && sig == 0) {\n \t\tHANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);\n \t\tif (h) {\ndiff --git a/compat/win32/exit-process.h b/compat/win32/exit-process.h\nnew file mode 100644\nindex 0000000000..d53989884c\n--- /dev/null\n+++ b/compat/win32/exit-process.h\n@@ -0,0 +1,165 @@\n+#ifndef EXIT_PROCESS_H\n+#define EXIT_PROCESS_H\n+\n+/*\n+ * This file contains functions to terminate a Win32 process, as gently as\n+ * possible.\n+ *\n+ * At first, we will attempt to inject a thread that calls ExitProcess(). If\n+ * that fails, we will fall back to terminating the entire process tree.\n+ *\n+ * For simplicity, these functions are marked as file-local.\n+ */\n+\n+#include <tlhelp32.h>\n+\n+/*\n+ * Terminates the process corresponding to the process ID and all of its\n+ * directly and indirectly spawned subprocesses.\n+ *\n+ * This way of terminating the processes is not gentle: the processes get\n+ * no chance of cleaning up after themselves (closing file handles, removing\n+ * .lock files, terminating spawned processes (if any), etc).\n+ */\n+static int terminate_process_tree(HANDLE main_process, int exit_status)\n+{\n+\tHANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n+\tPROCESSENTRY32 entry;\n+\tDWORD pids[16384];\n+\tint max_len = sizeof(pids) / sizeof(*pids), i, len, ret = 0;\n+\tpid_t pid = GetProcessId(main_process);\n+\n+\tpids[0] = (DWORD)pid;\n+\tlen = 1;\n+\n+\t/*\n+\t * Even if Process32First()/Process32Next() seem to traverse the\n+\t * processes in topological order (i.e. parent processes before\n+\t * child processes), there is nothing in the Win32 API documentation\n+\t * suggesting that this is guaranteed.\n+\t *\n+\t * Therefore, run through them at least twice and stop when no more\n+\t * process IDs were added to the list.\n+\t */\n+\tfor (;;) {\n+\t\tint orig_len = len;\n+\n+\t\tmemset(&entry, 0, sizeof(entry));\n+\t\tentry.dwSize = sizeof(entry);\n+\n+\t\tif (!Process32First(snapshot, &entry))\n+\t\t\tbreak;\n+\n+\t\tdo {\n+\t\t\tfor (i = len - 1; i >= 0; i--) {\n+\t\t\t\tif (pids[i] == entry.th32ProcessID)\n+\t\t\t\t\tbreak;\n+\t\t\t\tif (pids[i] == entry.th32ParentProcessID)\n+\t\t\t\t\tpids[len++] = entry.th32ProcessID;\n+\t\t\t}\n+\t\t} while (len < max_len && Process32Next(snapshot, &entry));\n+\n+\t\tif (orig_len == len || len >= max_len)\n+\t\t\tbreak;\n+\t}\n+\n+\tfor (i = len - 1; i > 0; i--) {\n+\t\tHANDLE process = OpenProcess(PROCESS_TERMINATE, FALSE, pids[i]);\n+\n+\t\tif (process) {\n+\t\t\tif (!TerminateProcess(process, exit_status))\n+\t\t\t\tret = -1;\n+\t\t\tCloseHandle(process);\n+\t\t}\n+\t}\n+\tif (!TerminateProcess(main_process, exit_status))\n+\t\tret = -1;\n+\tCloseHandle(main_process);\n+\n+\treturn ret;\n+}\n+\n+/**\n+ * Determine whether a process runs in the same architecture as the current\n+ * one. That test is required before we assume that GetProcAddress() returns\n+ * a valid address *for the target process*.\n+ */\n+static inline int process_architecture_matches_current(HANDLE process)\n+{\n+\tstatic BOOL current_is_wow = -1;\n+\tBOOL is_wow;\n+\n+\tif (current_is_wow == -1 &&\n+\t    !IsWow64Process (GetCurrentProcess(), &current_is_wow))\n+\t\tcurrent_is_wow = -2;\n+\tif (current_is_wow == -2)\n+\t\treturn 0; /* could not determine current process' WoW-ness */\n+\tif (!IsWow64Process (process, &is_wow))\n+\t\treturn 0; /* cannot determine */\n+\treturn is_wow == current_is_wow;\n+}\n+\n+/**\n+ * Inject a thread into the given process that runs ExitProcess().\n+ *\n+ * Note: as kernel32.dll is loaded before any process, the other process and\n+ * this process will have ExitProcess() at the same address.\n+ *\n+ * This function expects the process handle to have the access rights for\n+ * CreateRemoteThread(): PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION,\n+ * PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ.\n+ *\n+ * The idea comes from the Dr Dobb's article \"A Safer Alternative to\n+ * TerminateProcess()\" by Andrew Tucker (July 1, 1999),\n+ * http://www.drdobbs.com/a-safer-alternative-to-terminateprocess/184416547\n+ *\n+ * If this method fails, we fall back to running terminate_process_tree().\n+ */\n+static int exit_process(HANDLE process, int exit_code)\n+{\n+\tDWORD code;\n+\n+\tif (GetExitCodeProcess(process, &code) && code == STILL_ACTIVE) {\n+\t\tstatic int initialized;\n+\t\tstatic LPTHREAD_START_ROUTINE exit_process_address;\n+\t\tPVOID arg = (PVOID)(intptr_t)exit_code;\n+\t\tDWORD thread_id;\n+\t\tHANDLE thread = NULL;\n+\n+\t\tif (!initialized) {\n+\t\t\tHINSTANCE kernel32 = GetModuleHandleA(\"kernel32\");\n+\t\t\tif (!kernel32)\n+\t\t\t\tdie(\"BUG: cannot find kernel32\");\n+\t\t\texit_process_address =\n+\t\t\t\t(LPTHREAD_START_ROUTINE)(void (*)(void))\n+\t\t\t\tGetProcAddress(kernel32, \"ExitProcess\");\n+\t\t\tinitialized = 1;\n+\t\t}\n+\t\tif (!exit_process_address ||\n+\t\t    !process_architecture_matches_current(process))\n+\t\t\treturn terminate_process_tree(process, exit_code);\n+\n+\t\tthread = CreateRemoteThread(process, NULL, 0,\n+\t\t\t\t\t    exit_process_address,\n+\t\t\t\t\t    arg, 0, &thread_id);\n+\t\tif (thread) {\n+\t\t\tCloseHandle(thread);\n+\t\t\t/*\n+\t\t\t * If the process survives for 10 seconds (a completely\n+\t\t\t * arbitrary value picked from thin air), fall back to\n+\t\t\t * killing the process tree via TerminateProcess().\n+\t\t\t */\n+\t\t\tif (WaitForSingleObject(process, 10000) ==\n+\t\t\t    WAIT_OBJECT_0) {\n+\t\t\t\tCloseHandle(process);\n+\t\t\t\treturn 0;\n+\t\t\t}\n+\t\t}\n+\n+\t\treturn terminate_process_tree(process, exit_code);\n+\t}\n+\n+\treturn 0;\n+}\n+\n+#endif\n-- \ngitgitgadget\n\n"},{"id":"544751","messageId":"297cc921fb8c12d85f8bf4c1e05edfbab9609191.1780590261.git.gitgitgadget@gmail.com","threadId":"65754","inReplyTo":"pull.2130.git.1780590261.gitgitgadget@gmail.com","subject":"[PATCH 2/2] mingw: really handle SIGINT","fromName":"Johannes Schindelin via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-06-04T16:24:20Z","receivedAt":"2026-06-04T16:24:26Z","isPatch":true,"body":"From: Johannes Schindelin <johannes.schindelin@gmx.de>\n\nPreviously, we did not install any handler for Ctrl+C, but now we really\nwant to because the MSYS2 runtime learned the trick to call the\nConsoleCtrlHandler when Ctrl+C was pressed.\n\nWith this, hitting Ctrl+C while `git log` is running will only terminate\nthe Git process, but not the pager. This finally matches the behavior on\nLinux and on macOS.\n\nSigned-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>\n---\n compat/mingw.c | 9 +++++++++\n 1 file changed, 9 insertions(+)\n\ndiff --git a/compat/mingw.c b/compat/mingw.c\nindex 973049ffe3..f2b6c51f98 100644\n--- a/compat/mingw.c\n+++ b/compat/mingw.c\n@@ -3580,7 +3580,14 @@ static void adjust_symlink_flags(void)\n \t\tsymlink_file_flags |= 2;\n \t\tsymlink_directory_flags |= 2;\n \t}\n+}\n \n+static BOOL WINAPI handle_ctrl_c(DWORD ctrl_type)\n+{\n+\tif (ctrl_type != CTRL_C_EVENT)\n+\t\treturn FALSE; /* we did not handle this */\n+\tmingw_raise(SIGINT);\n+\treturn TRUE; /* we did handle this */\n }\n \n #ifdef _MSC_VER\n@@ -3617,6 +3624,8 @@ int wmain(int argc, const wchar_t **wargv)\n #endif\n #endif\n \n+\tSetConsoleCtrlHandler(handle_ctrl_c, TRUE);\n+\n \tmaybe_redirect_std_handles();\n \tadjust_symlink_flags();\n \n-- \ngitgitgadget\n"}]}