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