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