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