Skip to content

Commit e9cb332

Browse files
committed
squash! Kill also children of the process to be killed via Ctrl+C
Try to kill Win32 processes gently upon Ctrl+C When a process is terminated via TerminateProcess(), it has no chance to do anything in the way of cleaning up. This is particularly noticeable when a lengthy Git for Windows process tries to update Git's index file and leaves behind an index.lock file. Git's idea is to remove the stale index.lock file in that case, using the signal and atexit handlers available in Linux. But those signal handlers never run. Note: this is not an issue for MSYS2 processes because MSYS2 emulates Unix' signal system accurately, both for the process sending the kill signal and the process receiving it. Win32 processes do not have such a signal handler, though, instead MSYS2 shuts them down via `TerminateProcess()`. Let's use a gentler method, described in the Dr Dobb's article "A Safer Alternative to TerminateProcess()" by Andrew Tucker (July 1, 1999), http://www.drdobbs.com/a-safer-alternative-to-terminateprocess/184416547 Essentially, we inject a new thread into the running process that does nothing else than running the ExitProcess() function. If that fails, or when the process still lives on after 10 seconds, we fall back to calling TerminateProcess(), but in that case we take pains to kill also processes directly or indirectly spawned by that process; TerminateProcess() does not give any process a chance to terminate its child processes. Originally, we wanted to call the function `GenerateConsoleCtrlEvent()` for SIGTERM with console processes, but 1) that may not work as it requires a process *group* ID (i.e. the process ID of the initial process group member, which we may not have), and 2) it does not kill the process *tree* on Windows 7 and earlier. Note: we do not use the NtQueryInformationProcess() function because 1) it is marked internal and subject to change at any time of Microsoft's choosing, and 2) it does not even officially report the child/parent relationship (the pid of the parent process is stored in the `Reserved3` slot of the `PROCESS_BASIC_INFORMATION` structure). Instead, we resort to the Toolhelp32 API -- which happily also works on 64-bit Windows -- to enumerate the process tree and reconstruct the process tree rooted in the process we intend to kill. While at it, we also fix the exit status: the convention is to add 128 to the signal number, to give exit code handlers a chance to detect an "exit by signal" condition. This fixes the MSYS2 side of the bug where interrupting `git clone https://...` would send the spawned-off `git remote-https` process into the background instead of interrupting it, i.e. the clone would continue and its progress would be reported mercilessly to the console window without the user being able to do anything about it (short of firing up the task manager and killing the appropriate task manually). Note that this special-handling is only necessary when *MSYS2* handles the Ctrl+C event, e.g. when interrupting a process started from within MinTTY or any other non-cmd-based terminal emulator. If the process was started from within `cmd.exe`'s terminal window, child processes are already killed appropriately upon Ctrl+C. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 82014d1 commit e9cb332

File tree

3 files changed

+172
-61
lines changed

3 files changed

+172
-61
lines changed

winsup/cygwin/exceptions.cc

+2-4
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ details. */
2727
#include "child_info.h"
2828
#include "ntdll.h"
2929
#include "exception.h"
30+
#include "cygwin/exit_process.h"
3031

