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