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