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