Merge branch 'dl/compat-cleanup'
[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                 }
367
368         if (hide_dotfiles == HIDE_DOTFILES_TRUE)
369                 return *basename == '.';
370
371         assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
372         return !strncasecmp(".git", basename, 4) &&
373                 (!basename[4] || is_dir_sep(basename[4]));
374 }
375
376 static int set_hidden_flag(const wchar_t *path, int set)
377 {
378         DWORD original = GetFileAttributesW(path), modified;
379         if (set)
380                 modified = original | FILE_ATTRIBUTE_HIDDEN;
381         else
382                 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
383         if (original == modified || SetFileAttributesW(path, modified))
384                 return 0;
385         errno = err_win_to_posix(GetLastError());
386         return -1;
387 }
388
389 int mingw_mkdir(const char *path, int mode)
390 {
391         int ret;
392         wchar_t wpath[MAX_PATH];
393         if (xutftowcs_path(wpath, path) < 0)
394                 return -1;
395         ret = _wmkdir(wpath);
396         if (!ret && needs_hiding(path))
397                 return set_hidden_flag(wpath, 1);
398         return ret;
399 }
400
401 /*
402  * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
403  * is documented in [1] as opening a writable file handle in append mode.
404  * (It is believed that) this is atomic since it is maintained by the
405  * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
406  *
407  * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
408  *
409  * This trick does not appear to work for named pipes.  Instead it creates
410  * a named pipe client handle that cannot be written to.  Callers should
411  * just use the regular _wopen() for them.  (And since client handle gets
412  * bound to a unique server handle, it isn't really an issue.)
413  */
414 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
415 {
416         HANDLE handle;
417         int fd;
418         DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
419
420         /* only these flags are supported */
421         if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
422                 return errno = ENOSYS, -1;
423
424         /*
425          * FILE_SHARE_WRITE is required to permit child processes
426          * to append to the file.
427          */
428         handle = CreateFileW(wfilename, FILE_APPEND_DATA,
429                         FILE_SHARE_WRITE | FILE_SHARE_READ,
430                         NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
431         if (handle == INVALID_HANDLE_VALUE)
432                 return errno = err_win_to_posix(GetLastError()), -1;
433
434         /*
435          * No O_APPEND here, because the CRT uses it only to reset the
436          * file pointer to EOF before each write(); but that is not
437          * necessary (and may lead to races) for a file created with
438          * FILE_APPEND_DATA.
439          */
440         fd = _open_osfhandle((intptr_t)handle, O_BINARY);
441         if (fd < 0)
442                 CloseHandle(handle);
443         return fd;
444 }
445
446 /*
447  * Does the pathname map to the local named pipe filesystem?
448  * That is, does it have a "//./pipe/" prefix?
449  */
450 static int is_local_named_pipe_path(const char *filename)
451 {
452         return (is_dir_sep(filename[0]) &&
453                 is_dir_sep(filename[1]) &&
454                 filename[2] == '.'  &&
455                 is_dir_sep(filename[3]) &&
456                 !strncasecmp(filename+4, "pipe", 4) &&
457                 is_dir_sep(filename[8]) &&
458                 filename[9]);
459 }
460
461 int mingw_open (const char *filename, int oflags, ...)
462 {
463         typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
464         va_list args;
465         unsigned mode;
466         int fd;
467         wchar_t wfilename[MAX_PATH];
468         open_fn_t open_fn;
469
470         va_start(args, oflags);
471         mode = va_arg(args, int);
472         va_end(args);
473
474         if (filename && !strcmp(filename, "/dev/null"))
475                 filename = "nul";
476
477         if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
478                 open_fn = mingw_open_append;
479         else
480                 open_fn = _wopen;
481
482         if (xutftowcs_path(wfilename, filename) < 0)
483                 return -1;
484         fd = open_fn(wfilename, oflags, mode);
485
486         if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
487                 DWORD attrs = GetFileAttributesW(wfilename);
488                 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
489                         errno = EISDIR;
490         }
491         if ((oflags & O_CREAT) && needs_hiding(filename)) {
492                 /*
493                  * Internally, _wopen() uses the CreateFile() API which errors
494                  * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
495                  * specified and an already existing file's attributes do not
496                  * match *exactly*. As there is no mode or flag we can set that
497                  * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
498                  * again *without* the O_CREAT flag (that corresponds to the
499                  * CREATE_ALWAYS flag of CreateFile()).
500                  */
501                 if (fd < 0 && errno == EACCES)
502                         fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
503                 if (fd >= 0 && set_hidden_flag(wfilename, 1))
504                         warning("could not mark '%s' as hidden.", filename);
505         }
506         return fd;
507 }
508
509 static BOOL WINAPI ctrl_ignore(DWORD type)
510 {
511         return TRUE;
512 }
513
514 #undef fgetc
515 int mingw_fgetc(FILE *stream)
516 {
517         int ch;
518         if (!isatty(_fileno(stream)))
519                 return fgetc(stream);
520
521         SetConsoleCtrlHandler(ctrl_ignore, TRUE);
522         while (1) {
523                 ch = fgetc(stream);
524                 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
525                         break;
526
527                 /* Ctrl+C was pressed, simulate SIGINT and retry */
528                 mingw_raise(SIGINT);
529         }
530         SetConsoleCtrlHandler(ctrl_ignore, FALSE);
531         return ch;
532 }
533
534 #undef fopen
535 FILE *mingw_fopen (const char *filename, const char *otype)
536 {
537         int hide = needs_hiding(filename);
538         FILE *file;
539         wchar_t wfilename[MAX_PATH], wotype[4];
540         if (filename && !strcmp(filename, "/dev/null"))
541                 filename = "nul";
542         if (xutftowcs_path(wfilename, filename) < 0 ||
543                 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
544                 return NULL;
545         if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
546                 error("could not unhide %s", filename);
547                 return NULL;
548         }
549         file = _wfopen(wfilename, wotype);
550         if (!file && GetLastError() == ERROR_INVALID_NAME)
551                 errno = ENOENT;
552         if (file && hide && set_hidden_flag(wfilename, 1))
553                 warning("could not mark '%s' as hidden.", filename);
554         return file;
555 }
556
557 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
558 {
559         int hide = needs_hiding(filename);
560         FILE *file;
561         wchar_t wfilename[MAX_PATH], wotype[4];
562         if (filename && !strcmp(filename, "/dev/null"))
563                 filename = "nul";
564         if (xutftowcs_path(wfilename, filename) < 0 ||
565                 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
566                 return NULL;
567         if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
568                 error("could not unhide %s", filename);
569                 return NULL;
570         }
571         file = _wfreopen(wfilename, wotype, stream);
572         if (file && hide && set_hidden_flag(wfilename, 1))
573                 warning("could not mark '%s' as hidden.", filename);
574         return file;
575 }
576
577 #undef fflush
578 int mingw_fflush(FILE *stream)
579 {
580         int ret = fflush(stream);
581
582         /*
583          * write() is used behind the scenes of stdio output functions.
584          * Since git code does not check for errors after each stdio write
585          * operation, it can happen that write() is called by a later
586          * stdio function even if an earlier write() call failed. In the
587          * case of a pipe whose readable end was closed, only the first
588          * call to write() reports EPIPE on Windows. Subsequent write()
589          * calls report EINVAL. It is impossible to notice whether this
590          * fflush invocation triggered such a case, therefore, we have to
591          * catch all EINVAL errors whole-sale.
592          */
593         if (ret && errno == EINVAL)
594                 errno = EPIPE;
595
596         return ret;
597 }
598
599 #undef write
600 ssize_t mingw_write(int fd, const void *buf, size_t len)
601 {
602         ssize_t result = write(fd, buf, len);
603
604         if (result < 0 && errno == EINVAL && buf) {
605                 /* check if fd is a pipe */
606                 HANDLE h = (HANDLE) _get_osfhandle(fd);
607                 if (GetFileType(h) == FILE_TYPE_PIPE)
608                         errno = EPIPE;
609                 else
610                         errno = EINVAL;
611         }
612
613         return result;
614 }
615
616 int mingw_access(const char *filename, int mode)
617 {
618         wchar_t wfilename[MAX_PATH];
619         if (xutftowcs_path(wfilename, filename) < 0)
620                 return -1;
621         /* X_OK is not supported by the MSVCRT version */
622         return _waccess(wfilename, mode & ~X_OK);
623 }
624
625 int mingw_chdir(const char *dirname)
626 {
627         wchar_t wdirname[MAX_PATH];
628         if (xutftowcs_path(wdirname, dirname) < 0)
629                 return -1;
630         return _wchdir(wdirname);
631 }
632
633 int mingw_chmod(const char *filename, int mode)
634 {
635         wchar_t wfilename[MAX_PATH];
636         if (xutftowcs_path(wfilename, filename) < 0)
637                 return -1;
638         return _wchmod(wfilename, mode);
639 }
640
641 /*
642  * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
643  * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
644  */
645 static inline long long filetime_to_hnsec(const FILETIME *ft)
646 {
647         long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
648         /* Windows to Unix Epoch conversion */
649         return winTime - 116444736000000000LL;
650 }
651
652 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
653 {
654         long long hnsec = filetime_to_hnsec(ft);
655         ts->tv_sec = (time_t)(hnsec / 10000000);
656         ts->tv_nsec = (hnsec % 10000000) * 100;
657 }
658
659 /**
660  * Verifies that safe_create_leading_directories() would succeed.
661  */
662 static int has_valid_directory_prefix(wchar_t *wfilename)
663 {
664         int n = wcslen(wfilename);
665
666         while (n > 0) {
667                 wchar_t c = wfilename[--n];
668                 DWORD attributes;
669
670                 if (!is_dir_sep(c))
671                         continue;
672
673                 wfilename[n] = L'\0';
674                 attributes = GetFileAttributesW(wfilename);
675                 wfilename[n] = c;
676                 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
677                                 attributes == FILE_ATTRIBUTE_DEVICE)
678                         return 1;
679                 if (attributes == INVALID_FILE_ATTRIBUTES)
680                         switch (GetLastError()) {
681                         case ERROR_PATH_NOT_FOUND:
682                                 continue;
683                         case ERROR_FILE_NOT_FOUND:
684                                 /* This implies parent directory exists. */
685                                 return 1;
686                         }
687                 return 0;
688         }
689         return 1;
690 }
691
692 /* We keep the do_lstat code in a separate function to avoid recursion.
693  * When a path ends with a slash, the stat will fail with ENOENT. In
694  * this case, we strip the trailing slashes and stat again.
695  *
696  * If follow is true then act like stat() and report on the link
697  * target. Otherwise report on the link itself.
698  */
699 static int do_lstat(int follow, const char *file_name, struct stat *buf)
700 {
701         WIN32_FILE_ATTRIBUTE_DATA fdata;
702         wchar_t wfilename[MAX_PATH];
703         if (xutftowcs_path(wfilename, file_name) < 0)
704                 return -1;
705
706         if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
707                 buf->st_ino = 0;
708                 buf->st_gid = 0;
709                 buf->st_uid = 0;
710                 buf->st_nlink = 1;
711                 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
712                 buf->st_size = fdata.nFileSizeLow |
713                         (((off_t)fdata.nFileSizeHigh)<<32);
714                 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
715                 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
716                 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
717                 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
718                 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
719                         WIN32_FIND_DATAW findbuf;
720                         HANDLE handle = FindFirstFileW(wfilename, &findbuf);
721                         if (handle != INVALID_HANDLE_VALUE) {
722                                 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
723                                                 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
724                                         if (follow) {
725                                                 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
726                                                 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
727                                         } else {
728                                                 buf->st_mode = S_IFLNK;
729                                         }
730                                         buf->st_mode |= S_IREAD;
731                                         if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
732                                                 buf->st_mode |= S_IWRITE;
733                                 }
734                                 FindClose(handle);
735                         }
736                 }
737                 return 0;
738         }
739         switch (GetLastError()) {
740         case ERROR_ACCESS_DENIED:
741         case ERROR_SHARING_VIOLATION:
742         case ERROR_LOCK_VIOLATION:
743         case ERROR_SHARING_BUFFER_EXCEEDED:
744                 errno = EACCES;
745                 break;
746         case ERROR_BUFFER_OVERFLOW:
747                 errno = ENAMETOOLONG;
748                 break;
749         case ERROR_NOT_ENOUGH_MEMORY:
750                 errno = ENOMEM;
751                 break;
752         case ERROR_PATH_NOT_FOUND:
753                 if (!has_valid_directory_prefix(wfilename)) {
754                         errno = ENOTDIR;
755                         break;
756                 }
757                 /* fallthru */
758         default:
759                 errno = ENOENT;
760                 break;
761         }
762         return -1;
763 }
764
765 /* We provide our own lstat/fstat functions, since the provided
766  * lstat/fstat functions are so slow. These stat functions are
767  * tailored for Git's usage (read: fast), and are not meant to be
768  * complete. Note that Git stat()s are redirected to mingw_lstat()
769  * too, since Windows doesn't really handle symlinks that well.
770  */
771 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
772 {
773         int namelen;
774         char alt_name[PATH_MAX];
775
776         if (!do_lstat(follow, file_name, buf))
777                 return 0;
778
779         /* if file_name ended in a '/', Windows returned ENOENT;
780          * try again without trailing slashes
781          */
782         if (errno != ENOENT)
783                 return -1;
784
785         namelen = strlen(file_name);
786         if (namelen && file_name[namelen-1] != '/')
787                 return -1;
788         while (namelen && file_name[namelen-1] == '/')
789                 --namelen;
790         if (!namelen || namelen >= PATH_MAX)
791                 return -1;
792
793         memcpy(alt_name, file_name, namelen);
794         alt_name[namelen] = 0;
795         return do_lstat(follow, alt_name, buf);
796 }
797
798 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
799 {
800         BY_HANDLE_FILE_INFORMATION fdata;
801
802         if (!GetFileInformationByHandle(hnd, &fdata)) {
803                 errno = err_win_to_posix(GetLastError());
804                 return -1;
805         }
806
807         buf->st_ino = 0;
808         buf->st_gid = 0;
809         buf->st_uid = 0;
810         buf->st_nlink = 1;
811         buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
812         buf->st_size = fdata.nFileSizeLow |
813                 (((off_t)fdata.nFileSizeHigh)<<32);
814         buf->st_dev = buf->st_rdev = 0; /* not used by Git */
815         filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
816         filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
817         filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
818         return 0;
819 }
820
821 int mingw_lstat(const char *file_name, struct stat *buf)
822 {
823         return do_stat_internal(0, file_name, buf);
824 }
825 int mingw_stat(const char *file_name, struct stat *buf)
826 {
827         return do_stat_internal(1, file_name, buf);
828 }
829
830 int mingw_fstat(int fd, struct stat *buf)
831 {
832         HANDLE fh = (HANDLE)_get_osfhandle(fd);
833         DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
834
835         switch (type) {
836         case FILE_TYPE_DISK:
837                 return get_file_info_by_handle(fh, buf);
838
839         case FILE_TYPE_CHAR:
840         case FILE_TYPE_PIPE:
841                 /* initialize stat fields */
842                 memset(buf, 0, sizeof(*buf));
843                 buf->st_nlink = 1;
844
845                 if (type == FILE_TYPE_CHAR) {
846                         buf->st_mode = _S_IFCHR;
847                 } else {
848                         buf->st_mode = _S_IFIFO;
849                         if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
850                                 buf->st_size = avail;
851                 }
852                 return 0;
853
854         default:
855                 errno = EBADF;
856                 return -1;
857         }
858 }
859
860 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
861 {
862         long long winTime = t * 10000000LL + 116444736000000000LL;
863         ft->dwLowDateTime = winTime;
864         ft->dwHighDateTime = winTime >> 32;
865 }
866
867 int mingw_utime (const char *file_name, const struct utimbuf *times)
868 {
869         FILETIME mft, aft;
870         int fh, rc;
871         DWORD attrs;
872         wchar_t wfilename[MAX_PATH];
873         if (xutftowcs_path(wfilename, file_name) < 0)
874                 return -1;
875
876         /* must have write permission */
877         attrs = GetFileAttributesW(wfilename);
878         if (attrs != INVALID_FILE_ATTRIBUTES &&
879             (attrs & FILE_ATTRIBUTE_READONLY)) {
880                 /* ignore errors here; open() will report them */
881                 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
882         }
883
884         if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
885                 rc = -1;
886                 goto revert_attrs;
887         }
888
889         if (times) {
890                 time_t_to_filetime(times->modtime, &mft);
891                 time_t_to_filetime(times->actime, &aft);
892         } else {
893                 GetSystemTimeAsFileTime(&mft);
894                 aft = mft;
895         }
896         if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
897                 errno = EINVAL;
898                 rc = -1;
899         } else
900                 rc = 0;
901         close(fh);
902
903 revert_attrs:
904         if (attrs != INVALID_FILE_ATTRIBUTES &&
905             (attrs & FILE_ATTRIBUTE_READONLY)) {
906                 /* ignore errors again */
907                 SetFileAttributesW(wfilename, attrs);
908         }
909         return rc;
910 }
911
912 #undef strftime
913 size_t mingw_strftime(char *s, size_t max,
914                       const char *format, const struct tm *tm)
915 {
916         size_t ret = strftime(s, max, format, tm);
917
918         if (!ret && errno == EINVAL)
919                 die("invalid strftime format: '%s'", format);
920         return ret;
921 }
922
923 unsigned int sleep (unsigned int seconds)
924 {
925         Sleep(seconds*1000);
926         return 0;
927 }
928
929 char *mingw_mktemp(char *template)
930 {
931         wchar_t wtemplate[MAX_PATH];
932         if (xutftowcs_path(wtemplate, template) < 0)
933                 return NULL;
934         if (!_wmktemp(wtemplate))
935                 return NULL;
936         if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
937                 return NULL;
938         return template;
939 }
940
941 int mkstemp(char *template)
942 {
943         char *filename = mktemp(template);
944         if (filename == NULL)
945                 return -1;
946         return open(filename, O_RDWR | O_CREAT, 0600);
947 }
948
949 int gettimeofday(struct timeval *tv, void *tz)
950 {
951         FILETIME ft;
952         long long hnsec;
953
954         GetSystemTimeAsFileTime(&ft);
955         hnsec = filetime_to_hnsec(&ft);
956         tv->tv_sec = hnsec / 10000000;
957         tv->tv_usec = (hnsec % 10000000) / 10;
958         return 0;
959 }
960
961 int pipe(int filedes[2])
962 {
963         HANDLE h[2];
964
965         /* this creates non-inheritable handles */
966         if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
967                 errno = err_win_to_posix(GetLastError());
968                 return -1;
969         }
970         filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
971         if (filedes[0] < 0) {
972                 CloseHandle(h[0]);
973                 CloseHandle(h[1]);
974                 return -1;
975         }
976         filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
977         if (filedes[1] < 0) {
978                 close(filedes[0]);
979                 CloseHandle(h[1]);
980                 return -1;
981         }
982         return 0;
983 }
984
985 struct tm *gmtime_r(const time_t *timep, struct tm *result)
986 {
987         /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
988         memcpy(result, gmtime(timep), sizeof(struct tm));
989         return result;
990 }
991
992 struct tm *localtime_r(const time_t *timep, struct tm *result)
993 {
994         /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
995         memcpy(result, localtime(timep), sizeof(struct tm));
996         return result;
997 }
998
999 char *mingw_getcwd(char *pointer, int len)
1000 {
1001         wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1002         DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1003
1004         if (!ret || ret >= ARRAY_SIZE(cwd)) {
1005                 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1006                 return NULL;
1007         }
1008         ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1009         if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1010                 HANDLE hnd = CreateFileW(cwd, 0,
1011                         FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1012                         OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1013                 if (hnd == INVALID_HANDLE_VALUE)
1014                         return NULL;
1015                 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1016                 CloseHandle(hnd);
1017                 if (!ret || ret >= ARRAY_SIZE(wpointer))
1018                         return NULL;
1019                 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1020                         return NULL;
1021                 return pointer;
1022         }
1023         if (!ret || ret >= ARRAY_SIZE(wpointer))
1024                 return NULL;
1025         if (xwcstoutf(pointer, wpointer, len) < 0)
1026                 return NULL;
1027         convert_slashes(pointer);
1028         return pointer;
1029 }
1030
1031 /*
1032  * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1033  * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1034  */
1035 static const char *quote_arg_msvc(const char *arg)
1036 {
1037         /* count chars to quote */
1038         int len = 0, n = 0;
1039         int force_quotes = 0;
1040         char *q, *d;
1041         const char *p = arg;
1042         if (!*p) force_quotes = 1;
1043         while (*p) {
1044                 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1045                         force_quotes = 1;
1046                 else if (*p == '"')
1047                         n++;
1048                 else if (*p == '\\') {
1049                         int count = 0;
1050                         while (*p == '\\') {
1051                                 count++;
1052                                 p++;
1053                                 len++;
1054                         }
1055                         if (*p == '"')
1056                                 n += count*2 + 1;
1057                         continue;
1058                 }
1059                 len++;
1060                 p++;
1061         }
1062         if (!force_quotes && n == 0)
1063                 return arg;
1064
1065         /* insert \ where necessary */
1066         d = q = xmalloc(st_add3(len, n, 3));
1067         *d++ = '"';
1068         while (*arg) {
1069                 if (*arg == '"')
1070                         *d++ = '\\';
1071                 else if (*arg == '\\') {
1072                         int count = 0;
1073                         while (*arg == '\\') {
1074                                 count++;
1075                                 *d++ = *arg++;
1076                         }
1077                         if (*arg == '"') {
1078                                 while (count-- > 0)
1079                                         *d++ = '\\';
1080                                 *d++ = '\\';
1081                         }
1082                 }
1083                 *d++ = *arg++;
1084         }
1085         *d++ = '"';
1086         *d++ = 0;
1087         return q;
1088 }
1089
1090 #include "quote.h"
1091
1092 static const char *quote_arg_msys2(const char *arg)
1093 {
1094         struct strbuf buf = STRBUF_INIT;
1095         const char *p2 = arg, *p;
1096
1097         for (p = arg; *p; p++) {
1098                 int ws = isspace(*p);
1099                 if (!ws && *p != '\\' && *p != '"' && *p != '{')
1100                         continue;
1101                 if (!buf.len)
1102                         strbuf_addch(&buf, '"');
1103                 if (p != p2)
1104                         strbuf_add(&buf, p2, p - p2);
1105                 if (!ws && *p != '{')
1106                         strbuf_addch(&buf, '\\');
1107                 p2 = p;
1108         }
1109
1110         if (p == arg)
1111                 strbuf_addch(&buf, '"');
1112         else if (!buf.len)
1113                 return arg;
1114         else
1115                 strbuf_add(&buf, p2, p - p2),
1116
1117         strbuf_addch(&buf, '"');
1118         return strbuf_detach(&buf, 0);
1119 }
1120
1121 static const char *parse_interpreter(const char *cmd)
1122 {
1123         static char buf[100];
1124         char *p, *opt;
1125         int n, fd;
1126
1127         /* don't even try a .exe */
1128         n = strlen(cmd);
1129         if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1130                 return NULL;
1131
1132         fd = open(cmd, O_RDONLY);
1133         if (fd < 0)
1134                 return NULL;
1135         n = read(fd, buf, sizeof(buf)-1);
1136         close(fd);
1137         if (n < 4)      /* at least '#!/x' and not error */
1138                 return NULL;
1139
1140         if (buf[0] != '#' || buf[1] != '!')
1141                 return NULL;
1142         buf[n] = '\0';
1143         p = buf + strcspn(buf, "\r\n");
1144         if (!*p)
1145                 return NULL;
1146
1147         *p = '\0';
1148         if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1149                 return NULL;
1150         /* strip options */
1151         if ((opt = strchr(p+1, ' ')))
1152                 *opt = '\0';
1153         return p+1;
1154 }
1155
1156 /*
1157  * exe_only means that we only want to detect .exe files, but not scripts
1158  * (which do not have an extension)
1159  */
1160 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1161                          int isexe, int exe_only)
1162 {
1163         char path[MAX_PATH];
1164         wchar_t wpath[MAX_PATH];
1165         snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1166
1167         if (xutftowcs_path(wpath, path) < 0)
1168                 return NULL;
1169
1170         if (!isexe && _waccess(wpath, F_OK) == 0)
1171                 return xstrdup(path);
1172         wpath[wcslen(wpath)-4] = '\0';
1173         if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1174                 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1175                         path[strlen(path)-4] = '\0';
1176                         return xstrdup(path);
1177                 }
1178         }
1179         return NULL;
1180 }
1181
1182 /*
1183  * Determines the absolute path of cmd using the split path in path.
1184  * If cmd contains a slash or backslash, no lookup is performed.
1185  */
1186 static char *path_lookup(const char *cmd, int exe_only)
1187 {
1188         const char *path;
1189         char *prog = NULL;
1190         int len = strlen(cmd);
1191         int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1192
1193         if (strchr(cmd, '/') || strchr(cmd, '\\'))
1194                 return xstrdup(cmd);
1195
1196         path = mingw_getenv("PATH");
1197         if (!path)
1198                 return NULL;
1199
1200         while (!prog) {
1201                 const char *sep = strchrnul(path, ';');
1202                 int dirlen = sep - path;
1203                 if (dirlen)
1204                         prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1205                 if (!*sep)
1206                         break;
1207                 path = sep + 1;
1208         }
1209
1210         return prog;
1211 }
1212
1213 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1214 {
1215         while (*s && *s != c)
1216                 s++;
1217         return s;
1218 }
1219
1220 /* Compare only keys */
1221 static int wenvcmp(const void *a, const void *b)
1222 {
1223         wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1224         size_t p_len, q_len;
1225
1226         /* Find the keys */
1227         p_len = wcschrnul(p, L'=') - p;
1228         q_len = wcschrnul(q, L'=') - q;
1229
1230         /* If the length differs, include the shorter key's NUL */
1231         if (p_len < q_len)
1232                 p_len++;
1233         else if (p_len > q_len)
1234                 p_len = q_len + 1;
1235
1236         return _wcsnicmp(p, q, p_len);
1237 }
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                 COPY_ARRAY(result, wenv, size);
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_stable_qsort() and then copy,
1278          * skipping 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_stable_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                 COPY_ARRAY(p, array[i], size);
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         /* GetEnvironmentVariableW() only sets the last error upon failure */
1669         SetLastError(ERROR_SUCCESS);
1670         len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1671         if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1672                 free(w_key);
1673                 return NULL;
1674         }
1675         free(w_key);
1676
1677         len_value = len_value * 3 + 1;
1678         /* We cannot use xcalloc() here because that uses getenv() itself */
1679         value = calloc(len_value, sizeof(char));
1680         if (!value)
1681                 die("Out of memory, (tried to allocate %u bytes)", len_value);
1682         xwcstoutf(value, w_value, len_value);
1683
1684         /*
1685          * We return `value` which is an allocated value and the caller is NOT
1686          * expecting to have to free it, so we keep a round-robin array,
1687          * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1688          */
1689         free(values[value_counter]);
1690         values[value_counter++] = value;
1691         if (value_counter >= ARRAY_SIZE(values))
1692                 value_counter = 0;
1693
1694         return value;
1695 }
1696
1697 int mingw_putenv(const char *namevalue)
1698 {
1699         int size;
1700         wchar_t *wide, *equal;
1701         BOOL result;
1702
1703         if (!namevalue || !*namevalue)
1704                 return 0;
1705
1706         size = strlen(namevalue) * 2 + 1;
1707         wide = calloc(size, sizeof(wchar_t));
1708         if (!wide)
1709                 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1710         xutftowcs(wide, namevalue, size);
1711         equal = wcschr(wide, L'=');
1712         if (!equal)
1713                 result = SetEnvironmentVariableW(wide, NULL);
1714         else {
1715                 *equal = L'\0';
1716                 result = SetEnvironmentVariableW(wide, equal + 1);
1717         }
1718         free(wide);
1719
1720         if (!result)
1721                 errno = err_win_to_posix(GetLastError());
1722
1723         return result ? 0 : -1;
1724 }
1725
1726 static void ensure_socket_initialization(void)
1727 {
1728         WSADATA wsa;
1729         static int initialized = 0;
1730
1731         if (initialized)
1732                 return;
1733
1734         if (WSAStartup(MAKEWORD(2,2), &wsa))
1735                 die("unable to initialize winsock subsystem, error %d",
1736                         WSAGetLastError());
1737
1738         atexit((void(*)(void)) WSACleanup);
1739         initialized = 1;
1740 }
1741
1742 #undef gethostname
1743 int mingw_gethostname(char *name, int namelen)
1744 {
1745     ensure_socket_initialization();
1746     return gethostname(name, namelen);
1747 }
1748
1749 #undef gethostbyname
1750 struct hostent *mingw_gethostbyname(const char *host)
1751 {
1752         ensure_socket_initialization();
1753         return gethostbyname(host);
1754 }
1755
1756 #undef getaddrinfo
1757 int mingw_getaddrinfo(const char *node, const char *service,
1758                       const struct addrinfo *hints, struct addrinfo **res)
1759 {
1760         ensure_socket_initialization();
1761         return getaddrinfo(node, service, hints, res);
1762 }
1763
1764 int mingw_socket(int domain, int type, int protocol)
1765 {
1766         int sockfd;
1767         SOCKET s;
1768
1769         ensure_socket_initialization();
1770         s = WSASocket(domain, type, protocol, NULL, 0, 0);
1771         if (s == INVALID_SOCKET) {
1772                 /*
1773                  * WSAGetLastError() values are regular BSD error codes
1774                  * biased by WSABASEERR.
1775                  * However, strerror() does not know about networking
1776                  * specific errors, which are values beginning at 38 or so.
1777                  * Therefore, we choose to leave the biased error code
1778                  * in errno so that _if_ someone looks up the code somewhere,
1779                  * then it is at least the number that are usually listed.
1780                  */
1781                 errno = WSAGetLastError();
1782                 return -1;
1783         }
1784         /* convert into a file descriptor */
1785         if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1786                 closesocket(s);
1787                 return error("unable to make a socket file descriptor: %s",
1788                         strerror(errno));
1789         }
1790         return sockfd;
1791 }
1792
1793 #undef connect
1794 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1795 {
1796         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1797         return connect(s, sa, sz);
1798 }
1799
1800 #undef bind
1801 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1802 {
1803         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1804         return bind(s, sa, sz);
1805 }
1806
1807 #undef setsockopt
1808 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1809 {
1810         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1811         return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1812 }
1813
1814 #undef shutdown
1815 int mingw_shutdown(int sockfd, int how)
1816 {
1817         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1818         return shutdown(s, how);
1819 }
1820
1821 #undef listen
1822 int mingw_listen(int sockfd, int backlog)
1823 {
1824         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1825         return listen(s, backlog);
1826 }
1827
1828 #undef accept
1829 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1830 {
1831         int sockfd2;
1832
1833         SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1834         SOCKET s2 = accept(s1, sa, sz);
1835
1836         /* convert into a file descriptor */
1837         if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1838                 int err = errno;
1839                 closesocket(s2);
1840                 return error("unable to make a socket file descriptor: %s",
1841                         strerror(err));
1842         }
1843         return sockfd2;
1844 }
1845
1846 #undef rename
1847 int mingw_rename(const char *pold, const char *pnew)
1848 {
1849         DWORD attrs, gle;
1850         int tries = 0;
1851         wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1852         if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1853                 return -1;
1854
1855         /*
1856          * Try native rename() first to get errno right.
1857          * It is based on MoveFile(), which cannot overwrite existing files.
1858          */
1859         if (!_wrename(wpold, wpnew))
1860                 return 0;
1861         if (errno != EEXIST)
1862                 return -1;
1863 repeat:
1864         if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1865                 return 0;
1866         /* TODO: translate more errors */
1867         gle = GetLastError();
1868         if (gle == ERROR_ACCESS_DENIED &&
1869             (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
1870                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1871                         DWORD attrsold = GetFileAttributesW(wpold);
1872                         if (attrsold == INVALID_FILE_ATTRIBUTES ||
1873                             !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
1874                                 errno = EISDIR;
1875                         else if (!_wrmdir(wpnew))
1876                                 goto repeat;
1877                         return -1;
1878                 }
1879                 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1880                     SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1881                         if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1882                                 return 0;
1883                         gle = GetLastError();
1884                         /* revert file attributes on failure */
1885                         SetFileAttributesW(wpnew, attrs);
1886                 }
1887         }
1888         if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1889                 /*
1890                  * We assume that some other process had the source or
1891                  * destination file open at the wrong moment and retry.
1892                  * In order to give the other process a higher chance to
1893                  * complete its operation, we give up our time slice now.
1894                  * If we have to retry again, we do sleep a bit.
1895                  */
1896                 Sleep(delay[tries]);
1897                 tries++;
1898                 goto repeat;
1899         }
1900         if (gle == ERROR_ACCESS_DENIED &&
1901                ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1902                        "Should I try again?", pold, pnew))
1903                 goto repeat;
1904
1905         errno = EACCES;
1906         return -1;
1907 }
1908
1909 /*
1910  * Note that this doesn't return the actual pagesize, but
1911  * the allocation granularity. If future Windows specific git code
1912  * needs the real getpagesize function, we need to find another solution.
1913  */
1914 int mingw_getpagesize(void)
1915 {
1916         SYSTEM_INFO si;
1917         GetSystemInfo(&si);
1918         return si.dwAllocationGranularity;
1919 }
1920
1921 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
1922 enum EXTENDED_NAME_FORMAT {
1923         NameDisplay = 3,
1924         NameUserPrincipal = 8
1925 };
1926
1927 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
1928 {
1929         DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
1930                 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
1931         static wchar_t wbuffer[1024];
1932         DWORD len;
1933
1934         if (!INIT_PROC_ADDR(GetUserNameExW))
1935                 return NULL;
1936
1937         len = ARRAY_SIZE(wbuffer);
1938         if (GetUserNameExW(type, wbuffer, &len)) {
1939                 char *converted = xmalloc((len *= 3));
1940                 if (xwcstoutf(converted, wbuffer, len) >= 0)
1941                         return converted;
1942                 free(converted);
1943         }
1944
1945         return NULL;
1946 }
1947
1948 char *mingw_query_user_email(void)
1949 {
1950         return get_extended_user_info(NameUserPrincipal);
1951 }
1952
1953 struct passwd *getpwuid(int uid)
1954 {
1955         static unsigned initialized;
1956         static char user_name[100];
1957         static struct passwd *p;
1958         wchar_t buf[100];
1959         DWORD len;
1960
1961         if (initialized)
1962                 return p;
1963
1964         len = ARRAY_SIZE(buf);
1965         if (!GetUserNameW(buf, &len)) {
1966                 initialized = 1;
1967                 return NULL;
1968         }
1969
1970         if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
1971                 initialized = 1;
1972                 return NULL;
1973         }
1974
1975         p = xmalloc(sizeof(*p));
1976         p->pw_name = user_name;
1977         p->pw_gecos = get_extended_user_info(NameDisplay);
1978         if (!p->pw_gecos)
1979                 p->pw_gecos = "unknown";
1980         p->pw_dir = NULL;
1981
1982         initialized = 1;
1983         return p;
1984 }
1985
1986 static HANDLE timer_event;
1987 static HANDLE timer_thread;
1988 static int timer_interval;
1989 static int one_shot;
1990 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
1991
1992 /* The timer works like this:
1993  * The thread, ticktack(), is a trivial routine that most of the time
1994  * only waits to receive the signal to terminate. The main thread tells
1995  * the thread to terminate by setting the timer_event to the signalled
1996  * state.
1997  * But ticktack() interrupts the wait state after the timer's interval
1998  * length to call the signal handler.
1999  */
2000
2001 static unsigned __stdcall ticktack(void *dummy)
2002 {
2003         while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2004                 mingw_raise(SIGALRM);
2005                 if (one_shot)
2006                         break;
2007         }
2008         return 0;
2009 }
2010
2011 static int start_timer_thread(void)
2012 {
2013         timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2014         if (timer_event) {
2015                 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2016                 if (!timer_thread )
2017                         return errno = ENOMEM,
2018                                 error("cannot start timer thread");
2019         } else
2020                 return errno = ENOMEM,
2021                         error("cannot allocate resources for timer");
2022         return 0;
2023 }
2024
2025 static void stop_timer_thread(void)
2026 {
2027         if (timer_event)
2028                 SetEvent(timer_event);  /* tell thread to terminate */
2029         if (timer_thread) {
2030                 int rc = WaitForSingleObject(timer_thread, 10000);
2031                 if (rc == WAIT_TIMEOUT)
2032                         error("timer thread did not terminate timely");
2033                 else if (rc != WAIT_OBJECT_0)
2034                         error("waiting for timer thread failed: %lu",
2035                               GetLastError());
2036                 CloseHandle(timer_thread);
2037         }
2038         if (timer_event)
2039                 CloseHandle(timer_event);
2040         timer_event = NULL;
2041         timer_thread = NULL;
2042 }
2043
2044 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2045 {
2046         return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2047 }
2048
2049 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2050 {
2051         static const struct timeval zero;
2052         static int atexit_done;
2053
2054         if (out != NULL)
2055                 return errno = EINVAL,
2056                         error("setitimer param 3 != NULL not implemented");
2057         if (!is_timeval_eq(&in->it_interval, &zero) &&
2058             !is_timeval_eq(&in->it_interval, &in->it_value))
2059                 return errno = EINVAL,
2060                         error("setitimer: it_interval must be zero or eq it_value");
2061
2062         if (timer_thread)
2063                 stop_timer_thread();
2064
2065         if (is_timeval_eq(&in->it_value, &zero) &&
2066             is_timeval_eq(&in->it_interval, &zero))
2067                 return 0;
2068
2069         timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2070         one_shot = is_timeval_eq(&in->it_interval, &zero);
2071         if (!atexit_done) {
2072                 atexit(stop_timer_thread);
2073                 atexit_done = 1;
2074         }
2075         return start_timer_thread();
2076 }
2077
2078 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2079 {
2080         if (sig != SIGALRM)
2081                 return errno = EINVAL,
2082                         error("sigaction only implemented for SIGALRM");
2083         if (out != NULL)
2084                 return errno = EINVAL,
2085                         error("sigaction: param 3 != NULL not implemented");
2086
2087         timer_fn = in->sa_handler;
2088         return 0;
2089 }
2090
2091 #undef signal
2092 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2093 {
2094         sig_handler_t old;
2095
2096         switch (sig) {
2097         case SIGALRM:
2098                 old = timer_fn;
2099                 timer_fn = handler;
2100                 break;
2101
2102         case SIGINT:
2103                 old = sigint_fn;
2104                 sigint_fn = handler;
2105                 break;
2106
2107         default:
2108                 return signal(sig, handler);
2109         }
2110
2111         return old;
2112 }
2113
2114 #undef raise
2115 int mingw_raise(int sig)
2116 {
2117         switch (sig) {
2118         case SIGALRM:
2119                 if (timer_fn == SIG_DFL) {
2120                         if (isatty(STDERR_FILENO))
2121                                 fputs("Alarm clock\n", stderr);
2122                         exit(128 + SIGALRM);
2123                 } else if (timer_fn != SIG_IGN)
2124                         timer_fn(SIGALRM);
2125                 return 0;
2126
2127         case SIGINT:
2128                 if (sigint_fn == SIG_DFL)
2129                         exit(128 + SIGINT);
2130                 else if (sigint_fn != SIG_IGN)
2131                         sigint_fn(SIGINT);
2132                 return 0;
2133
2134 #if defined(_MSC_VER)
2135         case SIGILL:
2136         case SIGFPE:
2137         case SIGSEGV:
2138         case SIGTERM:
2139         case SIGBREAK:
2140         case SIGABRT:
2141         case SIGABRT_COMPAT:
2142                 /*
2143                  * The <signal.h> header in the MS C Runtime defines 8 signals
2144                  * as being supported on the platform. Anything else causes an
2145                  * "Invalid signal or error" (which in DEBUG builds causes the
2146                  * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2147                  * already know will fail.
2148                  */
2149                 return raise(sig);
2150         default:
2151                 errno = EINVAL;
2152                 return -1;
2153
2154 #else
2155
2156         default:
2157                 return raise(sig);
2158
2159 #endif
2160
2161         }
2162 }
2163
2164 int link(const char *oldpath, const char *newpath)
2165 {
2166         wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2167         if (xutftowcs_path(woldpath, oldpath) < 0 ||
2168                 xutftowcs_path(wnewpath, newpath) < 0)
2169                 return -1;
2170
2171         if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2172                 errno = err_win_to_posix(GetLastError());
2173                 return -1;
2174         }
2175         return 0;
2176 }
2177
2178 pid_t waitpid(pid_t pid, int *status, int options)
2179 {
2180         HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2181             FALSE, pid);
2182         if (!h) {
2183                 errno = ECHILD;
2184                 return -1;
2185         }
2186
2187         if (pid > 0 && options & WNOHANG) {
2188                 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2189                         CloseHandle(h);
2190                         return 0;
2191                 }
2192                 options &= ~WNOHANG;
2193         }
2194
2195         if (options == 0) {
2196                 struct pinfo_t **ppinfo;
2197                 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2198                         CloseHandle(h);
2199                         return 0;
2200                 }
2201
2202                 if (status)
2203                         GetExitCodeProcess(h, (LPDWORD)status);
2204
2205                 EnterCriticalSection(&pinfo_cs);
2206
2207                 ppinfo = &pinfo;
2208                 while (*ppinfo) {
2209                         struct pinfo_t *info = *ppinfo;
2210                         if (info->pid == pid) {
2211                                 CloseHandle(info->proc);
2212                                 *ppinfo = info->next;
2213                                 free(info);
2214                                 break;
2215                         }
2216                         ppinfo = &info->next;
2217                 }
2218
2219                 LeaveCriticalSection(&pinfo_cs);
2220
2221                 CloseHandle(h);
2222                 return pid;
2223         }
2224         CloseHandle(h);
2225
2226         errno = EINVAL;
2227         return -1;
2228 }
2229
2230 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2231 {
2232         int upos = 0, wpos = 0;
2233         const unsigned char *utf = (const unsigned char*) utfs;
2234         if (!utf || !wcs || wcslen < 1) {
2235                 errno = EINVAL;
2236                 return -1;
2237         }
2238         /* reserve space for \0 */
2239         wcslen--;
2240         if (utflen < 0)
2241                 utflen = INT_MAX;
2242
2243         while (upos < utflen) {
2244                 int c = utf[upos++] & 0xff;
2245                 if (utflen == INT_MAX && c == 0)
2246                         break;
2247
2248                 if (wpos >= wcslen) {
2249                         wcs[wpos] = 0;
2250                         errno = ERANGE;
2251                         return -1;
2252                 }
2253
2254                 if (c < 0x80) {
2255                         /* ASCII */
2256                         wcs[wpos++] = c;
2257                 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2258                                 (utf[upos] & 0xc0) == 0x80) {
2259                         /* 2-byte utf-8 */
2260                         c = ((c & 0x1f) << 6);
2261                         c |= (utf[upos++] & 0x3f);
2262                         wcs[wpos++] = c;
2263                 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2264                                 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2265                                 (utf[upos] & 0xc0) == 0x80 &&
2266                                 (utf[upos + 1] & 0xc0) == 0x80) {
2267                         /* 3-byte utf-8 */
2268                         c = ((c & 0x0f) << 12);
2269                         c |= ((utf[upos++] & 0x3f) << 6);
2270                         c |= (utf[upos++] & 0x3f);
2271                         wcs[wpos++] = c;
2272                 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2273                                 wpos + 1 < wcslen &&
2274                                 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2275                                 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2276                                 (utf[upos] & 0xc0) == 0x80 &&
2277                                 (utf[upos + 1] & 0xc0) == 0x80 &&
2278                                 (utf[upos + 2] & 0xc0) == 0x80) {
2279                         /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2280                         c = ((c & 0x07) << 18);
2281                         c |= ((utf[upos++] & 0x3f) << 12);
2282                         c |= ((utf[upos++] & 0x3f) << 6);
2283                         c |= (utf[upos++] & 0x3f);
2284                         c -= 0x10000;
2285                         wcs[wpos++] = 0xd800 | (c >> 10);
2286                         wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2287                 } else if (c >= 0xa0) {
2288                         /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2289                         wcs[wpos++] = c;
2290                 } else {
2291                         /* invalid utf-8 byte, non-printable unicode: convert to hex */
2292                         static const char *hex = "0123456789abcdef";
2293                         wcs[wpos++] = hex[c >> 4];
2294                         if (wpos < wcslen)
2295                                 wcs[wpos++] = hex[c & 0x0f];
2296                 }
2297         }
2298         wcs[wpos] = 0;
2299         return wpos;
2300 }
2301
2302 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2303 {
2304         if (!wcs || !utf || utflen < 1) {
2305                 errno = EINVAL;
2306                 return -1;
2307         }
2308         utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2309         if (utflen)
2310                 return utflen - 1;
2311         errno = ERANGE;
2312         return -1;
2313 }
2314
2315 static void setup_windows_environment(void)
2316 {
2317         char *tmp = getenv("TMPDIR");
2318
2319         /* on Windows it is TMP and TEMP */
2320         if (!tmp) {
2321                 if (!(tmp = getenv("TMP")))
2322                         tmp = getenv("TEMP");
2323                 if (tmp) {
2324                         setenv("TMPDIR", tmp, 1);
2325                         tmp = getenv("TMPDIR");
2326                 }
2327         }
2328
2329         if (tmp) {
2330                 /*
2331                  * Convert all dir separators to forward slashes,
2332                  * to help shell commands called from the Git
2333                  * executable (by not mistaking the dir separators
2334                  * for escape characters).
2335                  */
2336                 convert_slashes(tmp);
2337         }
2338
2339         /* simulate TERM to enable auto-color (see color.c) */
2340         if (!getenv("TERM"))
2341                 setenv("TERM", "cygwin", 1);
2342
2343         /* calculate HOME if not set */
2344         if (!getenv("HOME")) {
2345                 /*
2346                  * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2347                  * location, thus also check if the path exists (i.e. is not
2348                  * disconnected)
2349                  */
2350                 if ((tmp = getenv("HOMEDRIVE"))) {
2351                         struct strbuf buf = STRBUF_INIT;
2352                         strbuf_addstr(&buf, tmp);
2353                         if ((tmp = getenv("HOMEPATH"))) {
2354                                 strbuf_addstr(&buf, tmp);
2355                                 if (is_directory(buf.buf))
2356                                         setenv("HOME", buf.buf, 1);
2357                                 else
2358                                         tmp = NULL; /* use $USERPROFILE */
2359                         }
2360                         strbuf_release(&buf);
2361                 }
2362                 /* use $USERPROFILE if the home share is not available */
2363                 if (!tmp && (tmp = getenv("USERPROFILE")))
2364                         setenv("HOME", tmp, 1);
2365         }
2366 }
2367
2368 #if !defined(_MSC_VER)
2369 /*
2370  * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2371  * mingw startup code, see init.c in mingw runtime).
2372  */
2373 int _CRT_glob = 0;
2374 #endif
2375
2376 static NORETURN void die_startup(void)
2377 {
2378         fputs("fatal: not enough memory for initialization", stderr);
2379         exit(128);
2380 }
2381
2382 static void *malloc_startup(size_t size)
2383 {
2384         void *result = malloc(size);
2385         if (!result)
2386                 die_startup();
2387         return result;
2388 }
2389
2390 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2391 {
2392         len = xwcstoutf(buffer, wcs, len) + 1;
2393         return memcpy(malloc_startup(len), buffer, len);
2394 }
2395
2396 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2397                                       DWORD desired_access, DWORD flags)
2398 {
2399         DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2400         wchar_t buf[MAX_PATH];
2401         DWORD max = ARRAY_SIZE(buf);
2402         HANDLE handle;
2403         DWORD ret = GetEnvironmentVariableW(key, buf, max);
2404
2405         if (!ret || ret >= max)
2406                 return;
2407
2408         /* make sure this does not leak into child processes */
2409         SetEnvironmentVariableW(key, NULL);
2410         if (!wcscmp(buf, L"off")) {
2411                 close(fd);
2412                 handle = GetStdHandle(std_id);
2413                 if (handle != INVALID_HANDLE_VALUE)
2414                         CloseHandle(handle);
2415                 return;
2416         }
2417         if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2418                 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2419                 if (handle == INVALID_HANDLE_VALUE) {
2420                         close(fd);
2421                         handle = GetStdHandle(std_id);
2422                         if (handle != INVALID_HANDLE_VALUE)
2423                                 CloseHandle(handle);
2424                 } else {
2425                         int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2426                         SetStdHandle(std_id, handle);
2427                         dup2(new_fd, fd);
2428                         /* do *not* close the new_fd: that would close stdout */
2429                 }
2430                 return;
2431         }
2432         handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2433                              flags, NULL);
2434         if (handle != INVALID_HANDLE_VALUE) {
2435                 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2436                 SetStdHandle(std_id, handle);
2437                 dup2(new_fd, fd);
2438                 close(new_fd);
2439         }
2440 }
2441
2442 static void maybe_redirect_std_handles(void)
2443 {
2444         maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2445                                   GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2446         maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2447                                   GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2448         maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2449                                   GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2450 }
2451
2452 #ifdef _MSC_VER
2453 #ifdef _DEBUG
2454 #include <crtdbg.h>
2455 #endif
2456 #endif
2457
2458 /*
2459  * We implement wmain() and compile with -municode, which would
2460  * normally ignore main(), but we call the latter from the former
2461  * so that we can handle non-ASCII command-line parameters
2462  * appropriately.
2463  *
2464  * To be more compatible with the core git code, we convert
2465  * argv into UTF8 and pass them directly to main().
2466  */
2467 int wmain(int argc, const wchar_t **wargv)
2468 {
2469         int i, maxlen, exit_status;
2470         char *buffer, **save;
2471         const char **argv;
2472
2473         trace2_initialize_clock();
2474
2475 #ifdef _MSC_VER
2476 #ifdef _DEBUG
2477         _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2478 #endif
2479
2480 #ifdef USE_MSVC_CRTDBG
2481         _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2482 #endif
2483 #endif
2484
2485         maybe_redirect_std_handles();
2486
2487         /* determine size of argv and environ conversion buffer */
2488         maxlen = wcslen(wargv[0]);
2489         for (i = 1; i < argc; i++)
2490                 maxlen = max(maxlen, wcslen(wargv[i]));
2491
2492         /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2493         maxlen = 3 * maxlen + 1;
2494         buffer = malloc_startup(maxlen);
2495
2496         /*
2497          * Create a UTF-8 version of w_argv. Also create a "save" copy
2498          * to remember all the string pointers because parse_options()
2499          * will remove claimed items from the argv that we pass down.
2500          */
2501         ALLOC_ARRAY(argv, argc + 1);
2502         ALLOC_ARRAY(save, argc + 1);
2503         for (i = 0; i < argc; i++)
2504                 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2505         argv[i] = save[i] = NULL;
2506         free(buffer);
2507
2508         /* fix Windows specific environment settings */
2509         setup_windows_environment();
2510
2511         unset_environment_variables = xstrdup("PERL5LIB");
2512
2513         /* initialize critical section for waitpid pinfo_t list */
2514         InitializeCriticalSection(&pinfo_cs);
2515
2516         /* set up default file mode and file modes for stdin/out/err */
2517         _fmode = _O_BINARY;
2518         _setmode(_fileno(stdin), _O_BINARY);
2519         _setmode(_fileno(stdout), _O_BINARY);
2520         _setmode(_fileno(stderr), _O_BINARY);
2521
2522         /* initialize Unicode console */
2523         winansi_init();
2524
2525         /* invoke the real main() using our utf8 version of argv. */
2526         exit_status = main(argc, argv);
2527
2528         for (i = 0; i < argc; i++)
2529                 free(save[i]);
2530         free(save);
2531         free(argv);
2532
2533         return exit_status;
2534 }
2535
2536 int uname(struct utsname *buf)
2537 {
2538         unsigned v = (unsigned)GetVersion();
2539         memset(buf, 0, sizeof(*buf));
2540         xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2541         xsnprintf(buf->release, sizeof(buf->release),
2542                  "%u.%u", v & 0xff, (v >> 8) & 0xff);
2543         /* assuming NT variants only.. */
2544         xsnprintf(buf->version, sizeof(buf->version),
2545                   "%u", (v >> 16) & 0x7fff);
2546         return 0;
2547 }