Skip to content

Commit 5f291d6

Browse files
committed
Merge pull request #1170 from dscho/mingw-kill-process
Handle Ctrl+C in Git Bash nicely
2 parents cbe9c63 + bf19636 commit 5f291d6

File tree

2 files changed

+230
-8
lines changed

2 files changed

+230
-8
lines changed

compat/mingw.c

Lines changed: 66 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include "../run-command.h"
88
#include "../cache.h"
99
#include "win32/lazyload.h"
10+
#include "win32/exit-process.h"
1011

1112
#define HCAST(type, handle) ((type)(intptr_t)handle)
1213

@@ -1431,10 +1432,44 @@ struct pinfo_t {
14311432
static struct pinfo_t *pinfo = NULL;
14321433
CRITICAL_SECTION pinfo_cs;
14331434

1435+
#ifndef SIGRTMAX
1436+
#define SIGRTMAX 63
1437+
#endif
1438+
1439+
static void kill_child_processes_on_signal(void)
1440+
{
1441+
DWORD status;
1442+
1443+
/*
1444+
* Only continue if the process was terminated by a signal, as
1445+
* indicated by the exit status (128 + sig_no).
1446+
*
1447+
* As we are running in an atexit() handler, the exit code has been
1448+
* set at this stage by the ExitProcess() function already.
1449+
*/
1450+
if (!GetExitCodeProcess(GetCurrentProcess(), &status) ||
1451+
status <= 128 || status > 128 + SIGRTMAX)
1452+
return;
1453+
1454+
EnterCriticalSection(&pinfo_cs);
1455+
1456+
while (pinfo) {
1457+
struct pinfo_t *info = pinfo;
1458+
pinfo = pinfo->next;
1459+
if (exit_process(info->proc, status))
1460+
/* the handle is still valid in case of error */
1461+
CloseHandle(info->proc);
1462+
free(info);
1463+
}
1464+
1465+
LeaveCriticalSection(&pinfo_cs);
1466+
}
1467+
14341468
static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
14351469
const char *dir,
14361470
int prepend_cmd, int fhin, int fhout, int fherr)
14371471
{
1472+
static int atexit_handler_initialized;
14381473
STARTUPINFOW si;
14391474
PROCESS_INFORMATION pi;
14401475
struct strbuf args;
@@ -1444,6 +1479,17 @@ static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaen
14441479
HANDLE cons;
14451480
const char *strace_env;
14461481

1482+
if (!atexit_handler_initialized) {
1483+
atexit_handler_initialized = 1;
1484+
/*
1485+
* On Windows, there is no POSIX signaling. Instead, we inject
1486+
* a thread calling ExitProcess(128 + sig_no); and that calls
1487+
* the *atexit* handlers. Catch this condition and kill child
1488+
* processes with the same signal.
1489+
*/
1490+
atexit(kill_child_processes_on_signal);
1491+
}
1492+
14471493
do_unset_environment_variables();
14481494

14491495
/* Determine whether or not we are associated to a console */
@@ -1674,16 +1720,28 @@ int mingw_execvp(const char *cmd, char *const *argv)
16741720
int mingw_kill(pid_t pid, int sig)
16751721
{
16761722
if (pid > 0 && sig == SIGTERM) {
1677-
HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1678-
1679-
if (TerminateProcess(h, -1)) {
1723+
HANDLE h = OpenProcess(PROCESS_CREATE_THREAD |
1724+
PROCESS_QUERY_INFORMATION |
1725+
PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
1726+
PROCESS_VM_READ | PROCESS_TERMINATE,
1727+
FALSE, pid);
1728+
int ret;
1729+
1730+
if (h)
1731+
ret = exit_process(h, 128 + sig);
1732+
else {
1733+
h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1734+
if (!h) {
1735+
errno = err_win_to_posix(GetLastError());
1736+
return -1;
1737+
}
1738+
ret = terminate_process_tree(h, 128 + sig);
1739+
}
1740+
if (ret) {
1741+
errno = err_win_to_posix(GetLastError());
16801742
CloseHandle(h);
1681-
return 0;
16821743
}
1683-
1684-
errno = err_win_to_posix(GetLastError());
1685-
CloseHandle(h);
1686-
return -1;
1744+
return ret;
16871745
} else if (pid > 0 && sig == 0) {
16881746
HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
16891747
if (h) {

compat/win32/exit-process.h

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
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+
* For simplicity, these functions are marked as file-local.
12+
*/
13+
14+
#include <tlhelp32.h>
15+
16+
/*
17+
* Terminates the process corresponding to the process ID and all of its
18+
* directly and indirectly spawned subprocesses.
19+
*
20+
* This way of terminating the processes is not gentle: the processes get
21+
* no chance of cleaning up after themselves (closing file handles, removing
22+
* .lock files, terminating spawned processes (if any), etc).
23+
*/
24+
static int terminate_process_tree(HANDLE main_process, int exit_status)
25+
{
26+
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
27+
PROCESSENTRY32 entry;
28+
DWORD pids[16384];
29+
int max_len = sizeof(pids) / sizeof(*pids), i, len, ret = 0;
30+
pid_t pid = GetProcessId(main_process);
31+
32+
pids[0] = (DWORD)pid;
33+
len = 1;
34+
35+
/*
36+
* Even if Process32First()/Process32Next() seem to traverse the
37+
* processes in topological order (i.e. parent processes before
38+
* child processes), there is nothing in the Win32 API documentation
39+
* suggesting that this is guaranteed.
40+
*
41+
* Therefore, run through them at least twice and stop when no more
42+
* process IDs were added to the list.
43+
*/
44+
for (;;) {
45+
int orig_len = len;
46+
47+
memset(&entry, 0, sizeof(entry));
48+
entry.dwSize = sizeof(entry);
49+
50+
if (!Process32First(snapshot, &entry))
51+
break;
52+
53+
do {
54+
for (i = len - 1; i >= 0; i--) {
55+
if (pids[i] == entry.th32ProcessID)
56+
break;
57+
if (pids[i] == entry.th32ParentProcessID)
58+
pids[len++] = entry.th32ProcessID;
59+
}
60+
} while (len < max_len && Process32Next(snapshot, &entry));
61+
62+
if (orig_len == len || len >= max_len)
63+
break;
64+
}
65+
66+
for (i = len - 1; i > 0; i--) {
67+
HANDLE process = OpenProcess(PROCESS_TERMINATE, FALSE, pids[i]);
68+
69+
if (process) {
70+
if (!TerminateProcess(process, exit_status))
71+
ret = -1;
72+
CloseHandle(process);
73+
}
74+
}
75+
if (!TerminateProcess(main_process, exit_status))
76+
ret = -1;
77+
CloseHandle(main_process);
78+
79+
return ret;
80+
}
81+
82+
/**
83+
* Determine whether a process runs in the same architecture as the current
84+
* one. That test is required before we assume that GetProcAddress() returns
85+
* a valid address *for the target process*.
86+
*/
87+
static inline int process_architecture_matches_current(HANDLE process)
88+
{
89+
static BOOL current_is_wow = -1;
90+
BOOL is_wow;
91+
92+
if (current_is_wow == -1 &&
93+
!IsWow64Process (GetCurrentProcess(), &current_is_wow))
94+
current_is_wow = -2;
95+
if (current_is_wow == -2)
96+
return 0; /* could not determine current process' WoW-ness */
97+
if (!IsWow64Process (process, &is_wow))
98+
return 0; /* cannot determine */
99+
return is_wow == current_is_wow;
100+
}
101+
102+
/**
103+
* Inject a thread into the given process that runs ExitProcess().
104+
*
105+
* Note: as kernel32.dll is loaded before any process, the other process and
106+
* this process will have ExitProcess() at the same address.
107+
*
108+
* This function expects the process handle to have the access rights for
109+
* CreateRemoteThread(): PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION,
110+
* PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ.
111+
*
112+
* The idea comes from the Dr Dobb's article "A Safer Alternative to
113+
* TerminateProcess()" by Andrew Tucker (July 1, 1999),
114+
* http://www.drdobbs.com/a-safer-alternative-to-terminateprocess/184416547
115+
*
116+
* If this method fails, we fall back to running terminate_process_tree().
117+
*/
118+
static int exit_process(HANDLE process, int exit_code)
119+
{
120+
DWORD code;
121+
122+
if (GetExitCodeProcess(process, &code) && code == STILL_ACTIVE) {
123+
static int initialized;
124+
static LPTHREAD_START_ROUTINE exit_process_address;
125+
PVOID arg = (PVOID)(intptr_t)exit_code;
126+
DWORD thread_id;
127+
HANDLE thread = NULL;
128+
129+
if (!initialized) {
130+
HINSTANCE kernel32 = GetModuleHandle("kernel32");
131+
if (!kernel32)
132+
die("BUG: cannot find kernel32");
133+
exit_process_address = (LPTHREAD_START_ROUTINE)
134+
GetProcAddress(kernel32, "ExitProcess");
135+
initialized = 1;
136+
}
137+
if (!exit_process_address ||
138+
!process_architecture_matches_current(process))
139+
return terminate_process_tree(process, exit_code);
140+
141+
thread = CreateRemoteThread(process, NULL, 0,
142+
exit_process_address,
143+
arg, 0, &thread_id);
144+
if (thread) {
145+
CloseHandle(thread);
146+
/*
147+
* If the process survives for 10 seconds (a completely
148+
* arbitrary value picked from thin air), fall back to
149+
* killing the process tree via TerminateProcess().
150+
*/
151+
if (WaitForSingleObject(process, 10000) ==
152+
WAIT_OBJECT_0) {
153+
CloseHandle(process);
154+
return 0;
155+
}
156+
}
157+
158+
return terminate_process_tree(process, exit_code);
159+
}
160+
161+
return 0;
162+
}
163+
164+
#endif

0 commit comments

Comments
 (0)