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