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