3132
/* Definitions for code simplification */
3233
#ifdef __x86_64__
@@ -1547,10 +1548,7 @@ sigpacket::process ()
15471548
if (have_execed)
15481549
{
15491550
sigproc_printf ("terminating captive process");
1550-
if ((sigExeced = si.si_signo) == SIGINT)
1551-
kill_process_tree (GetProcessId (ch_spawn), sigExeced = si.si_signo);
1552-
else
1553-
TerminateProcess (ch_spawn, sigExeced = si.si_signo);
1551+
exit_process (ch_spawn, 128 + (sigExeced = si.si_signo));
15541552
}
15551553
/* Dispatch to the appropriate function. */
15561554
sigproc_printf ("signal %d, signal handler %p", si.si_signo, handler);
+170
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
#ifndef EXIT_PROCESS_H
2+
#define EXIT_PROCESS_H
3+
4+
/*
5+
* This file contains functions to terminate a Win32 process, as gently as
6+
* possible.
7+
*
8+
* At first, we will attempt to inject a thread that calls ExitProcess(). If
9+
* that fails, we will fall back to terminating the entire process tree.
10+
*
11+
* As we do not want to export this function in the MSYS2 runtime, these
12+
* functions are marked as file-local.
13+
*/
14+
15+
#include <tlhelp32.h>
16+
17+
/**
18+
* Terminates the process corresponding to the process ID and all of its
19+
* directly and indirectly spawned subprocesses.
20+
*
21+
* This way of terminating the processes is not gentle: the processes get
22+
* no chance of cleaning up after themselves (closing file handles, removing
23+
* .lock files, terminating spawned processes (if any), etc).
24+
*/
25+
static int
26+
terminate_process_tree(HANDLE main_process, int exit_code)
27+
{
28+
HANDLE snapshot = CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0);
29+
PROCESSENTRY32 entry;
30+
DWORD pids[16384];
31+
int max_len = sizeof (pids) / sizeof (*pids), i, len, ret = 0;
32+
pid_t pid = GetProcessId (main_process);
33+
34+
pids[0] = (DWORD) pid;
35+
len = 1;
36+
37+
/*
38+
* Even if Process32First()/Process32Next() seem to traverse the
39+
* processes in topological order (i.e. parent processes before
40+
* child processes), there is nothing in the Win32 API documentation
41+
* suggesting that this is guaranteed.
42+
*
43+
* Therefore, run through them at least twice and stop when no more
44+
* process IDs were added to the list.
45+
*/
46+
for (;;)
47+
{
48+
int orig_len = len;
49+
50+
memset (&entry, 0, sizeof (entry));
51+
entry.dwSize = sizeof (entry);
52+
53+
if (!Process32First (snapshot, &entry))
54+
break;
55+
56+
do
57+
{
58+
for (i = len - 1; i >= 0; i--)
59+
{
60+
if (pids[i] == entry.th32ProcessID)
61+
break;
62+
if (pids[i] == entry.th32ParentProcessID)
63+
pids[len++] = entry.th32ProcessID;
64+
}
65+
}
66+
while (len < max_len && Process32Next (snapshot, &entry));
67+
68+
if (orig_len == len || len >= max_len)
69+
break;
70+
}
71+
72+
for (i = len - 1; i >= 0; i--)
73+
{
74+
HANDLE process = i == 0 ? main_process :
75+
OpenProcess (PROCESS_TERMINATE, FALSE, pids[i]);
76+
77+
if (process)
78+
{
79+
if (!TerminateProcess (process, exit_code))
80+
ret = -1;
81+
CloseHandle (process);
82+
}
83+
}
84+
85+
return ret;
86+
}
87+
88+
/**
89+
* Determine whether a process runs in the same architecture as the current
90+
* one. That test is required before we assume that GetProcAddress() returns
91+
* a valid address *for the target process*.
92+
*/
93+
static inline bool
94+
process_architecture_matches_current(HANDLE process)
95+
{
96+
static BOOL current_is_wow = -1;
97+
BOOL is_wow;
98+
99+
if (current_is_wow == -1 &&
100+
!IsWow64Process (GetCurrentProcess (), &current_is_wow))
101+
current_is_wow = -2;
102+
if (current_is_wow == -2)
103+
return false; /* could not determine current process' WoW-ness */
104+
if (!IsWow64Process (process, &is_wow))
105+
return false; /* cannot determine */
106+
return is_wow == current_is_wow;
107+
}
108+
109+
/**
110+
* Inject a thread into the given process that runs ExitProcess().
111+
*
112+
* Note: as kernel32.dll is loaded before any process, the other process and
113+
* this process will have ExitProcess() at the same address.
114+
*
115+
* This function expects the process handle to have the access rights for
116+
* CreateRemoteThread(): PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION,
117+
* PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ.
118+
*
119+
* The idea comes from the Dr Dobb's article "A Safer Alternative to
120+
* TerminateProcess()" by Andrew Tucker (July 1, 1999),
121+
* http://www.drdobbs.com/a-safer-alternative-to-terminateprocess/184416547
122+
*
123+
* If this method fails, we fall back to running terminate_process_tree().
124+
*/
125+
static int
126+
exit_process(HANDLE process, int exit_code)
127+
{
128+
DWORD code;
129+
130+
if (GetExitCodeProcess (process, &code) && code == STILL_ACTIVE)
131+
{
132+
/*
133+
* We cannot determine the address of ExitProcess() for a process
134+
* that does not match the current architecture (e.g. for a 32-bit
135+
* process when we're running in 64-bit mode).
136+
*/
137+
if (process_architecture_matches_current (process))
138+
{
139+
static LPTHREAD_START_ROUTINE exit_process_address;
140+
if (!exit_process_address)
141+
{
142+
HINSTANCE kernel32 = GetModuleHandle ("kernel32");
143+
exit_process_address = (LPTHREAD_START_ROUTINE)
144+
GetProcAddress (kernel32, "ExitProcess");
145+
}
146+
DWORD thread_id;
147+
HANDLE thread = !exit_process_address ? NULL :
148+
CreateRemoteThread (process, NULL, 0, exit_process_address,
149+
(PVOID)exit_code, 0, &thread_id);
150+
151+
if (thread)
152+
{
153+
CloseHandle (thread);
154+
/*
155+
* Wait 10 seconds (arbitrary constant) for the process to
156+
* finish; After that grace period, fall back to terminating
157+
* non-gently.
158+
*/
159+
if (WaitForSingleObject (process, 10000) == WAIT_OBJECT_0)
160+
return 0;
161+
}
162+
}
163+
164+
return terminate_process_tree (process, exit_code);
165+
}
166+
167+
return -1;
168+
}
169+
170+
#endif

