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