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