winsup/cygwin/signal.cc

-57
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ Cygwin license. Please consult the file "CYGWIN_LICENSE" for
1010
details. */
1111

1212
#include "winsup.h"
13-
#include <tlhelp32.h>
1413
#include <stdlib.h>
1514
#include <sys/cygwin.h>
1615
#include "pinfo.h"
@@ -359,62 +358,6 @@ killpg (pid_t pgrp, int sig)
359358
return kill (-pgrp, sig);
360359
}
361360

362-
/**
363-
* Terminates the process corresponding to the process ID and all of its
364-
* directly and indirectly spawned subprocesses.
365-
*/
366-
extern "C" void
367-
kill_process_tree(pid_t pid, int sig)
368-
{
369-
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
370-
PROCESSENTRY32 entry;
371-
DWORD pids[16384];
372-
int max_len = sizeof(pids) / sizeof(*pids), i, len;
373-
374-
pids[0] = (DWORD) pid;
375-
len = 1;
376-
377-
/*
378-
* Even if Process32First()/Process32Next() seem to traverse the
379-
* processes in topological order (i.e. parent processes before
380-
* child processes), there is nothing in the Win32 API documentation
381-
* suggesting that this is guaranteed.
382-
*
383-
* Therefore, run through them at least twice and stop when no more
384-
* process IDs were added to the list.
385-
*/
386-
for (;;) {
387-
int orig_len = len;
388-
389-
memset(&entry, 0, sizeof(entry));
390-
entry.dwSize = sizeof(entry);
391-
392-
if (!Process32First(snapshot, &entry))
393-
break;
394-
395-
do {
396-
for (i = len - 1; i >= 0; i--) {
397-
if (pids[i] == entry.th32ProcessID)
398-
break;
399-
if (pids[i] == entry.th32ParentProcessID)
400-
pids[len++] = entry.th32ProcessID;
401-
}
402-
} while (len < max_len && Process32Next(snapshot, &entry));
403-
404-
if (orig_len == len || len >= max_len)
405-
break;
406-
}
407-
408-
for (i = len - 1; i >= 0; i--) {
409-
HANDLE process = OpenProcess(PROCESS_TERMINATE, FALSE, pids[i]);
410-
411-
if (process) {
412-
TerminateProcess(process, sig << 8);
413-
CloseHandle(process);
414-
}
415-
}
416-
}
417-
418361
extern "C" void
419362
abort (void)
420363
{

0 commit comments

Comments
 (0)