summaryrefslogtreecommitdiff
path: root/tools/windows/process.c
blob: 8bc9337305ba458253f800da93512b40da451068 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/*
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MIT
 *
 * Portions created by VMware are Copyright (c) 2007-2012 VMware, Inc.
 * All Rights Reserved.
 *
 * Portions created by Tony Garnock-Jones are Copyright (c) 2009-2010
 * VMware, Inc. and Tony Garnock-Jones. All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * ***** END LICENSE BLOCK *****
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <io.h>
#include <windows.h>

#include "common.h"
#include "process.h"

void die_windows_error(const char *fmt, ...)
{
	char *msg;

	va_list ap;
	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);

	if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
			       | FORMAT_MESSAGE_ALLOCATE_BUFFER,
			   NULL, GetLastError(),
			   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			   (LPSTR)&msg, 0, NULL))
		msg = "(failed to retrieve Windows error message)";

	fprintf(stderr, ": %s\n", msg);
	exit(1);
}

static char *make_command_line(const char *const *argv)
{
	int i;
	size_t len = 1; /* initial quotes */
	char *buf;
	char *dest;

	/* calculate the length of the required buffer, making worst
	   case assumptions for simplicity */
	for (i = 0;;) {
		/* each character could need escaping */
		len += strlen(argv[i]) * 2;

		if (!argv[++i])
			break;

		len += 3; /* quotes, space, quotes */
	}

	len += 2; /* final quotes and the terminating zero */

	dest = buf = malloc(len);
	if (!buf)
		die("allocating memory for subprocess command line");

	/* Here we perform the inverse of the CommandLineToArgvW
	   function.  Note that its rules are slightly crazy: A
	   sequence of backslashes only act to escape if followed by
	   double quotes.  A sequence of backslashes not followed by
	   double quotes is untouched. */

	for (i = 0;;) {
		const char *src = argv[i];
		int backslashes = 0;

		*dest++ = '\"';

		for (;;) {
			switch (*src) {
			case 0:
				goto done;

			case '\"':
				for (; backslashes; backslashes--)
					*dest++ = '\\';

				*dest++ = '\\';
				*dest++ = '\"';
				break;

			case '\\':
				backslashes++;
				*dest++ = '\\';
				break;

			default:
				backslashes = 0;
				*dest++ = *src;
				break;
			}

			src++;
		}
	done:
		for (; backslashes; backslashes--)
			*dest++ = '\\';

		*dest++ = '\"';

		if (!argv[++i])
			break;

		*dest++ = ' ';
	}

	*dest++ = 0;
	return buf;
}

void pipeline(const char *const *argv, struct pipeline *pl)
{
	HANDLE in_read_handle, in_write_handle;
	SECURITY_ATTRIBUTES sec_attr;
	PROCESS_INFORMATION proc_info;
	STARTUPINFO start_info;
	char *cmdline = make_command_line(argv);

	sec_attr.nLength = sizeof sec_attr;
	sec_attr.bInheritHandle = TRUE;
	sec_attr.lpSecurityDescriptor = NULL;

	if (!CreatePipe(&in_read_handle, &in_write_handle, &sec_attr, 0))
		die_windows_error("CreatePipe");

	if (!SetHandleInformation(in_write_handle, HANDLE_FLAG_INHERIT, 0))
		die_windows_error("SetHandleInformation");

	/* when in Rome... */
	ZeroMemory(&proc_info, sizeof proc_info);
	ZeroMemory(&start_info, sizeof start_info);

	start_info.cb = sizeof start_info;
	start_info.dwFlags |= STARTF_USESTDHANDLES;

	if ((start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE))
	                                             == INVALID_HANDLE_VALUE
	    || (start_info.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE))
	                                             == INVALID_HANDLE_VALUE)
		die_windows_error("GetStdHandle");

	start_info.hStdInput = in_read_handle;

	if (!CreateProcess(NULL, cmdline, NULL, NULL, TRUE, 0,
			   NULL, NULL, &start_info, &proc_info))
		die_windows_error("CreateProcess");

	free(cmdline);

	if (!CloseHandle(proc_info.hThread))
		die_windows_error("CloseHandle for thread");
	if (!CloseHandle(in_read_handle))
		die_windows_error("CloseHandle");

	pl->proc_handle = proc_info.hProcess;
	pl->infd = _open_osfhandle((intptr_t)in_write_handle, 0);
}

int finish_pipeline(struct pipeline *pl)
{
	DWORD code;

	if (close(pl->infd))
		die_errno(errno, "close");

	for (;;) {
		if (!GetExitCodeProcess(pl->proc_handle, &code))
			die_windows_error("GetExitCodeProcess");
		if (code != STILL_ACTIVE)
			break;

		if (WaitForSingleObject(pl->proc_handle, INFINITE)
		                                           == WAIT_FAILED)
			die_windows_error("WaitForSingleObject");
	}

	if (!CloseHandle(pl->proc_handle))
		die_windows_error("CloseHandle for process");

	return code;
}