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