1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include <wchar.h>
5 #include "../strbuf.h"
6 #include "../run-command.h"
7 #include "../cache.h"
8 #include "win32/lazyload.h"
9 #include "../config.h"
10 #include "dir.h"
11 
12 #define HCAST(type, handle) ((type)(intptr_t)handle)
13 
14 static const int delay[] = { 0, 1, 10, 20, 40 };
15 
open_in_gdb(void)16 void open_in_gdb(void)
17 {
18 	static struct child_process cp = CHILD_PROCESS_INIT;
19 	extern char *_pgmptr;
20 
21 	strvec_pushl(&cp.args, "mintty", "gdb", NULL);
22 	strvec_pushf(&cp.args, "--pid=%d", getpid());
23 	cp.clean_on_exit = 1;
24 	if (start_command(&cp) < 0)
25 		die_errno("Could not start gdb");
26 	sleep(1);
27 }
28 
err_win_to_posix(DWORD winerr)29 int err_win_to_posix(DWORD winerr)
30 {
31 	int error = ENOSYS;
32 	switch(winerr) {
33 	case ERROR_ACCESS_DENIED: error = EACCES; break;
34 	case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
35 	case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
36 	case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
37 	case ERROR_ALREADY_EXISTS: error = EEXIST; break;
38 	case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
39 	case ERROR_BAD_COMMAND: error = EIO; break;
40 	case ERROR_BAD_DEVICE: error = ENODEV; break;
41 	case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
42 	case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
43 	case ERROR_BAD_FORMAT: error = ENOEXEC; break;
44 	case ERROR_BAD_LENGTH: error = EINVAL; break;
45 	case ERROR_BAD_PATHNAME: error = ENOENT; break;
46 	case ERROR_BAD_PIPE: error = EPIPE; break;
47 	case ERROR_BAD_UNIT: error = ENODEV; break;
48 	case ERROR_BAD_USERNAME: error = EINVAL; break;
49 	case ERROR_BROKEN_PIPE: error = EPIPE; break;
50 	case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
51 	case ERROR_BUSY: error = EBUSY; break;
52 	case ERROR_BUSY_DRIVE: error = EBUSY; break;
53 	case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
54 	case ERROR_CANNOT_MAKE: error = EACCES; break;
55 	case ERROR_CANTOPEN: error = EIO; break;
56 	case ERROR_CANTREAD: error = EIO; break;
57 	case ERROR_CANTWRITE: error = EIO; break;
58 	case ERROR_CRC: error = EIO; break;
59 	case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
60 	case ERROR_DEVICE_IN_USE: error = EBUSY; break;
61 	case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
62 	case ERROR_DIRECTORY: error = EINVAL; break;
63 	case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
64 	case ERROR_DISK_CHANGE: error = EIO; break;
65 	case ERROR_DISK_FULL: error = ENOSPC; break;
66 	case ERROR_DRIVE_LOCKED: error = EBUSY; break;
67 	case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
68 	case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
69 	case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
70 	case ERROR_FILE_EXISTS: error = EEXIST; break;
71 	case ERROR_FILE_INVALID: error = ENODEV; break;
72 	case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
73 	case ERROR_GEN_FAILURE: error = EIO; break;
74 	case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
75 	case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
76 	case ERROR_INVALID_ACCESS: error = EACCES; break;
77 	case ERROR_INVALID_ADDRESS: error = EFAULT; break;
78 	case ERROR_INVALID_BLOCK: error = EFAULT; break;
79 	case ERROR_INVALID_DATA: error = EINVAL; break;
80 	case ERROR_INVALID_DRIVE: error = ENODEV; break;
81 	case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
82 	case ERROR_INVALID_FLAGS: error = EINVAL; break;
83 	case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
84 	case ERROR_INVALID_HANDLE: error = EBADF; break;
85 	case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
86 	case ERROR_INVALID_NAME: error = EINVAL; break;
87 	case ERROR_INVALID_OWNER: error = EINVAL; break;
88 	case ERROR_INVALID_PARAMETER: error = EINVAL; break;
89 	case ERROR_INVALID_PASSWORD: error = EPERM; break;
90 	case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
91 	case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
92 	case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
93 	case ERROR_INVALID_WORKSTATION: error = EACCES; break;
94 	case ERROR_IO_DEVICE: error = EIO; break;
95 	case ERROR_IO_INCOMPLETE: error = EINTR; break;
96 	case ERROR_LOCKED: error = EBUSY; break;
97 	case ERROR_LOCK_VIOLATION: error = EACCES; break;
98 	case ERROR_LOGON_FAILURE: error = EACCES; break;
99 	case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
100 	case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
101 	case ERROR_MORE_DATA: error = EPIPE; break;
102 	case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
103 	case ERROR_NOACCESS: error = EFAULT; break;
104 	case ERROR_NONE_MAPPED: error = EINVAL; break;
105 	case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
106 	case ERROR_NOT_READY: error = EAGAIN; break;
107 	case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
108 	case ERROR_NO_DATA: error = EPIPE; break;
109 	case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
110 	case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
111 	case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
112 	case ERROR_OPEN_FAILED: error = EIO; break;
113 	case ERROR_OPEN_FILES: error = EBUSY; break;
114 	case ERROR_OPERATION_ABORTED: error = EINTR; break;
115 	case ERROR_OUTOFMEMORY: error = ENOMEM; break;
116 	case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
117 	case ERROR_PATH_BUSY: error = EBUSY; break;
118 	case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
119 	case ERROR_PIPE_BUSY: error = EBUSY; break;
120 	case ERROR_PIPE_CONNECTED: error = EPIPE; break;
121 	case ERROR_PIPE_LISTENING: error = EPIPE; break;
122 	case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
123 	case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
124 	case ERROR_READ_FAULT: error = EIO; break;
125 	case ERROR_SEEK: error = EIO; break;
126 	case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
127 	case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
128 	case ERROR_SHARING_VIOLATION: error = EACCES; break;
129 	case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
130 	case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
131 	case ERROR_SWAPERROR: error = ENOENT; break;
132 	case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
133 	case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
134 	case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
135 	case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
136 	case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
137 	case ERROR_WRITE_FAULT: error = EIO; break;
138 	case ERROR_WRITE_PROTECT: error = EROFS; break;
139 	}
140 	return error;
141 }
142 
is_file_in_use_error(DWORD errcode)143 static inline int is_file_in_use_error(DWORD errcode)
144 {
145 	switch (errcode) {
146 	case ERROR_SHARING_VIOLATION:
147 	case ERROR_ACCESS_DENIED:
148 		return 1;
149 	}
150 
151 	return 0;
152 }
153 
read_yes_no_answer(void)154 static int read_yes_no_answer(void)
155 {
156 	char answer[1024];
157 
158 	if (fgets(answer, sizeof(answer), stdin)) {
159 		size_t answer_len = strlen(answer);
160 		int got_full_line = 0, c;
161 
162 		/* remove the newline */
163 		if (answer_len >= 2 && answer[answer_len-2] == '\r') {
164 			answer[answer_len-2] = '\0';
165 			got_full_line = 1;
166 		} else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
167 			answer[answer_len-1] = '\0';
168 			got_full_line = 1;
169 		}
170 		/* flush the buffer in case we did not get the full line */
171 		if (!got_full_line)
172 			while ((c = getchar()) != EOF && c != '\n')
173 				;
174 	} else
175 		/* we could not read, return the
176 		 * default answer which is no */
177 		return 0;
178 
179 	if (tolower(answer[0]) == 'y' && !answer[1])
180 		return 1;
181 	if (!strncasecmp(answer, "yes", sizeof(answer)))
182 		return 1;
183 	if (tolower(answer[0]) == 'n' && !answer[1])
184 		return 0;
185 	if (!strncasecmp(answer, "no", sizeof(answer)))
186 		return 0;
187 
188 	/* did not find an answer we understand */
189 	return -1;
190 }
191 
ask_yes_no_if_possible(const char * format,...)192 static int ask_yes_no_if_possible(const char *format, ...)
193 {
194 	char question[4096];
195 	const char *retry_hook[] = { NULL, NULL, NULL };
196 	va_list args;
197 
198 	va_start(args, format);
199 	vsnprintf(question, sizeof(question), format, args);
200 	va_end(args);
201 
202 	if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
203 		retry_hook[1] = question;
204 		return !run_command_v_opt(retry_hook, 0);
205 	}
206 
207 	if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
208 		return 0;
209 
210 	while (1) {
211 		int answer;
212 		fprintf(stderr, "%s (y/n) ", question);
213 
214 		if ((answer = read_yes_no_answer()) >= 0)
215 			return answer;
216 
217 		fprintf(stderr, "Sorry, I did not understand your answer. "
218 				"Please type 'y' or 'n'\n");
219 	}
220 }
221 
222 /* Windows only */
223 enum hide_dotfiles_type {
224 	HIDE_DOTFILES_FALSE = 0,
225 	HIDE_DOTFILES_TRUE,
226 	HIDE_DOTFILES_DOTGITONLY
227 };
228 
229 static int core_restrict_inherited_handles = -1;
230 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
231 static char *unset_environment_variables;
232 
mingw_core_config(const char * var,const char * value,void * cb)233 int mingw_core_config(const char *var, const char *value, void *cb)
234 {
235 	if (!strcmp(var, "core.hidedotfiles")) {
236 		if (value && !strcasecmp(value, "dotgitonly"))
237 			hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
238 		else
239 			hide_dotfiles = git_config_bool(var, value);
240 		return 0;
241 	}
242 
243 	if (!strcmp(var, "core.unsetenvvars")) {
244 		free(unset_environment_variables);
245 		unset_environment_variables = xstrdup(value);
246 		return 0;
247 	}
248 
249 	if (!strcmp(var, "core.restrictinheritedhandles")) {
250 		if (value && !strcasecmp(value, "auto"))
251 			core_restrict_inherited_handles = -1;
252 		else
253 			core_restrict_inherited_handles =
254 				git_config_bool(var, value);
255 		return 0;
256 	}
257 
258 	return 0;
259 }
260 
261 /* Normalizes NT paths as returned by some low-level APIs. */
normalize_ntpath(wchar_t * wbuf)262 static wchar_t *normalize_ntpath(wchar_t *wbuf)
263 {
264 	int i;
265 	/* fix absolute path prefixes */
266 	if (wbuf[0] == '\\') {
267 		/* strip NT namespace prefixes */
268 		if (!wcsncmp(wbuf, L"\\??\\", 4) ||
269 		    !wcsncmp(wbuf, L"\\\\?\\", 4))
270 			wbuf += 4;
271 		else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
272 			wbuf += 12;
273 		/* replace remaining '...UNC\' with '\\' */
274 		if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
275 			wbuf += 2;
276 			*wbuf = '\\';
277 		}
278 	}
279 	/* convert backslashes to slashes */
280 	for (i = 0; wbuf[i]; i++)
281 		if (wbuf[i] == '\\')
282 			wbuf[i] = '/';
283 	return wbuf;
284 }
285 
mingw_unlink(const char * pathname)286 int mingw_unlink(const char *pathname)
287 {
288 	int ret, tries = 0;
289 	wchar_t wpathname[MAX_PATH];
290 	if (xutftowcs_path(wpathname, pathname) < 0)
291 		return -1;
292 
293 	if (DeleteFileW(wpathname))
294 		return 0;
295 
296 	/* read-only files cannot be removed */
297 	_wchmod(wpathname, 0666);
298 	while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
299 		if (!is_file_in_use_error(GetLastError()))
300 			break;
301 		/*
302 		 * We assume that some other process had the source or
303 		 * destination file open at the wrong moment and retry.
304 		 * In order to give the other process a higher chance to
305 		 * complete its operation, we give up our time slice now.
306 		 * If we have to retry again, we do sleep a bit.
307 		 */
308 		Sleep(delay[tries]);
309 		tries++;
310 	}
311 	while (ret == -1 && is_file_in_use_error(GetLastError()) &&
312 	       ask_yes_no_if_possible("Unlink of file '%s' failed. "
313 			"Should I try again?", pathname))
314 	       ret = _wunlink(wpathname);
315 	return ret;
316 }
317 
is_dir_empty(const wchar_t * wpath)318 static int is_dir_empty(const wchar_t *wpath)
319 {
320 	WIN32_FIND_DATAW findbuf;
321 	HANDLE handle;
322 	wchar_t wbuf[MAX_PATH + 2];
323 	wcscpy(wbuf, wpath);
324 	wcscat(wbuf, L"\\*");
325 	handle = FindFirstFileW(wbuf, &findbuf);
326 	if (handle == INVALID_HANDLE_VALUE)
327 		return GetLastError() == ERROR_NO_MORE_FILES;
328 
329 	while (!wcscmp(findbuf.cFileName, L".") ||
330 			!wcscmp(findbuf.cFileName, L".."))
331 		if (!FindNextFileW(handle, &findbuf)) {
332 			DWORD err = GetLastError();
333 			FindClose(handle);
334 			return err == ERROR_NO_MORE_FILES;
335 		}
336 	FindClose(handle);
337 	return 0;
338 }
339 
mingw_rmdir(const char * pathname)340 int mingw_rmdir(const char *pathname)
341 {
342 	int ret, tries = 0;
343 	wchar_t wpathname[MAX_PATH];
344 	struct stat st;
345 
346 	/*
347 	 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
348 	 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
349 	 * symbolic link (if it points to a directory).
350 	 *
351 	 * This behavior breaks the assumption of e.g. `remove_path()` which
352 	 * upon successful deletion of a file will attempt to remove its parent
353 	 * directories recursively until failure (which usually happens when
354 	 * the directory is not empty).
355 	 *
356 	 * Therefore, before calling `_wrmdir()`, we first check if the path is
357 	 * a symbolic link. If it is, we exit and return the same error as
358 	 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
359 	 */
360 	if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
361 		errno = ENOTDIR;
362 		return -1;
363 	}
364 
365 	if (xutftowcs_path(wpathname, pathname) < 0)
366 		return -1;
367 
368 	while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
369 		if (!is_file_in_use_error(GetLastError()))
370 			errno = err_win_to_posix(GetLastError());
371 		if (errno != EACCES)
372 			break;
373 		if (!is_dir_empty(wpathname)) {
374 			errno = ENOTEMPTY;
375 			break;
376 		}
377 		/*
378 		 * We assume that some other process had the source or
379 		 * destination file open at the wrong moment and retry.
380 		 * In order to give the other process a higher chance to
381 		 * complete its operation, we give up our time slice now.
382 		 * If we have to retry again, we do sleep a bit.
383 		 */
384 		Sleep(delay[tries]);
385 		tries++;
386 	}
387 	while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
388 	       ask_yes_no_if_possible("Deletion of directory '%s' failed. "
389 			"Should I try again?", pathname))
390 	       ret = _wrmdir(wpathname);
391 	if (!ret)
392 		invalidate_lstat_cache();
393 	return ret;
394 }
395 
needs_hiding(const char * path)396 static inline int needs_hiding(const char *path)
397 {
398 	const char *basename;
399 
400 	if (hide_dotfiles == HIDE_DOTFILES_FALSE)
401 		return 0;
402 
403 	/* We cannot use basename(), as it would remove trailing slashes */
404 	win32_skip_dos_drive_prefix((char **)&path);
405 	if (!*path)
406 		return 0;
407 
408 	for (basename = path; *path; path++)
409 		if (is_dir_sep(*path)) {
410 			do {
411 				path++;
412 			} while (is_dir_sep(*path));
413 			/* ignore trailing slashes */
414 			if (*path)
415 				basename = path;
416 			else
417 				break;
418 		}
419 
420 	if (hide_dotfiles == HIDE_DOTFILES_TRUE)
421 		return *basename == '.';
422 
423 	assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
424 	return !strncasecmp(".git", basename, 4) &&
425 		(!basename[4] || is_dir_sep(basename[4]));
426 }
427 
set_hidden_flag(const wchar_t * path,int set)428 static int set_hidden_flag(const wchar_t *path, int set)
429 {
430 	DWORD original = GetFileAttributesW(path), modified;
431 	if (set)
432 		modified = original | FILE_ATTRIBUTE_HIDDEN;
433 	else
434 		modified = original & ~FILE_ATTRIBUTE_HIDDEN;
435 	if (original == modified || SetFileAttributesW(path, modified))
436 		return 0;
437 	errno = err_win_to_posix(GetLastError());
438 	return -1;
439 }
440 
mingw_mkdir(const char * path,int mode)441 int mingw_mkdir(const char *path, int mode)
442 {
443 	int ret;
444 	wchar_t wpath[MAX_PATH];
445 
446 	if (!is_valid_win32_path(path, 0)) {
447 		errno = EINVAL;
448 		return -1;
449 	}
450 
451 	if (xutftowcs_path(wpath, path) < 0)
452 		return -1;
453 	ret = _wmkdir(wpath);
454 	if (!ret && needs_hiding(path))
455 		return set_hidden_flag(wpath, 1);
456 	return ret;
457 }
458 
459 /*
460  * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
461  * is documented in [1] as opening a writable file handle in append mode.
462  * (It is believed that) this is atomic since it is maintained by the
463  * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
464  *
465  * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
466  *
467  * This trick does not appear to work for named pipes.  Instead it creates
468  * a named pipe client handle that cannot be written to.  Callers should
469  * just use the regular _wopen() for them.  (And since client handle gets
470  * bound to a unique server handle, it isn't really an issue.)
471  */
mingw_open_append(wchar_t const * wfilename,int oflags,...)472 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
473 {
474 	HANDLE handle;
475 	int fd;
476 	DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
477 
478 	/* only these flags are supported */
479 	if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
480 		return errno = ENOSYS, -1;
481 
482 	/*
483 	 * FILE_SHARE_WRITE is required to permit child processes
484 	 * to append to the file.
485 	 */
486 	handle = CreateFileW(wfilename, FILE_APPEND_DATA,
487 			FILE_SHARE_WRITE | FILE_SHARE_READ,
488 			NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
489 	if (handle == INVALID_HANDLE_VALUE) {
490 		DWORD err = GetLastError();
491 
492 		/*
493 		 * Some network storage solutions (e.g. Isilon) might return
494 		 * ERROR_INVALID_PARAMETER instead of expected error
495 		 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
496 		 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
497 		 */
498 		if (err == ERROR_INVALID_PARAMETER)
499 			err = ERROR_PATH_NOT_FOUND;
500 
501 		errno = err_win_to_posix(err);
502 		return -1;
503 	}
504 
505 	/*
506 	 * No O_APPEND here, because the CRT uses it only to reset the
507 	 * file pointer to EOF before each write(); but that is not
508 	 * necessary (and may lead to races) for a file created with
509 	 * FILE_APPEND_DATA.
510 	 */
511 	fd = _open_osfhandle((intptr_t)handle, O_BINARY);
512 	if (fd < 0)
513 		CloseHandle(handle);
514 	return fd;
515 }
516 
517 /*
518  * Does the pathname map to the local named pipe filesystem?
519  * That is, does it have a "//./pipe/" prefix?
520  */
is_local_named_pipe_path(const char * filename)521 static int is_local_named_pipe_path(const char *filename)
522 {
523 	return (is_dir_sep(filename[0]) &&
524 		is_dir_sep(filename[1]) &&
525 		filename[2] == '.'  &&
526 		is_dir_sep(filename[3]) &&
527 		!strncasecmp(filename+4, "pipe", 4) &&
528 		is_dir_sep(filename[8]) &&
529 		filename[9]);
530 }
531 
mingw_open(const char * filename,int oflags,...)532 int mingw_open (const char *filename, int oflags, ...)
533 {
534 	typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
535 	va_list args;
536 	unsigned mode;
537 	int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
538 	wchar_t wfilename[MAX_PATH];
539 	open_fn_t open_fn;
540 
541 	va_start(args, oflags);
542 	mode = va_arg(args, int);
543 	va_end(args);
544 
545 	if (!is_valid_win32_path(filename, !create)) {
546 		errno = create ? EINVAL : ENOENT;
547 		return -1;
548 	}
549 
550 	if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
551 		open_fn = mingw_open_append;
552 	else
553 		open_fn = _wopen;
554 
555 	if (filename && !strcmp(filename, "/dev/null"))
556 		wcscpy(wfilename, L"nul");
557 	else if (xutftowcs_path(wfilename, filename) < 0)
558 		return -1;
559 
560 	fd = open_fn(wfilename, oflags, mode);
561 
562 	if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
563 		DWORD attrs = GetFileAttributesW(wfilename);
564 		if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
565 			errno = EISDIR;
566 	}
567 	if ((oflags & O_CREAT) && needs_hiding(filename)) {
568 		/*
569 		 * Internally, _wopen() uses the CreateFile() API which errors
570 		 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
571 		 * specified and an already existing file's attributes do not
572 		 * match *exactly*. As there is no mode or flag we can set that
573 		 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
574 		 * again *without* the O_CREAT flag (that corresponds to the
575 		 * CREATE_ALWAYS flag of CreateFile()).
576 		 */
577 		if (fd < 0 && errno == EACCES)
578 			fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
579 		if (fd >= 0 && set_hidden_flag(wfilename, 1))
580 			warning("could not mark '%s' as hidden.", filename);
581 	}
582 	return fd;
583 }
584 
ctrl_ignore(DWORD type)585 static BOOL WINAPI ctrl_ignore(DWORD type)
586 {
587 	return TRUE;
588 }
589 
590 #undef fgetc
mingw_fgetc(FILE * stream)591 int mingw_fgetc(FILE *stream)
592 {
593 	int ch;
594 	if (!isatty(_fileno(stream)))
595 		return fgetc(stream);
596 
597 	SetConsoleCtrlHandler(ctrl_ignore, TRUE);
598 	while (1) {
599 		ch = fgetc(stream);
600 		if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
601 			break;
602 
603 		/* Ctrl+C was pressed, simulate SIGINT and retry */
604 		mingw_raise(SIGINT);
605 	}
606 	SetConsoleCtrlHandler(ctrl_ignore, FALSE);
607 	return ch;
608 }
609 
610 #undef fopen
mingw_fopen(const char * filename,const char * otype)611 FILE *mingw_fopen (const char *filename, const char *otype)
612 {
613 	int hide = needs_hiding(filename);
614 	FILE *file;
615 	wchar_t wfilename[MAX_PATH], wotype[4];
616 	if (filename && !strcmp(filename, "/dev/null"))
617 		wcscpy(wfilename, L"nul");
618 	else if (!is_valid_win32_path(filename, 1)) {
619 		int create = otype && strchr(otype, 'w');
620 		errno = create ? EINVAL : ENOENT;
621 		return NULL;
622 	} else if (xutftowcs_path(wfilename, filename) < 0)
623 		return NULL;
624 
625 	if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
626 		return NULL;
627 
628 	if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
629 		error("could not unhide %s", filename);
630 		return NULL;
631 	}
632 	file = _wfopen(wfilename, wotype);
633 	if (!file && GetLastError() == ERROR_INVALID_NAME)
634 		errno = ENOENT;
635 	if (file && hide && set_hidden_flag(wfilename, 1))
636 		warning("could not mark '%s' as hidden.", filename);
637 	return file;
638 }
639 
mingw_freopen(const char * filename,const char * otype,FILE * stream)640 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
641 {
642 	int hide = needs_hiding(filename);
643 	FILE *file;
644 	wchar_t wfilename[MAX_PATH], wotype[4];
645 	if (filename && !strcmp(filename, "/dev/null"))
646 		wcscpy(wfilename, L"nul");
647 	else if (!is_valid_win32_path(filename, 1)) {
648 		int create = otype && strchr(otype, 'w');
649 		errno = create ? EINVAL : ENOENT;
650 		return NULL;
651 	} else if (xutftowcs_path(wfilename, filename) < 0)
652 		return NULL;
653 
654 	if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
655 		return NULL;
656 
657 	if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
658 		error("could not unhide %s", filename);
659 		return NULL;
660 	}
661 	file = _wfreopen(wfilename, wotype, stream);
662 	if (file && hide && set_hidden_flag(wfilename, 1))
663 		warning("could not mark '%s' as hidden.", filename);
664 	return file;
665 }
666 
667 #undef fflush
mingw_fflush(FILE * stream)668 int mingw_fflush(FILE *stream)
669 {
670 	int ret = fflush(stream);
671 
672 	/*
673 	 * write() is used behind the scenes of stdio output functions.
674 	 * Since git code does not check for errors after each stdio write
675 	 * operation, it can happen that write() is called by a later
676 	 * stdio function even if an earlier write() call failed. In the
677 	 * case of a pipe whose readable end was closed, only the first
678 	 * call to write() reports EPIPE on Windows. Subsequent write()
679 	 * calls report EINVAL. It is impossible to notice whether this
680 	 * fflush invocation triggered such a case, therefore, we have to
681 	 * catch all EINVAL errors whole-sale.
682 	 */
683 	if (ret && errno == EINVAL)
684 		errno = EPIPE;
685 
686 	return ret;
687 }
688 
689 #undef write
mingw_write(int fd,const void * buf,size_t len)690 ssize_t mingw_write(int fd, const void *buf, size_t len)
691 {
692 	ssize_t result = write(fd, buf, len);
693 
694 	if (result < 0 && errno == EINVAL && buf) {
695 		/* check if fd is a pipe */
696 		HANDLE h = (HANDLE) _get_osfhandle(fd);
697 		if (GetFileType(h) == FILE_TYPE_PIPE)
698 			errno = EPIPE;
699 		else
700 			errno = EINVAL;
701 	}
702 
703 	return result;
704 }
705 
mingw_access(const char * filename,int mode)706 int mingw_access(const char *filename, int mode)
707 {
708 	wchar_t wfilename[MAX_PATH];
709 	if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
710 		return 0;
711 	if (xutftowcs_path(wfilename, filename) < 0)
712 		return -1;
713 	/* X_OK is not supported by the MSVCRT version */
714 	return _waccess(wfilename, mode & ~X_OK);
715 }
716 
mingw_chdir(const char * dirname)717 int mingw_chdir(const char *dirname)
718 {
719 	wchar_t wdirname[MAX_PATH];
720 	if (xutftowcs_path(wdirname, dirname) < 0)
721 		return -1;
722 	return _wchdir(wdirname);
723 }
724 
mingw_chmod(const char * filename,int mode)725 int mingw_chmod(const char *filename, int mode)
726 {
727 	wchar_t wfilename[MAX_PATH];
728 	if (xutftowcs_path(wfilename, filename) < 0)
729 		return -1;
730 	return _wchmod(wfilename, mode);
731 }
732 
733 /*
734  * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
735  * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
736  */
filetime_to_hnsec(const FILETIME * ft)737 static inline long long filetime_to_hnsec(const FILETIME *ft)
738 {
739 	long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
740 	/* Windows to Unix Epoch conversion */
741 	return winTime - 116444736000000000LL;
742 }
743 
filetime_to_timespec(const FILETIME * ft,struct timespec * ts)744 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
745 {
746 	long long hnsec = filetime_to_hnsec(ft);
747 	ts->tv_sec = (time_t)(hnsec / 10000000);
748 	ts->tv_nsec = (hnsec % 10000000) * 100;
749 }
750 
751 /**
752  * Verifies that safe_create_leading_directories() would succeed.
753  */
has_valid_directory_prefix(wchar_t * wfilename)754 static int has_valid_directory_prefix(wchar_t *wfilename)
755 {
756 	int n = wcslen(wfilename);
757 
758 	while (n > 0) {
759 		wchar_t c = wfilename[--n];
760 		DWORD attributes;
761 
762 		if (!is_dir_sep(c))
763 			continue;
764 
765 		wfilename[n] = L'\0';
766 		attributes = GetFileAttributesW(wfilename);
767 		wfilename[n] = c;
768 		if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
769 				attributes == FILE_ATTRIBUTE_DEVICE)
770 			return 1;
771 		if (attributes == INVALID_FILE_ATTRIBUTES)
772 			switch (GetLastError()) {
773 			case ERROR_PATH_NOT_FOUND:
774 				continue;
775 			case ERROR_FILE_NOT_FOUND:
776 				/* This implies parent directory exists. */
777 				return 1;
778 			}
779 		return 0;
780 	}
781 	return 1;
782 }
783 
784 /* We keep the do_lstat code in a separate function to avoid recursion.
785  * When a path ends with a slash, the stat will fail with ENOENT. In
786  * this case, we strip the trailing slashes and stat again.
787  *
788  * If follow is true then act like stat() and report on the link
789  * target. Otherwise report on the link itself.
790  */
do_lstat(int follow,const char * file_name,struct stat * buf)791 static int do_lstat(int follow, const char *file_name, struct stat *buf)
792 {
793 	WIN32_FILE_ATTRIBUTE_DATA fdata;
794 	wchar_t wfilename[MAX_PATH];
795 	if (xutftowcs_path(wfilename, file_name) < 0)
796 		return -1;
797 
798 	if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
799 		buf->st_ino = 0;
800 		buf->st_gid = 0;
801 		buf->st_uid = 0;
802 		buf->st_nlink = 1;
803 		buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
804 		buf->st_size = fdata.nFileSizeLow |
805 			(((off_t)fdata.nFileSizeHigh)<<32);
806 		buf->st_dev = buf->st_rdev = 0; /* not used by Git */
807 		filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
808 		filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
809 		filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
810 		if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
811 			WIN32_FIND_DATAW findbuf;
812 			HANDLE handle = FindFirstFileW(wfilename, &findbuf);
813 			if (handle != INVALID_HANDLE_VALUE) {
814 				if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
815 						(findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
816 					if (follow) {
817 						char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
818 						buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
819 					} else {
820 						buf->st_mode = S_IFLNK;
821 					}
822 					buf->st_mode |= S_IREAD;
823 					if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
824 						buf->st_mode |= S_IWRITE;
825 				}
826 				FindClose(handle);
827 			}
828 		}
829 		return 0;
830 	}
831 	switch (GetLastError()) {
832 	case ERROR_ACCESS_DENIED:
833 	case ERROR_SHARING_VIOLATION:
834 	case ERROR_LOCK_VIOLATION:
835 	case ERROR_SHARING_BUFFER_EXCEEDED:
836 		errno = EACCES;
837 		break;
838 	case ERROR_BUFFER_OVERFLOW:
839 		errno = ENAMETOOLONG;
840 		break;
841 	case ERROR_NOT_ENOUGH_MEMORY:
842 		errno = ENOMEM;
843 		break;
844 	case ERROR_PATH_NOT_FOUND:
845 		if (!has_valid_directory_prefix(wfilename)) {
846 			errno = ENOTDIR;
847 			break;
848 		}
849 		/* fallthru */
850 	default:
851 		errno = ENOENT;
852 		break;
853 	}
854 	return -1;
855 }
856 
857 /* We provide our own lstat/fstat functions, since the provided
858  * lstat/fstat functions are so slow. These stat functions are
859  * tailored for Git's usage (read: fast), and are not meant to be
860  * complete. Note that Git stat()s are redirected to mingw_lstat()
861  * too, since Windows doesn't really handle symlinks that well.
862  */
do_stat_internal(int follow,const char * file_name,struct stat * buf)863 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
864 {
865 	int namelen;
866 	char alt_name[PATH_MAX];
867 
868 	if (!do_lstat(follow, file_name, buf))
869 		return 0;
870 
871 	/* if file_name ended in a '/', Windows returned ENOENT;
872 	 * try again without trailing slashes
873 	 */
874 	if (errno != ENOENT)
875 		return -1;
876 
877 	namelen = strlen(file_name);
878 	if (namelen && file_name[namelen-1] != '/')
879 		return -1;
880 	while (namelen && file_name[namelen-1] == '/')
881 		--namelen;
882 	if (!namelen || namelen >= PATH_MAX)
883 		return -1;
884 
885 	memcpy(alt_name, file_name, namelen);
886 	alt_name[namelen] = 0;
887 	return do_lstat(follow, alt_name, buf);
888 }
889 
get_file_info_by_handle(HANDLE hnd,struct stat * buf)890 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
891 {
892 	BY_HANDLE_FILE_INFORMATION fdata;
893 
894 	if (!GetFileInformationByHandle(hnd, &fdata)) {
895 		errno = err_win_to_posix(GetLastError());
896 		return -1;
897 	}
898 
899 	buf->st_ino = 0;
900 	buf->st_gid = 0;
901 	buf->st_uid = 0;
902 	buf->st_nlink = 1;
903 	buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
904 	buf->st_size = fdata.nFileSizeLow |
905 		(((off_t)fdata.nFileSizeHigh)<<32);
906 	buf->st_dev = buf->st_rdev = 0; /* not used by Git */
907 	filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
908 	filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
909 	filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
910 	return 0;
911 }
912 
mingw_lstat(const char * file_name,struct stat * buf)913 int mingw_lstat(const char *file_name, struct stat *buf)
914 {
915 	return do_stat_internal(0, file_name, buf);
916 }
mingw_stat(const char * file_name,struct stat * buf)917 int mingw_stat(const char *file_name, struct stat *buf)
918 {
919 	return do_stat_internal(1, file_name, buf);
920 }
921 
mingw_fstat(int fd,struct stat * buf)922 int mingw_fstat(int fd, struct stat *buf)
923 {
924 	HANDLE fh = (HANDLE)_get_osfhandle(fd);
925 	DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
926 
927 	switch (type) {
928 	case FILE_TYPE_DISK:
929 		return get_file_info_by_handle(fh, buf);
930 
931 	case FILE_TYPE_CHAR:
932 	case FILE_TYPE_PIPE:
933 		/* initialize stat fields */
934 		memset(buf, 0, sizeof(*buf));
935 		buf->st_nlink = 1;
936 
937 		if (type == FILE_TYPE_CHAR) {
938 			buf->st_mode = _S_IFCHR;
939 		} else {
940 			buf->st_mode = _S_IFIFO;
941 			if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
942 				buf->st_size = avail;
943 		}
944 		return 0;
945 
946 	default:
947 		errno = EBADF;
948 		return -1;
949 	}
950 }
951 
time_t_to_filetime(time_t t,FILETIME * ft)952 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
953 {
954 	long long winTime = t * 10000000LL + 116444736000000000LL;
955 	ft->dwLowDateTime = winTime;
956 	ft->dwHighDateTime = winTime >> 32;
957 }
958 
mingw_utime(const char * file_name,const struct utimbuf * times)959 int mingw_utime (const char *file_name, const struct utimbuf *times)
960 {
961 	FILETIME mft, aft;
962 	int fh, rc;
963 	DWORD attrs;
964 	wchar_t wfilename[MAX_PATH];
965 	if (xutftowcs_path(wfilename, file_name) < 0)
966 		return -1;
967 
968 	/* must have write permission */
969 	attrs = GetFileAttributesW(wfilename);
970 	if (attrs != INVALID_FILE_ATTRIBUTES &&
971 	    (attrs & FILE_ATTRIBUTE_READONLY)) {
972 		/* ignore errors here; open() will report them */
973 		SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
974 	}
975 
976 	if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
977 		rc = -1;
978 		goto revert_attrs;
979 	}
980 
981 	if (times) {
982 		time_t_to_filetime(times->modtime, &mft);
983 		time_t_to_filetime(times->actime, &aft);
984 	} else {
985 		GetSystemTimeAsFileTime(&mft);
986 		aft = mft;
987 	}
988 	if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
989 		errno = EINVAL;
990 		rc = -1;
991 	} else
992 		rc = 0;
993 	close(fh);
994 
995 revert_attrs:
996 	if (attrs != INVALID_FILE_ATTRIBUTES &&
997 	    (attrs & FILE_ATTRIBUTE_READONLY)) {
998 		/* ignore errors again */
999 		SetFileAttributesW(wfilename, attrs);
1000 	}
1001 	return rc;
1002 }
1003 
1004 #undef strftime
mingw_strftime(char * s,size_t max,const char * format,const struct tm * tm)1005 size_t mingw_strftime(char *s, size_t max,
1006 		      const char *format, const struct tm *tm)
1007 {
1008 	/* a pointer to the original strftime in case we can't find the UCRT version */
1009 	static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1010 	size_t ret;
1011 	DECLARE_PROC_ADDR(ucrtbase.dll, size_t, strftime, char *, size_t,
1012 		const char *, const struct tm *);
1013 
1014 	if (INIT_PROC_ADDR(strftime))
1015 		ret = strftime(s, max, format, tm);
1016 	else
1017 		ret = fallback(s, max, format, tm);
1018 
1019 	if (!ret && errno == EINVAL)
1020 		die("invalid strftime format: '%s'", format);
1021 	return ret;
1022 }
1023 
sleep(unsigned int seconds)1024 unsigned int sleep (unsigned int seconds)
1025 {
1026 	Sleep(seconds*1000);
1027 	return 0;
1028 }
1029 
mingw_mktemp(char * template)1030 char *mingw_mktemp(char *template)
1031 {
1032 	wchar_t wtemplate[MAX_PATH];
1033 	if (xutftowcs_path(wtemplate, template) < 0)
1034 		return NULL;
1035 	if (!_wmktemp(wtemplate))
1036 		return NULL;
1037 	if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1038 		return NULL;
1039 	return template;
1040 }
1041 
mkstemp(char * template)1042 int mkstemp(char *template)
1043 {
1044 	char *filename = mktemp(template);
1045 	if (filename == NULL)
1046 		return -1;
1047 	return open(filename, O_RDWR | O_CREAT, 0600);
1048 }
1049 
gettimeofday(struct timeval * tv,void * tz)1050 int gettimeofday(struct timeval *tv, void *tz)
1051 {
1052 	FILETIME ft;
1053 	long long hnsec;
1054 
1055 	GetSystemTimeAsFileTime(&ft);
1056 	hnsec = filetime_to_hnsec(&ft);
1057 	tv->tv_sec = hnsec / 10000000;
1058 	tv->tv_usec = (hnsec % 10000000) / 10;
1059 	return 0;
1060 }
1061 
pipe(int filedes[2])1062 int pipe(int filedes[2])
1063 {
1064 	HANDLE h[2];
1065 
1066 	/* this creates non-inheritable handles */
1067 	if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1068 		errno = err_win_to_posix(GetLastError());
1069 		return -1;
1070 	}
1071 	filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1072 	if (filedes[0] < 0) {
1073 		CloseHandle(h[0]);
1074 		CloseHandle(h[1]);
1075 		return -1;
1076 	}
1077 	filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1078 	if (filedes[1] < 0) {
1079 		close(filedes[0]);
1080 		CloseHandle(h[1]);
1081 		return -1;
1082 	}
1083 	return 0;
1084 }
1085 
gmtime_r(const time_t * timep,struct tm * result)1086 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1087 {
1088 	if (gmtime_s(result, timep) == 0)
1089 		return result;
1090 	return NULL;
1091 }
1092 
localtime_r(const time_t * timep,struct tm * result)1093 struct tm *localtime_r(const time_t *timep, struct tm *result)
1094 {
1095 	if (localtime_s(result, timep) == 0)
1096 		return result;
1097 	return NULL;
1098 }
1099 
mingw_getcwd(char * pointer,int len)1100 char *mingw_getcwd(char *pointer, int len)
1101 {
1102 	wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1103 	DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1104 
1105 	if (!ret || ret >= ARRAY_SIZE(cwd)) {
1106 		errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1107 		return NULL;
1108 	}
1109 	ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1110 	if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1111 		HANDLE hnd = CreateFileW(cwd, 0,
1112 			FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1113 			OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1114 		if (hnd == INVALID_HANDLE_VALUE)
1115 			return NULL;
1116 		ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1117 		CloseHandle(hnd);
1118 		if (!ret || ret >= ARRAY_SIZE(wpointer))
1119 			return NULL;
1120 		if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1121 			return NULL;
1122 		return pointer;
1123 	}
1124 	if (!ret || ret >= ARRAY_SIZE(wpointer))
1125 		return NULL;
1126 	if (xwcstoutf(pointer, wpointer, len) < 0)
1127 		return NULL;
1128 	convert_slashes(pointer);
1129 	return pointer;
1130 }
1131 
1132 /*
1133  * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1134  * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1135  */
quote_arg_msvc(const char * arg)1136 static const char *quote_arg_msvc(const char *arg)
1137 {
1138 	/* count chars to quote */
1139 	int len = 0, n = 0;
1140 	int force_quotes = 0;
1141 	char *q, *d;
1142 	const char *p = arg;
1143 	if (!*p) force_quotes = 1;
1144 	while (*p) {
1145 		if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1146 			force_quotes = 1;
1147 		else if (*p == '"')
1148 			n++;
1149 		else if (*p == '\\') {
1150 			int count = 0;
1151 			while (*p == '\\') {
1152 				count++;
1153 				p++;
1154 				len++;
1155 			}
1156 			if (*p == '"' || !*p)
1157 				n += count*2 + 1;
1158 			continue;
1159 		}
1160 		len++;
1161 		p++;
1162 	}
1163 	if (!force_quotes && n == 0)
1164 		return arg;
1165 
1166 	/* insert \ where necessary */
1167 	d = q = xmalloc(st_add3(len, n, 3));
1168 	*d++ = '"';
1169 	while (*arg) {
1170 		if (*arg == '"')
1171 			*d++ = '\\';
1172 		else if (*arg == '\\') {
1173 			int count = 0;
1174 			while (*arg == '\\') {
1175 				count++;
1176 				*d++ = *arg++;
1177 			}
1178 			if (*arg == '"' || !*arg) {
1179 				while (count-- > 0)
1180 					*d++ = '\\';
1181 				/* don't escape the surrounding end quote */
1182 				if (!*arg)
1183 					break;
1184 				*d++ = '\\';
1185 			}
1186 		}
1187 		*d++ = *arg++;
1188 	}
1189 	*d++ = '"';
1190 	*d++ = '\0';
1191 	return q;
1192 }
1193 
1194 #include "quote.h"
1195 
quote_arg_msys2(const char * arg)1196 static const char *quote_arg_msys2(const char *arg)
1197 {
1198 	struct strbuf buf = STRBUF_INIT;
1199 	const char *p2 = arg, *p;
1200 
1201 	for (p = arg; *p; p++) {
1202 		int ws = isspace(*p);
1203 		if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1204 		    *p != '?' && *p != '*' && *p != '~')
1205 			continue;
1206 		if (!buf.len)
1207 			strbuf_addch(&buf, '"');
1208 		if (p != p2)
1209 			strbuf_add(&buf, p2, p - p2);
1210 		if (*p == '\\' || *p == '"')
1211 			strbuf_addch(&buf, '\\');
1212 		p2 = p;
1213 	}
1214 
1215 	if (p == arg)
1216 		strbuf_addch(&buf, '"');
1217 	else if (!buf.len)
1218 		return arg;
1219 	else
1220 		strbuf_add(&buf, p2, p - p2);
1221 
1222 	strbuf_addch(&buf, '"');
1223 	return strbuf_detach(&buf, 0);
1224 }
1225 
parse_interpreter(const char * cmd)1226 static const char *parse_interpreter(const char *cmd)
1227 {
1228 	static char buf[100];
1229 	char *p, *opt;
1230 	int n, fd;
1231 
1232 	/* don't even try a .exe */
1233 	n = strlen(cmd);
1234 	if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1235 		return NULL;
1236 
1237 	fd = open(cmd, O_RDONLY);
1238 	if (fd < 0)
1239 		return NULL;
1240 	n = read(fd, buf, sizeof(buf)-1);
1241 	close(fd);
1242 	if (n < 4)	/* at least '#!/x' and not error */
1243 		return NULL;
1244 
1245 	if (buf[0] != '#' || buf[1] != '!')
1246 		return NULL;
1247 	buf[n] = '\0';
1248 	p = buf + strcspn(buf, "\r\n");
1249 	if (!*p)
1250 		return NULL;
1251 
1252 	*p = '\0';
1253 	if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1254 		return NULL;
1255 	/* strip options */
1256 	if ((opt = strchr(p+1, ' ')))
1257 		*opt = '\0';
1258 	return p+1;
1259 }
1260 
1261 /*
1262  * exe_only means that we only want to detect .exe files, but not scripts
1263  * (which do not have an extension)
1264  */
lookup_prog(const char * dir,int dirlen,const char * cmd,int isexe,int exe_only)1265 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1266 			 int isexe, int exe_only)
1267 {
1268 	char path[MAX_PATH];
1269 	wchar_t wpath[MAX_PATH];
1270 	snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1271 
1272 	if (xutftowcs_path(wpath, path) < 0)
1273 		return NULL;
1274 
1275 	if (!isexe && _waccess(wpath, F_OK) == 0)
1276 		return xstrdup(path);
1277 	wpath[wcslen(wpath)-4] = '\0';
1278 	if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1279 		if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1280 			path[strlen(path)-4] = '\0';
1281 			return xstrdup(path);
1282 		}
1283 	}
1284 	return NULL;
1285 }
1286 
1287 /*
1288  * Determines the absolute path of cmd using the split path in path.
1289  * If cmd contains a slash or backslash, no lookup is performed.
1290  */
path_lookup(const char * cmd,int exe_only)1291 static char *path_lookup(const char *cmd, int exe_only)
1292 {
1293 	const char *path;
1294 	char *prog = NULL;
1295 	int len = strlen(cmd);
1296 	int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1297 
1298 	if (strpbrk(cmd, "/\\"))
1299 		return xstrdup(cmd);
1300 
1301 	path = mingw_getenv("PATH");
1302 	if (!path)
1303 		return NULL;
1304 
1305 	while (!prog) {
1306 		const char *sep = strchrnul(path, ';');
1307 		int dirlen = sep - path;
1308 		if (dirlen)
1309 			prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1310 		if (!*sep)
1311 			break;
1312 		path = sep + 1;
1313 	}
1314 
1315 	return prog;
1316 }
1317 
wcschrnul(const wchar_t * s,wchar_t c)1318 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1319 {
1320 	while (*s && *s != c)
1321 		s++;
1322 	return s;
1323 }
1324 
1325 /* Compare only keys */
wenvcmp(const void * a,const void * b)1326 static int wenvcmp(const void *a, const void *b)
1327 {
1328 	wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1329 	size_t p_len, q_len;
1330 
1331 	/* Find the keys */
1332 	p_len = wcschrnul(p, L'=') - p;
1333 	q_len = wcschrnul(q, L'=') - q;
1334 
1335 	/* If the length differs, include the shorter key's NUL */
1336 	if (p_len < q_len)
1337 		p_len++;
1338 	else if (p_len > q_len)
1339 		p_len = q_len + 1;
1340 
1341 	return _wcsnicmp(p, q, p_len);
1342 }
1343 
1344 /*
1345  * Build an environment block combining the inherited environment
1346  * merged with the given list of settings.
1347  *
1348  * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1349  * Values of the form "KEY" in deltaenv delete inherited values.
1350  *
1351  * Multiple entries in deltaenv for the same key are explicitly allowed.
1352  *
1353  * We return a contiguous block of UNICODE strings with a final trailing
1354  * zero word.
1355  */
make_environment_block(char ** deltaenv)1356 static wchar_t *make_environment_block(char **deltaenv)
1357 {
1358 	wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1359 	size_t wlen, s, delta_size, size;
1360 
1361 	wchar_t **array = NULL;
1362 	size_t alloc = 0, nr = 0, i;
1363 
1364 	size = 1; /* for extra NUL at the end */
1365 
1366 	/* If there is no deltaenv to apply, simply return a copy. */
1367 	if (!deltaenv || !*deltaenv) {
1368 		for (p = wenv; p && *p; ) {
1369 			size_t s = wcslen(p) + 1;
1370 			size += s;
1371 			p += s;
1372 		}
1373 
1374 		ALLOC_ARRAY(result, size);
1375 		COPY_ARRAY(result, wenv, size);
1376 		FreeEnvironmentStringsW(wenv);
1377 		return result;
1378 	}
1379 
1380 	/*
1381 	 * If there is a deltaenv, let's accumulate all keys into `array`,
1382 	 * sort them using the stable git_stable_qsort() and then copy,
1383 	 * skipping duplicate keys
1384 	 */
1385 	for (p = wenv; p && *p; ) {
1386 		ALLOC_GROW(array, nr + 1, alloc);
1387 		s = wcslen(p) + 1;
1388 		array[nr++] = p;
1389 		p += s;
1390 		size += s;
1391 	}
1392 
1393 	/* (over-)assess size needed for wchar version of deltaenv */
1394 	for (delta_size = 0, i = 0; deltaenv[i]; i++)
1395 		delta_size += strlen(deltaenv[i]) * 2 + 1;
1396 	ALLOC_ARRAY(wdeltaenv, delta_size);
1397 
1398 	/* convert the deltaenv, appending to array */
1399 	for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1400 		ALLOC_GROW(array, nr + 1, alloc);
1401 		wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1402 		array[nr++] = p;
1403 		p += wlen + 1;
1404 	}
1405 
1406 	git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1407 	ALLOC_ARRAY(result, size + delta_size);
1408 
1409 	for (p = result, i = 0; i < nr; i++) {
1410 		/* Skip any duplicate keys; last one wins */
1411 		while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1412 		       i++;
1413 
1414 		/* Skip "to delete" entry */
1415 		if (!wcschr(array[i], L'='))
1416 			continue;
1417 
1418 		size = wcslen(array[i]) + 1;
1419 		COPY_ARRAY(p, array[i], size);
1420 		p += size;
1421 	}
1422 	*p = L'\0';
1423 
1424 	free(array);
1425 	free(wdeltaenv);
1426 	FreeEnvironmentStringsW(wenv);
1427 	return result;
1428 }
1429 
do_unset_environment_variables(void)1430 static void do_unset_environment_variables(void)
1431 {
1432 	static int done;
1433 	char *p = unset_environment_variables;
1434 
1435 	if (done || !p)
1436 		return;
1437 	done = 1;
1438 
1439 	for (;;) {
1440 		char *comma = strchr(p, ',');
1441 
1442 		if (comma)
1443 			*comma = '\0';
1444 		unsetenv(p);
1445 		if (!comma)
1446 			break;
1447 		p = comma + 1;
1448 	}
1449 }
1450 
1451 struct pinfo_t {
1452 	struct pinfo_t *next;
1453 	pid_t pid;
1454 	HANDLE proc;
1455 };
1456 static struct pinfo_t *pinfo = NULL;
1457 CRITICAL_SECTION pinfo_cs;
1458 
1459 /* Used to match and chomp off path components */
match_last_path_component(const char * path,size_t * len,const char * component)1460 static inline int match_last_path_component(const char *path, size_t *len,
1461 					    const char *component)
1462 {
1463 	size_t component_len = strlen(component);
1464 	if (*len < component_len + 1 ||
1465 	    !is_dir_sep(path[*len - component_len - 1]) ||
1466 	    fspathncmp(path + *len - component_len, component, component_len))
1467 		return 0;
1468 	*len -= component_len + 1;
1469 	/* chomp off repeated dir separators */
1470 	while (*len > 0 && is_dir_sep(path[*len - 1]))
1471 		(*len)--;
1472 	return 1;
1473 }
1474 
is_msys2_sh(const char * cmd)1475 static int is_msys2_sh(const char *cmd)
1476 {
1477 	if (!cmd)
1478 		return 0;
1479 
1480 	if (!strcmp(cmd, "sh")) {
1481 		static int ret = -1;
1482 		char *p;
1483 
1484 		if (ret >= 0)
1485 			return ret;
1486 
1487 		p = path_lookup(cmd, 0);
1488 		if (!p)
1489 			ret = 0;
1490 		else {
1491 			size_t len = strlen(p);
1492 
1493 			ret = match_last_path_component(p, &len, "sh.exe") &&
1494 				match_last_path_component(p, &len, "bin") &&
1495 				match_last_path_component(p, &len, "usr");
1496 			free(p);
1497 		}
1498 		return ret;
1499 	}
1500 
1501 	if (ends_with(cmd, "\\sh.exe")) {
1502 		static char *sh;
1503 
1504 		if (!sh)
1505 			sh = path_lookup("sh", 0);
1506 
1507 		return !fspathcmp(cmd, sh);
1508 	}
1509 
1510 	return 0;
1511 }
1512 
mingw_spawnve_fd(const char * cmd,const char ** argv,char ** deltaenv,const char * dir,int prepend_cmd,int fhin,int fhout,int fherr)1513 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1514 			      const char *dir,
1515 			      int prepend_cmd, int fhin, int fhout, int fherr)
1516 {
1517 	static int restrict_handle_inheritance = -1;
1518 	STARTUPINFOEXW si;
1519 	PROCESS_INFORMATION pi;
1520 	LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1521 	HANDLE stdhandles[3];
1522 	DWORD stdhandles_count = 0;
1523 	SIZE_T size;
1524 	struct strbuf args;
1525 	wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1526 	unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1527 	BOOL ret;
1528 	HANDLE cons;
1529 	const char *(*quote_arg)(const char *arg) =
1530 		is_msys2_sh(cmd ? cmd : *argv) ?
1531 		quote_arg_msys2 : quote_arg_msvc;
1532 	const char *strace_env;
1533 
1534 	/* Make sure to override previous errors, if any */
1535 	errno = 0;
1536 
1537 	if (restrict_handle_inheritance < 0)
1538 		restrict_handle_inheritance = core_restrict_inherited_handles;
1539 	/*
1540 	 * The following code to restrict which handles are inherited seems
1541 	 * to work properly only on Windows 7 and later, so let's disable it
1542 	 * on Windows Vista and 2008.
1543 	 */
1544 	if (restrict_handle_inheritance < 0)
1545 		restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1546 
1547 	do_unset_environment_variables();
1548 
1549 	/* Determine whether or not we are associated to a console */
1550 	cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1551 			FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1552 			FILE_ATTRIBUTE_NORMAL, NULL);
1553 	if (cons == INVALID_HANDLE_VALUE) {
1554 		/* There is no console associated with this process.
1555 		 * Since the child is a console process, Windows
1556 		 * would normally create a console window. But
1557 		 * since we'll be redirecting std streams, we do
1558 		 * not need the console.
1559 		 * It is necessary to use DETACHED_PROCESS
1560 		 * instead of CREATE_NO_WINDOW to make ssh
1561 		 * recognize that it has no console.
1562 		 */
1563 		flags |= DETACHED_PROCESS;
1564 	} else {
1565 		/* There is already a console. If we specified
1566 		 * DETACHED_PROCESS here, too, Windows would
1567 		 * disassociate the child from the console.
1568 		 * The same is true for CREATE_NO_WINDOW.
1569 		 * Go figure!
1570 		 */
1571 		CloseHandle(cons);
1572 	}
1573 	memset(&si, 0, sizeof(si));
1574 	si.StartupInfo.cb = sizeof(si);
1575 	si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1576 	si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1577 	si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1578 
1579 	/* The list of handles cannot contain duplicates */
1580 	if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1581 		stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1582 	if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1583 	    si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1584 		stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1585 	if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1586 	    si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1587 	    si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1588 		stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1589 	if (stdhandles_count)
1590 		si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1591 
1592 	if (*argv && !strcmp(cmd, *argv))
1593 		wcmd[0] = L'\0';
1594 	else if (xutftowcs_path(wcmd, cmd) < 0)
1595 		return -1;
1596 	if (dir && xutftowcs_path(wdir, dir) < 0)
1597 		return -1;
1598 
1599 	/* concatenate argv, quoting args as we go */
1600 	strbuf_init(&args, 0);
1601 	if (prepend_cmd) {
1602 		char *quoted = (char *)quote_arg(cmd);
1603 		strbuf_addstr(&args, quoted);
1604 		if (quoted != cmd)
1605 			free(quoted);
1606 	}
1607 	for (; *argv; argv++) {
1608 		char *quoted = (char *)quote_arg(*argv);
1609 		if (*args.buf)
1610 			strbuf_addch(&args, ' ');
1611 		strbuf_addstr(&args, quoted);
1612 		if (quoted != *argv)
1613 			free(quoted);
1614 	}
1615 
1616 	strace_env = getenv("GIT_STRACE_COMMANDS");
1617 	if (strace_env) {
1618 		char *p = path_lookup("strace.exe", 1);
1619 		if (!p)
1620 			return error("strace not found!");
1621 		if (xutftowcs_path(wcmd, p) < 0) {
1622 			free(p);
1623 			return -1;
1624 		}
1625 		free(p);
1626 		if (!strcmp("1", strace_env) ||
1627 		    !strcasecmp("yes", strace_env) ||
1628 		    !strcasecmp("true", strace_env))
1629 			strbuf_insert(&args, 0, "strace ", 7);
1630 		else {
1631 			const char *quoted = quote_arg(strace_env);
1632 			struct strbuf buf = STRBUF_INIT;
1633 			strbuf_addf(&buf, "strace -o %s ", quoted);
1634 			if (quoted != strace_env)
1635 				free((char *)quoted);
1636 			strbuf_insert(&args, 0, buf.buf, buf.len);
1637 			strbuf_release(&buf);
1638 		}
1639 	}
1640 
1641 	ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1642 	xutftowcs(wargs, args.buf, 2 * args.len + 1);
1643 	strbuf_release(&args);
1644 
1645 	wenvblk = make_environment_block(deltaenv);
1646 
1647 	memset(&pi, 0, sizeof(pi));
1648 	if (restrict_handle_inheritance && stdhandles_count &&
1649 	    (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1650 	     GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1651 	    (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1652 			(HeapAlloc(GetProcessHeap(), 0, size))) &&
1653 	    InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1654 	    UpdateProcThreadAttribute(attr_list, 0,
1655 				      PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1656 				      stdhandles,
1657 				      stdhandles_count * sizeof(HANDLE),
1658 				      NULL, NULL)) {
1659 		si.lpAttributeList = attr_list;
1660 		flags |= EXTENDED_STARTUPINFO_PRESENT;
1661 	}
1662 
1663 	ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1664 			     stdhandles_count ? TRUE : FALSE,
1665 			     flags, wenvblk, dir ? wdir : NULL,
1666 			     &si.StartupInfo, &pi);
1667 
1668 	/*
1669 	 * On Windows 2008 R2, it seems that specifying certain types of handles
1670 	 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1671 	 * error. Rather than playing finicky and fragile games, let's just try
1672 	 * to detect this situation and simply try again without restricting any
1673 	 * handle inheritance. This is still better than failing to create
1674 	 * processes.
1675 	 */
1676 	if (!ret && restrict_handle_inheritance && stdhandles_count) {
1677 		DWORD err = GetLastError();
1678 		struct strbuf buf = STRBUF_INIT;
1679 
1680 		if (err != ERROR_NO_SYSTEM_RESOURCES &&
1681 		    /*
1682 		     * On Windows 7 and earlier, handles on pipes and character
1683 		     * devices are inherited automatically, and cannot be
1684 		     * specified in the thread handle list. Rather than trying
1685 		     * to catch each and every corner case (and running the
1686 		     * chance of *still* forgetting a few), let's just fall
1687 		     * back to creating the process without trying to limit the
1688 		     * handle inheritance.
1689 		     */
1690 		    !(err == ERROR_INVALID_PARAMETER &&
1691 		      GetVersion() >> 16 < 9200) &&
1692 		    !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1693 			DWORD fl = 0;
1694 			int i;
1695 
1696 			setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1697 
1698 			for (i = 0; i < stdhandles_count; i++) {
1699 				HANDLE h = stdhandles[i];
1700 				strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1701 					    "handle info (%d) %lx\n", i, h,
1702 					    GetFileType(h),
1703 					    GetHandleInformation(h, &fl),
1704 					    fl);
1705 			}
1706 			strbuf_addstr(&buf, "\nThis is a bug; please report it "
1707 				      "at\nhttps://github.com/git-for-windows/"
1708 				      "git/issues/new\n\n"
1709 				      "To suppress this warning, please set "
1710 				      "the environment variable\n\n"
1711 				      "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1712 				      "\n");
1713 		}
1714 		restrict_handle_inheritance = 0;
1715 		flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1716 		ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1717 				     TRUE, flags, wenvblk, dir ? wdir : NULL,
1718 				     &si.StartupInfo, &pi);
1719 		if (!ret)
1720 			errno = err_win_to_posix(GetLastError());
1721 		if (ret && buf.len) {
1722 			warning("failed to restrict file handles (%ld)\n\n%s",
1723 				err, buf.buf);
1724 		}
1725 		strbuf_release(&buf);
1726 	} else if (!ret)
1727 		errno = err_win_to_posix(GetLastError());
1728 
1729 	if (si.lpAttributeList)
1730 		DeleteProcThreadAttributeList(si.lpAttributeList);
1731 	if (attr_list)
1732 		HeapFree(GetProcessHeap(), 0, attr_list);
1733 
1734 	free(wenvblk);
1735 	free(wargs);
1736 
1737 	if (!ret)
1738 		return -1;
1739 
1740 	CloseHandle(pi.hThread);
1741 
1742 	/*
1743 	 * The process ID is the human-readable identifier of the process
1744 	 * that we want to present in log and error messages. The handle
1745 	 * is not useful for this purpose. But we cannot close it, either,
1746 	 * because it is not possible to turn a process ID into a process
1747 	 * handle after the process terminated.
1748 	 * Keep the handle in a list for waitpid.
1749 	 */
1750 	EnterCriticalSection(&pinfo_cs);
1751 	{
1752 		struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1753 		info->pid = pi.dwProcessId;
1754 		info->proc = pi.hProcess;
1755 		info->next = pinfo;
1756 		pinfo = info;
1757 	}
1758 	LeaveCriticalSection(&pinfo_cs);
1759 
1760 	return (pid_t)pi.dwProcessId;
1761 }
1762 
mingw_spawnv(const char * cmd,const char ** argv,int prepend_cmd)1763 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1764 {
1765 	return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1766 }
1767 
mingw_spawnvpe(const char * cmd,const char ** argv,char ** deltaenv,const char * dir,int fhin,int fhout,int fherr)1768 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1769 		     const char *dir,
1770 		     int fhin, int fhout, int fherr)
1771 {
1772 	pid_t pid;
1773 	char *prog = path_lookup(cmd, 0);
1774 
1775 	if (!prog) {
1776 		errno = ENOENT;
1777 		pid = -1;
1778 	}
1779 	else {
1780 		const char *interpr = parse_interpreter(prog);
1781 
1782 		if (interpr) {
1783 			const char *argv0 = argv[0];
1784 			char *iprog = path_lookup(interpr, 1);
1785 			argv[0] = prog;
1786 			if (!iprog) {
1787 				errno = ENOENT;
1788 				pid = -1;
1789 			}
1790 			else {
1791 				pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1792 						       fhin, fhout, fherr);
1793 				free(iprog);
1794 			}
1795 			argv[0] = argv0;
1796 		}
1797 		else
1798 			pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1799 					       fhin, fhout, fherr);
1800 		free(prog);
1801 	}
1802 	return pid;
1803 }
1804 
try_shell_exec(const char * cmd,char * const * argv)1805 static int try_shell_exec(const char *cmd, char *const *argv)
1806 {
1807 	const char *interpr = parse_interpreter(cmd);
1808 	char *prog;
1809 	int pid = 0;
1810 
1811 	if (!interpr)
1812 		return 0;
1813 	prog = path_lookup(interpr, 1);
1814 	if (prog) {
1815 		int exec_id;
1816 		int argc = 0;
1817 #ifndef _MSC_VER
1818 		const
1819 #endif
1820 		char **argv2;
1821 		while (argv[argc]) argc++;
1822 		ALLOC_ARRAY(argv2, argc + 1);
1823 		argv2[0] = (char *)cmd;	/* full path to the script file */
1824 		COPY_ARRAY(&argv2[1], &argv[1], argc);
1825 		exec_id = trace2_exec(prog, argv2);
1826 		pid = mingw_spawnv(prog, argv2, 1);
1827 		if (pid >= 0) {
1828 			int status;
1829 			if (waitpid(pid, &status, 0) < 0)
1830 				status = 255;
1831 			trace2_exec_result(exec_id, status);
1832 			exit(status);
1833 		}
1834 		trace2_exec_result(exec_id, -1);
1835 		pid = 1;	/* indicate that we tried but failed */
1836 		free(prog);
1837 		free(argv2);
1838 	}
1839 	return pid;
1840 }
1841 
mingw_execv(const char * cmd,char * const * argv)1842 int mingw_execv(const char *cmd, char *const *argv)
1843 {
1844 	/* check if git_command is a shell script */
1845 	if (!try_shell_exec(cmd, argv)) {
1846 		int pid, status;
1847 		int exec_id;
1848 
1849 		exec_id = trace2_exec(cmd, (const char **)argv);
1850 		pid = mingw_spawnv(cmd, (const char **)argv, 0);
1851 		if (pid < 0) {
1852 			trace2_exec_result(exec_id, -1);
1853 			return -1;
1854 		}
1855 		if (waitpid(pid, &status, 0) < 0)
1856 			status = 255;
1857 		trace2_exec_result(exec_id, status);
1858 		exit(status);
1859 	}
1860 	return -1;
1861 }
1862 
mingw_execvp(const char * cmd,char * const * argv)1863 int mingw_execvp(const char *cmd, char *const *argv)
1864 {
1865 	char *prog = path_lookup(cmd, 0);
1866 
1867 	if (prog) {
1868 		mingw_execv(prog, argv);
1869 		free(prog);
1870 	} else
1871 		errno = ENOENT;
1872 
1873 	return -1;
1874 }
1875 
mingw_kill(pid_t pid,int sig)1876 int mingw_kill(pid_t pid, int sig)
1877 {
1878 	if (pid > 0 && sig == SIGTERM) {
1879 		HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1880 
1881 		if (TerminateProcess(h, -1)) {
1882 			CloseHandle(h);
1883 			return 0;
1884 		}
1885 
1886 		errno = err_win_to_posix(GetLastError());
1887 		CloseHandle(h);
1888 		return -1;
1889 	} else if (pid > 0 && sig == 0) {
1890 		HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1891 		if (h) {
1892 			CloseHandle(h);
1893 			return 0;
1894 		}
1895 	}
1896 
1897 	errno = EINVAL;
1898 	return -1;
1899 }
1900 
1901 /*
1902  * UTF-8 versions of getenv(), putenv() and unsetenv().
1903  * Internally, they use the CRT's stock UNICODE routines
1904  * to avoid data loss.
1905  */
mingw_getenv(const char * name)1906 char *mingw_getenv(const char *name)
1907 {
1908 #define GETENV_MAX_RETAIN 64
1909 	static char *values[GETENV_MAX_RETAIN];
1910 	static int value_counter;
1911 	int len_key, len_value;
1912 	wchar_t *w_key;
1913 	char *value;
1914 	wchar_t w_value[32768];
1915 
1916 	if (!name || !*name)
1917 		return NULL;
1918 
1919 	len_key = strlen(name) + 1;
1920 	/* We cannot use xcalloc() here because that uses getenv() itself */
1921 	w_key = calloc(len_key, sizeof(wchar_t));
1922 	if (!w_key)
1923 		die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1924 	xutftowcs(w_key, name, len_key);
1925 	/* GetEnvironmentVariableW() only sets the last error upon failure */
1926 	SetLastError(ERROR_SUCCESS);
1927 	len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1928 	if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1929 		free(w_key);
1930 		return NULL;
1931 	}
1932 	free(w_key);
1933 
1934 	len_value = len_value * 3 + 1;
1935 	/* We cannot use xcalloc() here because that uses getenv() itself */
1936 	value = calloc(len_value, sizeof(char));
1937 	if (!value)
1938 		die("Out of memory, (tried to allocate %u bytes)", len_value);
1939 	xwcstoutf(value, w_value, len_value);
1940 
1941 	/*
1942 	 * We return `value` which is an allocated value and the caller is NOT
1943 	 * expecting to have to free it, so we keep a round-robin array,
1944 	 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1945 	 */
1946 	free(values[value_counter]);
1947 	values[value_counter++] = value;
1948 	if (value_counter >= ARRAY_SIZE(values))
1949 		value_counter = 0;
1950 
1951 	return value;
1952 }
1953 
mingw_putenv(const char * namevalue)1954 int mingw_putenv(const char *namevalue)
1955 {
1956 	int size;
1957 	wchar_t *wide, *equal;
1958 	BOOL result;
1959 
1960 	if (!namevalue || !*namevalue)
1961 		return 0;
1962 
1963 	size = strlen(namevalue) * 2 + 1;
1964 	wide = calloc(size, sizeof(wchar_t));
1965 	if (!wide)
1966 		die("Out of memory, (tried to allocate %u wchar_t's)", size);
1967 	xutftowcs(wide, namevalue, size);
1968 	equal = wcschr(wide, L'=');
1969 	if (!equal)
1970 		result = SetEnvironmentVariableW(wide, NULL);
1971 	else {
1972 		*equal = L'\0';
1973 		result = SetEnvironmentVariableW(wide, equal + 1);
1974 	}
1975 	free(wide);
1976 
1977 	if (!result)
1978 		errno = err_win_to_posix(GetLastError());
1979 
1980 	return result ? 0 : -1;
1981 }
1982 
ensure_socket_initialization(void)1983 static void ensure_socket_initialization(void)
1984 {
1985 	WSADATA wsa;
1986 	static int initialized = 0;
1987 
1988 	if (initialized)
1989 		return;
1990 
1991 	if (WSAStartup(MAKEWORD(2,2), &wsa))
1992 		die("unable to initialize winsock subsystem, error %d",
1993 			WSAGetLastError());
1994 
1995 	atexit((void(*)(void)) WSACleanup);
1996 	initialized = 1;
1997 }
1998 
1999 #undef gethostname
mingw_gethostname(char * name,int namelen)2000 int mingw_gethostname(char *name, int namelen)
2001 {
2002     ensure_socket_initialization();
2003     return gethostname(name, namelen);
2004 }
2005 
2006 #undef gethostbyname
mingw_gethostbyname(const char * host)2007 struct hostent *mingw_gethostbyname(const char *host)
2008 {
2009 	ensure_socket_initialization();
2010 	return gethostbyname(host);
2011 }
2012 
2013 #undef getaddrinfo
mingw_getaddrinfo(const char * node,const char * service,const struct addrinfo * hints,struct addrinfo ** res)2014 int mingw_getaddrinfo(const char *node, const char *service,
2015 		      const struct addrinfo *hints, struct addrinfo **res)
2016 {
2017 	ensure_socket_initialization();
2018 	return getaddrinfo(node, service, hints, res);
2019 }
2020 
mingw_socket(int domain,int type,int protocol)2021 int mingw_socket(int domain, int type, int protocol)
2022 {
2023 	int sockfd;
2024 	SOCKET s;
2025 
2026 	ensure_socket_initialization();
2027 	s = WSASocket(domain, type, protocol, NULL, 0, 0);
2028 	if (s == INVALID_SOCKET) {
2029 		/*
2030 		 * WSAGetLastError() values are regular BSD error codes
2031 		 * biased by WSABASEERR.
2032 		 * However, strerror() does not know about networking
2033 		 * specific errors, which are values beginning at 38 or so.
2034 		 * Therefore, we choose to leave the biased error code
2035 		 * in errno so that _if_ someone looks up the code somewhere,
2036 		 * then it is at least the number that are usually listed.
2037 		 */
2038 		errno = WSAGetLastError();
2039 		return -1;
2040 	}
2041 	/* convert into a file descriptor */
2042 	if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2043 		closesocket(s);
2044 		return error("unable to make a socket file descriptor: %s",
2045 			strerror(errno));
2046 	}
2047 	return sockfd;
2048 }
2049 
2050 #undef connect
mingw_connect(int sockfd,struct sockaddr * sa,size_t sz)2051 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2052 {
2053 	SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2054 	return connect(s, sa, sz);
2055 }
2056 
2057 #undef bind
mingw_bind(int sockfd,struct sockaddr * sa,size_t sz)2058 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2059 {
2060 	SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2061 	return bind(s, sa, sz);
2062 }
2063 
2064 #undef setsockopt
mingw_setsockopt(int sockfd,int lvl,int optname,void * optval,int optlen)2065 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2066 {
2067 	SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2068 	return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2069 }
2070 
2071 #undef shutdown
mingw_shutdown(int sockfd,int how)2072 int mingw_shutdown(int sockfd, int how)
2073 {
2074 	SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2075 	return shutdown(s, how);
2076 }
2077 
2078 #undef listen
mingw_listen(int sockfd,int backlog)2079 int mingw_listen(int sockfd, int backlog)
2080 {
2081 	SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2082 	return listen(s, backlog);
2083 }
2084 
2085 #undef accept
mingw_accept(int sockfd1,struct sockaddr * sa,socklen_t * sz)2086 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2087 {
2088 	int sockfd2;
2089 
2090 	SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2091 	SOCKET s2 = accept(s1, sa, sz);
2092 
2093 	/* convert into a file descriptor */
2094 	if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2095 		int err = errno;
2096 		closesocket(s2);
2097 		return error("unable to make a socket file descriptor: %s",
2098 			strerror(err));
2099 	}
2100 	return sockfd2;
2101 }
2102 
2103 #undef rename
mingw_rename(const char * pold,const char * pnew)2104 int mingw_rename(const char *pold, const char *pnew)
2105 {
2106 	DWORD attrs, gle;
2107 	int tries = 0;
2108 	wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2109 	if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2110 		return -1;
2111 
2112 	/*
2113 	 * Try native rename() first to get errno right.
2114 	 * It is based on MoveFile(), which cannot overwrite existing files.
2115 	 */
2116 	if (!_wrename(wpold, wpnew))
2117 		return 0;
2118 	if (errno != EEXIST)
2119 		return -1;
2120 repeat:
2121 	if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2122 		return 0;
2123 	/* TODO: translate more errors */
2124 	gle = GetLastError();
2125 	if (gle == ERROR_ACCESS_DENIED &&
2126 	    (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2127 		if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2128 			DWORD attrsold = GetFileAttributesW(wpold);
2129 			if (attrsold == INVALID_FILE_ATTRIBUTES ||
2130 			    !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2131 				errno = EISDIR;
2132 			else if (!_wrmdir(wpnew))
2133 				goto repeat;
2134 			return -1;
2135 		}
2136 		if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2137 		    SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2138 			if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2139 				return 0;
2140 			gle = GetLastError();
2141 			/* revert file attributes on failure */
2142 			SetFileAttributesW(wpnew, attrs);
2143 		}
2144 	}
2145 	if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2146 		/*
2147 		 * We assume that some other process had the source or
2148 		 * destination file open at the wrong moment and retry.
2149 		 * In order to give the other process a higher chance to
2150 		 * complete its operation, we give up our time slice now.
2151 		 * If we have to retry again, we do sleep a bit.
2152 		 */
2153 		Sleep(delay[tries]);
2154 		tries++;
2155 		goto repeat;
2156 	}
2157 	if (gle == ERROR_ACCESS_DENIED &&
2158 	       ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2159 		       "Should I try again?", pold, pnew))
2160 		goto repeat;
2161 
2162 	errno = EACCES;
2163 	return -1;
2164 }
2165 
2166 /*
2167  * Note that this doesn't return the actual pagesize, but
2168  * the allocation granularity. If future Windows specific git code
2169  * needs the real getpagesize function, we need to find another solution.
2170  */
mingw_getpagesize(void)2171 int mingw_getpagesize(void)
2172 {
2173 	SYSTEM_INFO si;
2174 	GetSystemInfo(&si);
2175 	return si.dwAllocationGranularity;
2176 }
2177 
2178 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2179 enum EXTENDED_NAME_FORMAT {
2180 	NameDisplay = 3,
2181 	NameUserPrincipal = 8
2182 };
2183 
get_extended_user_info(enum EXTENDED_NAME_FORMAT type)2184 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2185 {
2186 	DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2187 		enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2188 	static wchar_t wbuffer[1024];
2189 	DWORD len;
2190 
2191 	if (!INIT_PROC_ADDR(GetUserNameExW))
2192 		return NULL;
2193 
2194 	len = ARRAY_SIZE(wbuffer);
2195 	if (GetUserNameExW(type, wbuffer, &len)) {
2196 		char *converted = xmalloc((len *= 3));
2197 		if (xwcstoutf(converted, wbuffer, len) >= 0)
2198 			return converted;
2199 		free(converted);
2200 	}
2201 
2202 	return NULL;
2203 }
2204 
mingw_query_user_email(void)2205 char *mingw_query_user_email(void)
2206 {
2207 	return get_extended_user_info(NameUserPrincipal);
2208 }
2209 
getpwuid(int uid)2210 struct passwd *getpwuid(int uid)
2211 {
2212 	static unsigned initialized;
2213 	static char user_name[100];
2214 	static struct passwd *p;
2215 	wchar_t buf[100];
2216 	DWORD len;
2217 
2218 	if (initialized)
2219 		return p;
2220 
2221 	len = ARRAY_SIZE(buf);
2222 	if (!GetUserNameW(buf, &len)) {
2223 		initialized = 1;
2224 		return NULL;
2225 	}
2226 
2227 	if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2228 		initialized = 1;
2229 		return NULL;
2230 	}
2231 
2232 	p = xmalloc(sizeof(*p));
2233 	p->pw_name = user_name;
2234 	p->pw_gecos = get_extended_user_info(NameDisplay);
2235 	if (!p->pw_gecos)
2236 		p->pw_gecos = "unknown";
2237 	p->pw_dir = NULL;
2238 
2239 	initialized = 1;
2240 	return p;
2241 }
2242 
2243 static HANDLE timer_event;
2244 static HANDLE timer_thread;
2245 static int timer_interval;
2246 static int one_shot;
2247 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2248 
2249 /* The timer works like this:
2250  * The thread, ticktack(), is a trivial routine that most of the time
2251  * only waits to receive the signal to terminate. The main thread tells
2252  * the thread to terminate by setting the timer_event to the signalled
2253  * state.
2254  * But ticktack() interrupts the wait state after the timer's interval
2255  * length to call the signal handler.
2256  */
2257 
ticktack(void * dummy)2258 static unsigned __stdcall ticktack(void *dummy)
2259 {
2260 	while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2261 		mingw_raise(SIGALRM);
2262 		if (one_shot)
2263 			break;
2264 	}
2265 	return 0;
2266 }
2267 
start_timer_thread(void)2268 static int start_timer_thread(void)
2269 {
2270 	timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2271 	if (timer_event) {
2272 		timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2273 		if (!timer_thread )
2274 			return errno = ENOMEM,
2275 				error("cannot start timer thread");
2276 	} else
2277 		return errno = ENOMEM,
2278 			error("cannot allocate resources for timer");
2279 	return 0;
2280 }
2281 
stop_timer_thread(void)2282 static void stop_timer_thread(void)
2283 {
2284 	if (timer_event)
2285 		SetEvent(timer_event);	/* tell thread to terminate */
2286 	if (timer_thread) {
2287 		int rc = WaitForSingleObject(timer_thread, 10000);
2288 		if (rc == WAIT_TIMEOUT)
2289 			error("timer thread did not terminate timely");
2290 		else if (rc != WAIT_OBJECT_0)
2291 			error("waiting for timer thread failed: %lu",
2292 			      GetLastError());
2293 		CloseHandle(timer_thread);
2294 	}
2295 	if (timer_event)
2296 		CloseHandle(timer_event);
2297 	timer_event = NULL;
2298 	timer_thread = NULL;
2299 }
2300 
is_timeval_eq(const struct timeval * i1,const struct timeval * i2)2301 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2302 {
2303 	return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2304 }
2305 
setitimer(int type,struct itimerval * in,struct itimerval * out)2306 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2307 {
2308 	static const struct timeval zero;
2309 	static int atexit_done;
2310 
2311 	if (out != NULL)
2312 		return errno = EINVAL,
2313 			error("setitimer param 3 != NULL not implemented");
2314 	if (!is_timeval_eq(&in->it_interval, &zero) &&
2315 	    !is_timeval_eq(&in->it_interval, &in->it_value))
2316 		return errno = EINVAL,
2317 			error("setitimer: it_interval must be zero or eq it_value");
2318 
2319 	if (timer_thread)
2320 		stop_timer_thread();
2321 
2322 	if (is_timeval_eq(&in->it_value, &zero) &&
2323 	    is_timeval_eq(&in->it_interval, &zero))
2324 		return 0;
2325 
2326 	timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2327 	one_shot = is_timeval_eq(&in->it_interval, &zero);
2328 	if (!atexit_done) {
2329 		atexit(stop_timer_thread);
2330 		atexit_done = 1;
2331 	}
2332 	return start_timer_thread();
2333 }
2334 
sigaction(int sig,struct sigaction * in,struct sigaction * out)2335 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2336 {
2337 	if (sig != SIGALRM)
2338 		return errno = EINVAL,
2339 			error("sigaction only implemented for SIGALRM");
2340 	if (out != NULL)
2341 		return errno = EINVAL,
2342 			error("sigaction: param 3 != NULL not implemented");
2343 
2344 	timer_fn = in->sa_handler;
2345 	return 0;
2346 }
2347 
2348 #undef signal
mingw_signal(int sig,sig_handler_t handler)2349 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2350 {
2351 	sig_handler_t old;
2352 
2353 	switch (sig) {
2354 	case SIGALRM:
2355 		old = timer_fn;
2356 		timer_fn = handler;
2357 		break;
2358 
2359 	case SIGINT:
2360 		old = sigint_fn;
2361 		sigint_fn = handler;
2362 		break;
2363 
2364 	default:
2365 		return signal(sig, handler);
2366 	}
2367 
2368 	return old;
2369 }
2370 
2371 #undef raise
mingw_raise(int sig)2372 int mingw_raise(int sig)
2373 {
2374 	switch (sig) {
2375 	case SIGALRM:
2376 		if (timer_fn == SIG_DFL) {
2377 			if (isatty(STDERR_FILENO))
2378 				fputs("Alarm clock\n", stderr);
2379 			exit(128 + SIGALRM);
2380 		} else if (timer_fn != SIG_IGN)
2381 			timer_fn(SIGALRM);
2382 		return 0;
2383 
2384 	case SIGINT:
2385 		if (sigint_fn == SIG_DFL)
2386 			exit(128 + SIGINT);
2387 		else if (sigint_fn != SIG_IGN)
2388 			sigint_fn(SIGINT);
2389 		return 0;
2390 
2391 #if defined(_MSC_VER)
2392 	case SIGILL:
2393 	case SIGFPE:
2394 	case SIGSEGV:
2395 	case SIGTERM:
2396 	case SIGBREAK:
2397 	case SIGABRT:
2398 	case SIGABRT_COMPAT:
2399 		/*
2400 		 * The <signal.h> header in the MS C Runtime defines 8 signals
2401 		 * as being supported on the platform. Anything else causes an
2402 		 * "Invalid signal or error" (which in DEBUG builds causes the
2403 		 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2404 		 * already know will fail.
2405 		 */
2406 		return raise(sig);
2407 	default:
2408 		errno = EINVAL;
2409 		return -1;
2410 
2411 #else
2412 
2413 	default:
2414 		return raise(sig);
2415 
2416 #endif
2417 
2418 	}
2419 }
2420 
link(const char * oldpath,const char * newpath)2421 int link(const char *oldpath, const char *newpath)
2422 {
2423 	wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2424 	if (xutftowcs_path(woldpath, oldpath) < 0 ||
2425 		xutftowcs_path(wnewpath, newpath) < 0)
2426 		return -1;
2427 
2428 	if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2429 		errno = err_win_to_posix(GetLastError());
2430 		return -1;
2431 	}
2432 	return 0;
2433 }
2434 
waitpid(pid_t pid,int * status,int options)2435 pid_t waitpid(pid_t pid, int *status, int options)
2436 {
2437 	HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2438 	    FALSE, pid);
2439 	if (!h) {
2440 		errno = ECHILD;
2441 		return -1;
2442 	}
2443 
2444 	if (pid > 0 && options & WNOHANG) {
2445 		if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2446 			CloseHandle(h);
2447 			return 0;
2448 		}
2449 		options &= ~WNOHANG;
2450 	}
2451 
2452 	if (options == 0) {
2453 		struct pinfo_t **ppinfo;
2454 		if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2455 			CloseHandle(h);
2456 			return 0;
2457 		}
2458 
2459 		if (status)
2460 			GetExitCodeProcess(h, (LPDWORD)status);
2461 
2462 		EnterCriticalSection(&pinfo_cs);
2463 
2464 		ppinfo = &pinfo;
2465 		while (*ppinfo) {
2466 			struct pinfo_t *info = *ppinfo;
2467 			if (info->pid == pid) {
2468 				CloseHandle(info->proc);
2469 				*ppinfo = info->next;
2470 				free(info);
2471 				break;
2472 			}
2473 			ppinfo = &info->next;
2474 		}
2475 
2476 		LeaveCriticalSection(&pinfo_cs);
2477 
2478 		CloseHandle(h);
2479 		return pid;
2480 	}
2481 	CloseHandle(h);
2482 
2483 	errno = EINVAL;
2484 	return -1;
2485 }
2486 
xutftowcsn(wchar_t * wcs,const char * utfs,size_t wcslen,int utflen)2487 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2488 {
2489 	int upos = 0, wpos = 0;
2490 	const unsigned char *utf = (const unsigned char*) utfs;
2491 	if (!utf || !wcs || wcslen < 1) {
2492 		errno = EINVAL;
2493 		return -1;
2494 	}
2495 	/* reserve space for \0 */
2496 	wcslen--;
2497 	if (utflen < 0)
2498 		utflen = INT_MAX;
2499 
2500 	while (upos < utflen) {
2501 		int c = utf[upos++] & 0xff;
2502 		if (utflen == INT_MAX && c == 0)
2503 			break;
2504 
2505 		if (wpos >= wcslen) {
2506 			wcs[wpos] = 0;
2507 			errno = ERANGE;
2508 			return -1;
2509 		}
2510 
2511 		if (c < 0x80) {
2512 			/* ASCII */
2513 			wcs[wpos++] = c;
2514 		} else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2515 				(utf[upos] & 0xc0) == 0x80) {
2516 			/* 2-byte utf-8 */
2517 			c = ((c & 0x1f) << 6);
2518 			c |= (utf[upos++] & 0x3f);
2519 			wcs[wpos++] = c;
2520 		} else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2521 				!(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2522 				(utf[upos] & 0xc0) == 0x80 &&
2523 				(utf[upos + 1] & 0xc0) == 0x80) {
2524 			/* 3-byte utf-8 */
2525 			c = ((c & 0x0f) << 12);
2526 			c |= ((utf[upos++] & 0x3f) << 6);
2527 			c |= (utf[upos++] & 0x3f);
2528 			wcs[wpos++] = c;
2529 		} else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2530 				wpos + 1 < wcslen &&
2531 				!(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2532 				!(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2533 				(utf[upos] & 0xc0) == 0x80 &&
2534 				(utf[upos + 1] & 0xc0) == 0x80 &&
2535 				(utf[upos + 2] & 0xc0) == 0x80) {
2536 			/* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2537 			c = ((c & 0x07) << 18);
2538 			c |= ((utf[upos++] & 0x3f) << 12);
2539 			c |= ((utf[upos++] & 0x3f) << 6);
2540 			c |= (utf[upos++] & 0x3f);
2541 			c -= 0x10000;
2542 			wcs[wpos++] = 0xd800 | (c >> 10);
2543 			wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2544 		} else if (c >= 0xa0) {
2545 			/* invalid utf-8 byte, printable unicode char: convert 1:1 */
2546 			wcs[wpos++] = c;
2547 		} else {
2548 			/* invalid utf-8 byte, non-printable unicode: convert to hex */
2549 			static const char *hex = "0123456789abcdef";
2550 			wcs[wpos++] = hex[c >> 4];
2551 			if (wpos < wcslen)
2552 				wcs[wpos++] = hex[c & 0x0f];
2553 		}
2554 	}
2555 	wcs[wpos] = 0;
2556 	return wpos;
2557 }
2558 
xwcstoutf(char * utf,const wchar_t * wcs,size_t utflen)2559 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2560 {
2561 	if (!wcs || !utf || utflen < 1) {
2562 		errno = EINVAL;
2563 		return -1;
2564 	}
2565 	utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2566 	if (utflen)
2567 		return utflen - 1;
2568 	errno = ERANGE;
2569 	return -1;
2570 }
2571 
setup_windows_environment(void)2572 static void setup_windows_environment(void)
2573 {
2574 	char *tmp = getenv("TMPDIR");
2575 
2576 	/* on Windows it is TMP and TEMP */
2577 	if (!tmp) {
2578 		if (!(tmp = getenv("TMP")))
2579 			tmp = getenv("TEMP");
2580 		if (tmp) {
2581 			setenv("TMPDIR", tmp, 1);
2582 			tmp = getenv("TMPDIR");
2583 		}
2584 	}
2585 
2586 	if (tmp) {
2587 		/*
2588 		 * Convert all dir separators to forward slashes,
2589 		 * to help shell commands called from the Git
2590 		 * executable (by not mistaking the dir separators
2591 		 * for escape characters).
2592 		 */
2593 		convert_slashes(tmp);
2594 	}
2595 
2596 	/* simulate TERM to enable auto-color (see color.c) */
2597 	if (!getenv("TERM"))
2598 		setenv("TERM", "cygwin", 1);
2599 
2600 	/* calculate HOME if not set */
2601 	if (!getenv("HOME")) {
2602 		/*
2603 		 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2604 		 * location, thus also check if the path exists (i.e. is not
2605 		 * disconnected)
2606 		 */
2607 		if ((tmp = getenv("HOMEDRIVE"))) {
2608 			struct strbuf buf = STRBUF_INIT;
2609 			strbuf_addstr(&buf, tmp);
2610 			if ((tmp = getenv("HOMEPATH"))) {
2611 				strbuf_addstr(&buf, tmp);
2612 				if (is_directory(buf.buf))
2613 					setenv("HOME", buf.buf, 1);
2614 				else
2615 					tmp = NULL; /* use $USERPROFILE */
2616 			}
2617 			strbuf_release(&buf);
2618 		}
2619 		/* use $USERPROFILE if the home share is not available */
2620 		if (!tmp && (tmp = getenv("USERPROFILE")))
2621 			setenv("HOME", tmp, 1);
2622 	}
2623 }
2624 
is_valid_win32_path(const char * path,int allow_literal_nul)2625 int is_valid_win32_path(const char *path, int allow_literal_nul)
2626 {
2627 	const char *p = path;
2628 	int preceding_space_or_period = 0, i = 0, periods = 0;
2629 
2630 	if (!protect_ntfs)
2631 		return 1;
2632 
2633 	skip_dos_drive_prefix((char **)&path);
2634 	goto segment_start;
2635 
2636 	for (;;) {
2637 		char c = *(path++);
2638 		switch (c) {
2639 		case '\0':
2640 		case '/': case '\\':
2641 			/* cannot end in ` ` or `.`, except for `.` and `..` */
2642 			if (preceding_space_or_period &&
2643 			    (i != periods || periods > 2))
2644 				return 0;
2645 			if (!c)
2646 				return 1;
2647 
2648 			i = periods = preceding_space_or_period = 0;
2649 
2650 segment_start:
2651 			switch (*path) {
2652 			case 'a': case 'A': /* AUX */
2653 				if (((c = path[++i]) != 'u' && c != 'U') ||
2654 				    ((c = path[++i]) != 'x' && c != 'X')) {
2655 not_a_reserved_name:
2656 					path += i;
2657 					continue;
2658 				}
2659 				break;
2660 			case 'c': case 'C':
2661 				/* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2662 				if ((c = path[++i]) != 'o' && c != 'O')
2663 					goto not_a_reserved_name;
2664 				c = path[++i];
2665 				if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2666 					c = path[++i];
2667 					if (c < '1' || c > '9')
2668 						goto not_a_reserved_name;
2669 				} else if (c == 'n' || c == 'N') { /* CON */
2670 					c = path[i + 1];
2671 					if ((c == 'i' || c == 'I') &&
2672 					    ((c = path[i + 2]) == 'n' ||
2673 					     c == 'N') &&
2674 					    path[i + 3] == '$')
2675 						i += 3; /* CONIN$ */
2676 					else if ((c == 'o' || c == 'O') &&
2677 						 ((c = path[i + 2]) == 'u' ||
2678 						  c == 'U') &&
2679 						 ((c = path[i + 3]) == 't' ||
2680 						  c == 'T') &&
2681 						 path[i + 4] == '$')
2682 						i += 4; /* CONOUT$ */
2683 				} else
2684 					goto not_a_reserved_name;
2685 				break;
2686 			case 'l': case 'L': /* LPT<N> */
2687 				if (((c = path[++i]) != 'p' && c != 'P') ||
2688 				    ((c = path[++i]) != 't' && c != 'T') ||
2689 				    !isdigit(path[++i]))
2690 					goto not_a_reserved_name;
2691 				break;
2692 			case 'n': case 'N': /* NUL */
2693 				if (((c = path[++i]) != 'u' && c != 'U') ||
2694 				    ((c = path[++i]) != 'l' && c != 'L') ||
2695 				    (allow_literal_nul &&
2696 				     !path[i + 1] && p == path))
2697 					goto not_a_reserved_name;
2698 				break;
2699 			case 'p': case 'P': /* PRN */
2700 				if (((c = path[++i]) != 'r' && c != 'R') ||
2701 				    ((c = path[++i]) != 'n' && c != 'N'))
2702 					goto not_a_reserved_name;
2703 				break;
2704 			default:
2705 				continue;
2706 			}
2707 
2708 			/*
2709 			 * So far, this looks like a reserved name. Let's see
2710 			 * whether it actually is one: trailing spaces, a file
2711 			 * extension, or an NTFS Alternate Data Stream do not
2712 			 * matter, the name is still reserved if any of those
2713 			 * follow immediately after the actual name.
2714 			 */
2715 			i++;
2716 			if (path[i] == ' ') {
2717 				preceding_space_or_period = 1;
2718 				while (path[++i] == ' ')
2719 					; /* skip all spaces */
2720 			}
2721 
2722 			c = path[i];
2723 			if (c && c != '.' && c != ':' && c != '/' && c != '\\')
2724 				goto not_a_reserved_name;
2725 
2726 			/* contains reserved name */
2727 			return 0;
2728 		case '.':
2729 			periods++;
2730 			/* fallthru */
2731 		case ' ':
2732 			preceding_space_or_period = 1;
2733 			i++;
2734 			continue;
2735 		case ':': /* DOS drive prefix was already skipped */
2736 		case '<': case '>': case '"': case '|': case '?': case '*':
2737 			/* illegal character */
2738 			return 0;
2739 		default:
2740 			if (c > '\0' && c < '\x20')
2741 				/* illegal character */
2742 				return 0;
2743 		}
2744 		preceding_space_or_period = 0;
2745 		i++;
2746 	}
2747 }
2748 
2749 #if !defined(_MSC_VER)
2750 /*
2751  * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2752  * mingw startup code, see init.c in mingw runtime).
2753  */
2754 int _CRT_glob = 0;
2755 #endif
2756 
die_startup(void)2757 static NORETURN void die_startup(void)
2758 {
2759 	fputs("fatal: not enough memory for initialization", stderr);
2760 	exit(128);
2761 }
2762 
malloc_startup(size_t size)2763 static void *malloc_startup(size_t size)
2764 {
2765 	void *result = malloc(size);
2766 	if (!result)
2767 		die_startup();
2768 	return result;
2769 }
2770 
wcstoutfdup_startup(char * buffer,const wchar_t * wcs,size_t len)2771 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2772 {
2773 	len = xwcstoutf(buffer, wcs, len) + 1;
2774 	return memcpy(malloc_startup(len), buffer, len);
2775 }
2776 
maybe_redirect_std_handle(const wchar_t * key,DWORD std_id,int fd,DWORD desired_access,DWORD flags)2777 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2778 				      DWORD desired_access, DWORD flags)
2779 {
2780 	DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2781 	wchar_t buf[MAX_PATH];
2782 	DWORD max = ARRAY_SIZE(buf);
2783 	HANDLE handle;
2784 	DWORD ret = GetEnvironmentVariableW(key, buf, max);
2785 
2786 	if (!ret || ret >= max)
2787 		return;
2788 
2789 	/* make sure this does not leak into child processes */
2790 	SetEnvironmentVariableW(key, NULL);
2791 	if (!wcscmp(buf, L"off")) {
2792 		close(fd);
2793 		handle = GetStdHandle(std_id);
2794 		if (handle != INVALID_HANDLE_VALUE)
2795 			CloseHandle(handle);
2796 		return;
2797 	}
2798 	if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2799 		handle = GetStdHandle(STD_OUTPUT_HANDLE);
2800 		if (handle == INVALID_HANDLE_VALUE) {
2801 			close(fd);
2802 			handle = GetStdHandle(std_id);
2803 			if (handle != INVALID_HANDLE_VALUE)
2804 				CloseHandle(handle);
2805 		} else {
2806 			int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2807 			SetStdHandle(std_id, handle);
2808 			dup2(new_fd, fd);
2809 			/* do *not* close the new_fd: that would close stdout */
2810 		}
2811 		return;
2812 	}
2813 	handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2814 			     flags, NULL);
2815 	if (handle != INVALID_HANDLE_VALUE) {
2816 		int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2817 		SetStdHandle(std_id, handle);
2818 		dup2(new_fd, fd);
2819 		close(new_fd);
2820 	}
2821 }
2822 
maybe_redirect_std_handles(void)2823 static void maybe_redirect_std_handles(void)
2824 {
2825 	maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2826 				  GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2827 	maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2828 				  GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2829 	maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2830 				  GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2831 }
2832 
2833 #ifdef _MSC_VER
2834 #ifdef _DEBUG
2835 #include <crtdbg.h>
2836 #endif
2837 #endif
2838 
2839 /*
2840  * We implement wmain() and compile with -municode, which would
2841  * normally ignore main(), but we call the latter from the former
2842  * so that we can handle non-ASCII command-line parameters
2843  * appropriately.
2844  *
2845  * To be more compatible with the core git code, we convert
2846  * argv into UTF8 and pass them directly to main().
2847  */
wmain(int argc,const wchar_t ** wargv)2848 int wmain(int argc, const wchar_t **wargv)
2849 {
2850 	int i, maxlen, exit_status;
2851 	char *buffer, **save;
2852 	const char **argv;
2853 
2854 	trace2_initialize_clock();
2855 
2856 #ifdef _MSC_VER
2857 #ifdef _DEBUG
2858 	_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2859 #endif
2860 
2861 #ifdef USE_MSVC_CRTDBG
2862 	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2863 #endif
2864 #endif
2865 
2866 	maybe_redirect_std_handles();
2867 
2868 	/* determine size of argv and environ conversion buffer */
2869 	maxlen = wcslen(wargv[0]);
2870 	for (i = 1; i < argc; i++)
2871 		maxlen = max(maxlen, wcslen(wargv[i]));
2872 
2873 	/* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2874 	maxlen = 3 * maxlen + 1;
2875 	buffer = malloc_startup(maxlen);
2876 
2877 	/*
2878 	 * Create a UTF-8 version of w_argv. Also create a "save" copy
2879 	 * to remember all the string pointers because parse_options()
2880 	 * will remove claimed items from the argv that we pass down.
2881 	 */
2882 	ALLOC_ARRAY(argv, argc + 1);
2883 	ALLOC_ARRAY(save, argc + 1);
2884 	for (i = 0; i < argc; i++)
2885 		argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2886 	argv[i] = save[i] = NULL;
2887 	free(buffer);
2888 
2889 	/* fix Windows specific environment settings */
2890 	setup_windows_environment();
2891 
2892 	unset_environment_variables = xstrdup("PERL5LIB");
2893 
2894 	/* initialize critical section for waitpid pinfo_t list */
2895 	InitializeCriticalSection(&pinfo_cs);
2896 
2897 	/* set up default file mode and file modes for stdin/out/err */
2898 	_fmode = _O_BINARY;
2899 	_setmode(_fileno(stdin), _O_BINARY);
2900 	_setmode(_fileno(stdout), _O_BINARY);
2901 	_setmode(_fileno(stderr), _O_BINARY);
2902 
2903 	/* initialize Unicode console */
2904 	winansi_init();
2905 
2906 	/* invoke the real main() using our utf8 version of argv. */
2907 	exit_status = main(argc, argv);
2908 
2909 	for (i = 0; i < argc; i++)
2910 		free(save[i]);
2911 	free(save);
2912 	free(argv);
2913 
2914 	return exit_status;
2915 }
2916 
uname(struct utsname * buf)2917 int uname(struct utsname *buf)
2918 {
2919 	unsigned v = (unsigned)GetVersion();
2920 	memset(buf, 0, sizeof(*buf));
2921 	xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2922 	xsnprintf(buf->release, sizeof(buf->release),
2923 		 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2924 	/* assuming NT variants only.. */
2925 	xsnprintf(buf->version, sizeof(buf->version),
2926 		  "%u", (v >> 16) & 0x7fff);
2927 	return 0;
2928 }
2929