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