Code

mingw: work around irregular failures of unlink on windows
[git.git] / compat / mingw.c
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include "../strbuf.h"
6 static const int delay[] = { 0, 1, 10, 20, 40 };
8 int err_win_to_posix(DWORD winerr)
9 {
10         int error = ENOSYS;
11         switch(winerr) {
12         case ERROR_ACCESS_DENIED: error = EACCES; break;
13         case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
14         case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
15         case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
16         case ERROR_ALREADY_EXISTS: error = EEXIST; break;
17         case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
18         case ERROR_BAD_COMMAND: error = EIO; break;
19         case ERROR_BAD_DEVICE: error = ENODEV; break;
20         case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
21         case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
22         case ERROR_BAD_FORMAT: error = ENOEXEC; break;
23         case ERROR_BAD_LENGTH: error = EINVAL; break;
24         case ERROR_BAD_PATHNAME: error = ENOENT; break;
25         case ERROR_BAD_PIPE: error = EPIPE; break;
26         case ERROR_BAD_UNIT: error = ENODEV; break;
27         case ERROR_BAD_USERNAME: error = EINVAL; break;
28         case ERROR_BROKEN_PIPE: error = EPIPE; break;
29         case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
30         case ERROR_BUSY: error = EBUSY; break;
31         case ERROR_BUSY_DRIVE: error = EBUSY; break;
32         case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
33         case ERROR_CANNOT_MAKE: error = EACCES; break;
34         case ERROR_CANTOPEN: error = EIO; break;
35         case ERROR_CANTREAD: error = EIO; break;
36         case ERROR_CANTWRITE: error = EIO; break;
37         case ERROR_CRC: error = EIO; break;
38         case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
39         case ERROR_DEVICE_IN_USE: error = EBUSY; break;
40         case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
41         case ERROR_DIRECTORY: error = EINVAL; break;
42         case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
43         case ERROR_DISK_CHANGE: error = EIO; break;
44         case ERROR_DISK_FULL: error = ENOSPC; break;
45         case ERROR_DRIVE_LOCKED: error = EBUSY; break;
46         case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
47         case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
48         case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
49         case ERROR_FILE_EXISTS: error = EEXIST; break;
50         case ERROR_FILE_INVALID: error = ENODEV; break;
51         case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
52         case ERROR_GEN_FAILURE: error = EIO; break;
53         case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
54         case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
55         case ERROR_INVALID_ACCESS: error = EACCES; break;
56         case ERROR_INVALID_ADDRESS: error = EFAULT; break;
57         case ERROR_INVALID_BLOCK: error = EFAULT; break;
58         case ERROR_INVALID_DATA: error = EINVAL; break;
59         case ERROR_INVALID_DRIVE: error = ENODEV; break;
60         case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
61         case ERROR_INVALID_FLAGS: error = EINVAL; break;
62         case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
63         case ERROR_INVALID_HANDLE: error = EBADF; break;
64         case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
65         case ERROR_INVALID_NAME: error = EINVAL; break;
66         case ERROR_INVALID_OWNER: error = EINVAL; break;
67         case ERROR_INVALID_PARAMETER: error = EINVAL; break;
68         case ERROR_INVALID_PASSWORD: error = EPERM; break;
69         case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
70         case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
71         case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
72         case ERROR_INVALID_WORKSTATION: error = EACCES; break;
73         case ERROR_IO_DEVICE: error = EIO; break;
74         case ERROR_IO_INCOMPLETE: error = EINTR; break;
75         case ERROR_LOCKED: error = EBUSY; break;
76         case ERROR_LOCK_VIOLATION: error = EACCES; break;
77         case ERROR_LOGON_FAILURE: error = EACCES; break;
78         case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
79         case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
80         case ERROR_MORE_DATA: error = EPIPE; break;
81         case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
82         case ERROR_NOACCESS: error = EFAULT; break;
83         case ERROR_NONE_MAPPED: error = EINVAL; break;
84         case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
85         case ERROR_NOT_READY: error = EAGAIN; break;
86         case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
87         case ERROR_NO_DATA: error = EPIPE; break;
88         case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
89         case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
90         case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
91         case ERROR_OPEN_FAILED: error = EIO; break;
92         case ERROR_OPEN_FILES: error = EBUSY; break;
93         case ERROR_OPERATION_ABORTED: error = EINTR; break;
94         case ERROR_OUTOFMEMORY: error = ENOMEM; break;
95         case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
96         case ERROR_PATH_BUSY: error = EBUSY; break;
97         case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
98         case ERROR_PIPE_BUSY: error = EBUSY; break;
99         case ERROR_PIPE_CONNECTED: error = EPIPE; break;
100         case ERROR_PIPE_LISTENING: error = EPIPE; break;
101         case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
102         case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
103         case ERROR_READ_FAULT: error = EIO; break;
104         case ERROR_SEEK: error = EIO; break;
105         case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
106         case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
107         case ERROR_SHARING_VIOLATION: error = EACCES; break;
108         case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
109         case ERROR_SWAPERROR: error = ENOENT; break;
110         case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
111         case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
112         case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
113         case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
114         case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
115         case ERROR_WRITE_FAULT: error = EIO; break;
116         case ERROR_WRITE_PROTECT: error = EROFS; break;
117         }
118         return error;
121 static inline int is_file_in_use_error(DWORD errcode)
123         switch (errcode) {
124         case ERROR_SHARING_VIOLATION:
125         case ERROR_ACCESS_DENIED:
126                 return 1;
127         }
129         return 0;
132 #undef unlink
133 int mingw_unlink(const char *pathname)
135         int ret, tries = 0;
137         /* read-only files cannot be removed */
138         chmod(pathname, 0666);
139         while ((ret = unlink(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
140                 if (!is_file_in_use_error(GetLastError()))
141                         break;
142                 /*
143                  * We assume that some other process had the source or
144                  * destination file open at the wrong moment and retry.
145                  * In order to give the other process a higher chance to
146                  * complete its operation, we give up our time slice now.
147                  * If we have to retry again, we do sleep a bit.
148                  */
149                 Sleep(delay[tries]);
150                 tries++;
151         }
152         return ret;
155 #undef open
156 int mingw_open (const char *filename, int oflags, ...)
158         va_list args;
159         unsigned mode;
160         int fd;
162         va_start(args, oflags);
163         mode = va_arg(args, int);
164         va_end(args);
166         if (filename && !strcmp(filename, "/dev/null"))
167                 filename = "nul";
169         fd = open(filename, oflags, mode);
171         if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
172                 DWORD attrs = GetFileAttributes(filename);
173                 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
174                         errno = EISDIR;
175         }
176         return fd;
179 #undef write
180 ssize_t mingw_write(int fd, const void *buf, size_t count)
182         /*
183          * While write() calls to a file on a local disk are translated
184          * into WriteFile() calls with a maximum size of 64KB on Windows
185          * XP and 256KB on Vista, no such cap is placed on writes to
186          * files over the network on Windows XP.  Unfortunately, there
187          * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
188          * bigger writes fail on Windows XP.
189          * So we cap to a nice 31MB here to avoid write failures over
190          * the net without changing the number of WriteFile() calls in
191          * the local case.
192          */
193         return write(fd, buf, min(count, 31 * 1024 * 1024));
196 #undef fopen
197 FILE *mingw_fopen (const char *filename, const char *otype)
199         if (filename && !strcmp(filename, "/dev/null"))
200                 filename = "nul";
201         return fopen(filename, otype);
204 #undef freopen
205 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
207         if (filename && !strcmp(filename, "/dev/null"))
208                 filename = "nul";
209         return freopen(filename, otype, stream);
212 /*
213  * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
214  * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
215  */
216 static inline long long filetime_to_hnsec(const FILETIME *ft)
218         long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
219         /* Windows to Unix Epoch conversion */
220         return winTime - 116444736000000000LL;
223 static inline time_t filetime_to_time_t(const FILETIME *ft)
225         return (time_t)(filetime_to_hnsec(ft) / 10000000);
228 /* We keep the do_lstat code in a separate function to avoid recursion.
229  * When a path ends with a slash, the stat will fail with ENOENT. In
230  * this case, we strip the trailing slashes and stat again.
231  *
232  * If follow is true then act like stat() and report on the link
233  * target. Otherwise report on the link itself.
234  */
235 static int do_lstat(int follow, const char *file_name, struct stat *buf)
237         int err;
238         WIN32_FILE_ATTRIBUTE_DATA fdata;
240         if (!(err = get_file_attr(file_name, &fdata))) {
241                 buf->st_ino = 0;
242                 buf->st_gid = 0;
243                 buf->st_uid = 0;
244                 buf->st_nlink = 1;
245                 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
246                 buf->st_size = fdata.nFileSizeLow |
247                         (((off_t)fdata.nFileSizeHigh)<<32);
248                 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
249                 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
250                 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
251                 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
252                 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
253                         WIN32_FIND_DATAA findbuf;
254                         HANDLE handle = FindFirstFileA(file_name, &findbuf);
255                         if (handle != INVALID_HANDLE_VALUE) {
256                                 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
257                                                 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
258                                         if (follow) {
259                                                 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
260                                                 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
261                                         } else {
262                                                 buf->st_mode = S_IFLNK;
263                                         }
264                                         buf->st_mode |= S_IREAD;
265                                         if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
266                                                 buf->st_mode |= S_IWRITE;
267                                 }
268                                 FindClose(handle);
269                         }
270                 }
271                 return 0;
272         }
273         errno = err;
274         return -1;
277 /* We provide our own lstat/fstat functions, since the provided
278  * lstat/fstat functions are so slow. These stat functions are
279  * tailored for Git's usage (read: fast), and are not meant to be
280  * complete. Note that Git stat()s are redirected to mingw_lstat()
281  * too, since Windows doesn't really handle symlinks that well.
282  */
283 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
285         int namelen;
286         static char alt_name[PATH_MAX];
288         if (!do_lstat(follow, file_name, buf))
289                 return 0;
291         /* if file_name ended in a '/', Windows returned ENOENT;
292          * try again without trailing slashes
293          */
294         if (errno != ENOENT)
295                 return -1;
297         namelen = strlen(file_name);
298         if (namelen && file_name[namelen-1] != '/')
299                 return -1;
300         while (namelen && file_name[namelen-1] == '/')
301                 --namelen;
302         if (!namelen || namelen >= PATH_MAX)
303                 return -1;
305         memcpy(alt_name, file_name, namelen);
306         alt_name[namelen] = 0;
307         return do_lstat(follow, alt_name, buf);
310 int mingw_lstat(const char *file_name, struct stat *buf)
312         return do_stat_internal(0, file_name, buf);
314 int mingw_stat(const char *file_name, struct stat *buf)
316         return do_stat_internal(1, file_name, buf);
319 #undef fstat
320 int mingw_fstat(int fd, struct stat *buf)
322         HANDLE fh = (HANDLE)_get_osfhandle(fd);
323         BY_HANDLE_FILE_INFORMATION fdata;
325         if (fh == INVALID_HANDLE_VALUE) {
326                 errno = EBADF;
327                 return -1;
328         }
329         /* direct non-file handles to MS's fstat() */
330         if (GetFileType(fh) != FILE_TYPE_DISK)
331                 return _fstati64(fd, buf);
333         if (GetFileInformationByHandle(fh, &fdata)) {
334                 buf->st_ino = 0;
335                 buf->st_gid = 0;
336                 buf->st_uid = 0;
337                 buf->st_nlink = 1;
338                 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
339                 buf->st_size = fdata.nFileSizeLow |
340                         (((off_t)fdata.nFileSizeHigh)<<32);
341                 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
342                 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
343                 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
344                 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
345                 return 0;
346         }
347         errno = EBADF;
348         return -1;
351 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
353         long long winTime = t * 10000000LL + 116444736000000000LL;
354         ft->dwLowDateTime = winTime;
355         ft->dwHighDateTime = winTime >> 32;
358 int mingw_utime (const char *file_name, const struct utimbuf *times)
360         FILETIME mft, aft;
361         int fh, rc;
363         /* must have write permission */
364         DWORD attrs = GetFileAttributes(file_name);
365         if (attrs != INVALID_FILE_ATTRIBUTES &&
366             (attrs & FILE_ATTRIBUTE_READONLY)) {
367                 /* ignore errors here; open() will report them */
368                 SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
369         }
371         if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
372                 rc = -1;
373                 goto revert_attrs;
374         }
376         if (times) {
377                 time_t_to_filetime(times->modtime, &mft);
378                 time_t_to_filetime(times->actime, &aft);
379         } else {
380                 GetSystemTimeAsFileTime(&mft);
381                 aft = mft;
382         }
383         if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
384                 errno = EINVAL;
385                 rc = -1;
386         } else
387                 rc = 0;
388         close(fh);
390 revert_attrs:
391         if (attrs != INVALID_FILE_ATTRIBUTES &&
392             (attrs & FILE_ATTRIBUTE_READONLY)) {
393                 /* ignore errors again */
394                 SetFileAttributes(file_name, attrs);
395         }
396         return rc;
399 unsigned int sleep (unsigned int seconds)
401         Sleep(seconds*1000);
402         return 0;
405 int mkstemp(char *template)
407         char *filename = mktemp(template);
408         if (filename == NULL)
409                 return -1;
410         return open(filename, O_RDWR | O_CREAT, 0600);
413 int gettimeofday(struct timeval *tv, void *tz)
415         FILETIME ft;
416         long long hnsec;
418         GetSystemTimeAsFileTime(&ft);
419         hnsec = filetime_to_hnsec(&ft);
420         tv->tv_sec = hnsec / 10000000;
421         tv->tv_usec = (hnsec % 10000000) / 10;
422         return 0;
425 int pipe(int filedes[2])
427         HANDLE h[2];
429         /* this creates non-inheritable handles */
430         if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
431                 errno = err_win_to_posix(GetLastError());
432                 return -1;
433         }
434         filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
435         if (filedes[0] < 0) {
436                 CloseHandle(h[0]);
437                 CloseHandle(h[1]);
438                 return -1;
439         }
440         filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
441         if (filedes[0] < 0) {
442                 close(filedes[0]);
443                 CloseHandle(h[1]);
444                 return -1;
445         }
446         return 0;
449 struct tm *gmtime_r(const time_t *timep, struct tm *result)
451         /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
452         memcpy(result, gmtime(timep), sizeof(struct tm));
453         return result;
456 struct tm *localtime_r(const time_t *timep, struct tm *result)
458         /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
459         memcpy(result, localtime(timep), sizeof(struct tm));
460         return result;
463 #undef getcwd
464 char *mingw_getcwd(char *pointer, int len)
466         int i;
467         char *ret = getcwd(pointer, len);
468         if (!ret)
469                 return ret;
470         for (i = 0; pointer[i]; i++)
471                 if (pointer[i] == '\\')
472                         pointer[i] = '/';
473         return ret;
476 #undef getenv
477 char *mingw_getenv(const char *name)
479         char *result = getenv(name);
480         if (!result && !strcmp(name, "TMPDIR")) {
481                 /* on Windows it is TMP and TEMP */
482                 result = getenv("TMP");
483                 if (!result)
484                         result = getenv("TEMP");
485         }
486         return result;
489 /*
490  * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
491  * (Parsing C++ Command-Line Arguments)
492  */
493 static const char *quote_arg(const char *arg)
495         /* count chars to quote */
496         int len = 0, n = 0;
497         int force_quotes = 0;
498         char *q, *d;
499         const char *p = arg;
500         if (!*p) force_quotes = 1;
501         while (*p) {
502                 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
503                         force_quotes = 1;
504                 else if (*p == '"')
505                         n++;
506                 else if (*p == '\\') {
507                         int count = 0;
508                         while (*p == '\\') {
509                                 count++;
510                                 p++;
511                                 len++;
512                         }
513                         if (*p == '"')
514                                 n += count*2 + 1;
515                         continue;
516                 }
517                 len++;
518                 p++;
519         }
520         if (!force_quotes && n == 0)
521                 return arg;
523         /* insert \ where necessary */
524         d = q = xmalloc(len+n+3);
525         *d++ = '"';
526         while (*arg) {
527                 if (*arg == '"')
528                         *d++ = '\\';
529                 else if (*arg == '\\') {
530                         int count = 0;
531                         while (*arg == '\\') {
532                                 count++;
533                                 *d++ = *arg++;
534                         }
535                         if (*arg == '"') {
536                                 while (count-- > 0)
537                                         *d++ = '\\';
538                                 *d++ = '\\';
539                         }
540                 }
541                 *d++ = *arg++;
542         }
543         *d++ = '"';
544         *d++ = 0;
545         return q;
548 static const char *parse_interpreter(const char *cmd)
550         static char buf[100];
551         char *p, *opt;
552         int n, fd;
554         /* don't even try a .exe */
555         n = strlen(cmd);
556         if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
557                 return NULL;
559         fd = open(cmd, O_RDONLY);
560         if (fd < 0)
561                 return NULL;
562         n = read(fd, buf, sizeof(buf)-1);
563         close(fd);
564         if (n < 4)      /* at least '#!/x' and not error */
565                 return NULL;
567         if (buf[0] != '#' || buf[1] != '!')
568                 return NULL;
569         buf[n] = '\0';
570         p = buf + strcspn(buf, "\r\n");
571         if (!*p)
572                 return NULL;
574         *p = '\0';
575         if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
576                 return NULL;
577         /* strip options */
578         if ((opt = strchr(p+1, ' ')))
579                 *opt = '\0';
580         return p+1;
583 /*
584  * Splits the PATH into parts.
585  */
586 static char **get_path_split(void)
588         char *p, **path, *envpath = getenv("PATH");
589         int i, n = 0;
591         if (!envpath || !*envpath)
592                 return NULL;
594         envpath = xstrdup(envpath);
595         p = envpath;
596         while (p) {
597                 char *dir = p;
598                 p = strchr(p, ';');
599                 if (p) *p++ = '\0';
600                 if (*dir) {     /* not earlier, catches series of ; */
601                         ++n;
602                 }
603         }
604         if (!n)
605                 return NULL;
607         path = xmalloc((n+1)*sizeof(char *));
608         p = envpath;
609         i = 0;
610         do {
611                 if (*p)
612                         path[i++] = xstrdup(p);
613                 p = p+strlen(p)+1;
614         } while (i < n);
615         path[i] = NULL;
617         free(envpath);
619         return path;
622 static void free_path_split(char **path)
624         char **p = path;
626         if (!path)
627                 return;
629         while (*p)
630                 free(*p++);
631         free(path);
634 /*
635  * exe_only means that we only want to detect .exe files, but not scripts
636  * (which do not have an extension)
637  */
638 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
640         char path[MAX_PATH];
641         snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
643         if (!isexe && access(path, F_OK) == 0)
644                 return xstrdup(path);
645         path[strlen(path)-4] = '\0';
646         if ((!exe_only || isexe) && access(path, F_OK) == 0)
647                 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
648                         return xstrdup(path);
649         return NULL;
652 /*
653  * Determines the absolute path of cmd using the split path in path.
654  * If cmd contains a slash or backslash, no lookup is performed.
655  */
656 static char *path_lookup(const char *cmd, char **path, int exe_only)
658         char *prog = NULL;
659         int len = strlen(cmd);
660         int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
662         if (strchr(cmd, '/') || strchr(cmd, '\\'))
663                 prog = xstrdup(cmd);
665         while (!prog && *path)
666                 prog = lookup_prog(*path++, cmd, isexe, exe_only);
668         return prog;
671 static int env_compare(const void *a, const void *b)
673         char *const *ea = a;
674         char *const *eb = b;
675         return strcasecmp(*ea, *eb);
678 struct pinfo_t {
679         struct pinfo_t *next;
680         pid_t pid;
681         HANDLE proc;
682 } pinfo_t;
683 struct pinfo_t *pinfo = NULL;
684 CRITICAL_SECTION pinfo_cs;
686 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
687                               const char *dir,
688                               int prepend_cmd, int fhin, int fhout, int fherr)
690         STARTUPINFO si;
691         PROCESS_INFORMATION pi;
692         struct strbuf envblk, args;
693         unsigned flags;
694         BOOL ret;
696         /* Determine whether or not we are associated to a console */
697         HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
698                         FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
699                         FILE_ATTRIBUTE_NORMAL, NULL);
700         if (cons == INVALID_HANDLE_VALUE) {
701                 /* There is no console associated with this process.
702                  * Since the child is a console process, Windows
703                  * would normally create a console window. But
704                  * since we'll be redirecting std streams, we do
705                  * not need the console.
706                  * It is necessary to use DETACHED_PROCESS
707                  * instead of CREATE_NO_WINDOW to make ssh
708                  * recognize that it has no console.
709                  */
710                 flags = DETACHED_PROCESS;
711         } else {
712                 /* There is already a console. If we specified
713                  * DETACHED_PROCESS here, too, Windows would
714                  * disassociate the child from the console.
715                  * The same is true for CREATE_NO_WINDOW.
716                  * Go figure!
717                  */
718                 flags = 0;
719                 CloseHandle(cons);
720         }
721         memset(&si, 0, sizeof(si));
722         si.cb = sizeof(si);
723         si.dwFlags = STARTF_USESTDHANDLES;
724         si.hStdInput = (HANDLE) _get_osfhandle(fhin);
725         si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
726         si.hStdError = (HANDLE) _get_osfhandle(fherr);
728         /* concatenate argv, quoting args as we go */
729         strbuf_init(&args, 0);
730         if (prepend_cmd) {
731                 char *quoted = (char *)quote_arg(cmd);
732                 strbuf_addstr(&args, quoted);
733                 if (quoted != cmd)
734                         free(quoted);
735         }
736         for (; *argv; argv++) {
737                 char *quoted = (char *)quote_arg(*argv);
738                 if (*args.buf)
739                         strbuf_addch(&args, ' ');
740                 strbuf_addstr(&args, quoted);
741                 if (quoted != *argv)
742                         free(quoted);
743         }
745         if (env) {
746                 int count = 0;
747                 char **e, **sorted_env;
749                 for (e = env; *e; e++)
750                         count++;
752                 /* environment must be sorted */
753                 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
754                 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
755                 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
757                 strbuf_init(&envblk, 0);
758                 for (e = sorted_env; *e; e++) {
759                         strbuf_addstr(&envblk, *e);
760                         strbuf_addch(&envblk, '\0');
761                 }
762                 free(sorted_env);
763         }
765         memset(&pi, 0, sizeof(pi));
766         ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
767                 env ? envblk.buf : NULL, dir, &si, &pi);
769         if (env)
770                 strbuf_release(&envblk);
771         strbuf_release(&args);
773         if (!ret) {
774                 errno = ENOENT;
775                 return -1;
776         }
777         CloseHandle(pi.hThread);
779         /*
780          * The process ID is the human-readable identifier of the process
781          * that we want to present in log and error messages. The handle
782          * is not useful for this purpose. But we cannot close it, either,
783          * because it is not possible to turn a process ID into a process
784          * handle after the process terminated.
785          * Keep the handle in a list for waitpid.
786          */
787         EnterCriticalSection(&pinfo_cs);
788         {
789                 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
790                 info->pid = pi.dwProcessId;
791                 info->proc = pi.hProcess;
792                 info->next = pinfo;
793                 pinfo = info;
794         }
795         LeaveCriticalSection(&pinfo_cs);
797         return (pid_t)pi.dwProcessId;
800 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
801                            int prepend_cmd)
803         return mingw_spawnve_fd(cmd, argv, env, NULL, prepend_cmd, 0, 1, 2);
806 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
807                      const char *dir,
808                      int fhin, int fhout, int fherr)
810         pid_t pid;
811         char **path = get_path_split();
812         char *prog = path_lookup(cmd, path, 0);
814         if (!prog) {
815                 errno = ENOENT;
816                 pid = -1;
817         }
818         else {
819                 const char *interpr = parse_interpreter(prog);
821                 if (interpr) {
822                         const char *argv0 = argv[0];
823                         char *iprog = path_lookup(interpr, path, 1);
824                         argv[0] = prog;
825                         if (!iprog) {
826                                 errno = ENOENT;
827                                 pid = -1;
828                         }
829                         else {
830                                 pid = mingw_spawnve_fd(iprog, argv, env, dir, 1,
831                                                        fhin, fhout, fherr);
832                                 free(iprog);
833                         }
834                         argv[0] = argv0;
835                 }
836                 else
837                         pid = mingw_spawnve_fd(prog, argv, env, dir, 0,
838                                                fhin, fhout, fherr);
839                 free(prog);
840         }
841         free_path_split(path);
842         return pid;
845 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
847         const char *interpr = parse_interpreter(cmd);
848         char **path;
849         char *prog;
850         int pid = 0;
852         if (!interpr)
853                 return 0;
854         path = get_path_split();
855         prog = path_lookup(interpr, path, 1);
856         if (prog) {
857                 int argc = 0;
858                 const char **argv2;
859                 while (argv[argc]) argc++;
860                 argv2 = xmalloc(sizeof(*argv) * (argc+1));
861                 argv2[0] = (char *)cmd; /* full path to the script file */
862                 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
863                 pid = mingw_spawnve(prog, argv2, env, 1);
864                 if (pid >= 0) {
865                         int status;
866                         if (waitpid(pid, &status, 0) < 0)
867                                 status = 255;
868                         exit(status);
869                 }
870                 pid = 1;        /* indicate that we tried but failed */
871                 free(prog);
872                 free(argv2);
873         }
874         free_path_split(path);
875         return pid;
878 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
880         /* check if git_command is a shell script */
881         if (!try_shell_exec(cmd, argv, (char **)env)) {
882                 int pid, status;
884                 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
885                 if (pid < 0)
886                         return;
887                 if (waitpid(pid, &status, 0) < 0)
888                         status = 255;
889                 exit(status);
890         }
893 void mingw_execvp(const char *cmd, char *const *argv)
895         char **path = get_path_split();
896         char *prog = path_lookup(cmd, path, 0);
898         if (prog) {
899                 mingw_execve(prog, argv, environ);
900                 free(prog);
901         } else
902                 errno = ENOENT;
904         free_path_split(path);
907 void mingw_execv(const char *cmd, char *const *argv)
909         mingw_execve(cmd, argv, environ);
912 int mingw_kill(pid_t pid, int sig)
914         if (pid > 0 && sig == SIGTERM) {
915                 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
917                 if (TerminateProcess(h, -1)) {
918                         CloseHandle(h);
919                         return 0;
920                 }
922                 errno = err_win_to_posix(GetLastError());
923                 CloseHandle(h);
924                 return -1;
925         }
927         errno = EINVAL;
928         return -1;
931 static char **copy_environ(void)
933         char **env;
934         int i = 0;
935         while (environ[i])
936                 i++;
937         env = xmalloc((i+1)*sizeof(*env));
938         for (i = 0; environ[i]; i++)
939                 env[i] = xstrdup(environ[i]);
940         env[i] = NULL;
941         return env;
944 void free_environ(char **env)
946         int i;
947         for (i = 0; env[i]; i++)
948                 free(env[i]);
949         free(env);
952 static int lookup_env(char **env, const char *name, size_t nmln)
954         int i;
956         for (i = 0; env[i]; i++) {
957                 if (0 == strncmp(env[i], name, nmln)
958                     && '=' == env[i][nmln])
959                         /* matches */
960                         return i;
961         }
962         return -1;
965 /*
966  * If name contains '=', then sets the variable, otherwise it unsets it
967  */
968 static char **env_setenv(char **env, const char *name)
970         char *eq = strchrnul(name, '=');
971         int i = lookup_env(env, name, eq-name);
973         if (i < 0) {
974                 if (*eq) {
975                         for (i = 0; env[i]; i++)
976                                 ;
977                         env = xrealloc(env, (i+2)*sizeof(*env));
978                         env[i] = xstrdup(name);
979                         env[i+1] = NULL;
980                 }
981         }
982         else {
983                 free(env[i]);
984                 if (*eq)
985                         env[i] = xstrdup(name);
986                 else
987                         for (; env[i]; i++)
988                                 env[i] = env[i+1];
989         }
990         return env;
993 /*
994  * Copies global environ and adjusts variables as specified by vars.
995  */
996 char **make_augmented_environ(const char *const *vars)
998         char **env = copy_environ();
1000         while (*vars)
1001                 env = env_setenv(env, *vars++);
1002         return env;
1005 /*
1006  * Note, this isn't a complete replacement for getaddrinfo. It assumes
1007  * that service contains a numerical port, or that it it is null. It
1008  * does a simple search using gethostbyname, and returns one IPv4 host
1009  * if one was found.
1010  */
1011 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1012                                    const struct addrinfo *hints,
1013                                    struct addrinfo **res)
1015         struct hostent *h = NULL;
1016         struct addrinfo *ai;
1017         struct sockaddr_in *sin;
1019         if (node) {
1020                 h = gethostbyname(node);
1021                 if (!h)
1022                         return WSAGetLastError();
1023         }
1025         ai = xmalloc(sizeof(struct addrinfo));
1026         *res = ai;
1027         ai->ai_flags = 0;
1028         ai->ai_family = AF_INET;
1029         ai->ai_socktype = hints ? hints->ai_socktype : 0;
1030         switch (ai->ai_socktype) {
1031         case SOCK_STREAM:
1032                 ai->ai_protocol = IPPROTO_TCP;
1033                 break;
1034         case SOCK_DGRAM:
1035                 ai->ai_protocol = IPPROTO_UDP;
1036                 break;
1037         default:
1038                 ai->ai_protocol = 0;
1039                 break;
1040         }
1041         ai->ai_addrlen = sizeof(struct sockaddr_in);
1042         if (hints && (hints->ai_flags & AI_CANONNAME))
1043                 ai->ai_canonname = h ? strdup(h->h_name) : NULL;
1044         else
1045                 ai->ai_canonname = NULL;
1047         sin = xmalloc(ai->ai_addrlen);
1048         memset(sin, 0, ai->ai_addrlen);
1049         sin->sin_family = AF_INET;
1050         /* Note: getaddrinfo is supposed to allow service to be a string,
1051          * which should be looked up using getservbyname. This is
1052          * currently not implemented */
1053         if (service)
1054                 sin->sin_port = htons(atoi(service));
1055         if (h)
1056                 sin->sin_addr = *(struct in_addr *)h->h_addr;
1057         else if (hints && (hints->ai_flags & AI_PASSIVE))
1058                 sin->sin_addr.s_addr = INADDR_ANY;
1059         else
1060                 sin->sin_addr.s_addr = INADDR_LOOPBACK;
1061         ai->ai_addr = (struct sockaddr *)sin;
1062         ai->ai_next = 0;
1063         return 0;
1066 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1068         free(res->ai_canonname);
1069         free(res->ai_addr);
1070         free(res);
1073 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1074                                    char *host, DWORD hostlen,
1075                                    char *serv, DWORD servlen, int flags)
1077         const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1078         if (sa->sa_family != AF_INET)
1079                 return EAI_FAMILY;
1080         if (!host && !serv)
1081                 return EAI_NONAME;
1083         if (host && hostlen > 0) {
1084                 struct hostent *ent = NULL;
1085                 if (!(flags & NI_NUMERICHOST))
1086                         ent = gethostbyaddr((const char *)&sin->sin_addr,
1087                                             sizeof(sin->sin_addr), AF_INET);
1089                 if (ent)
1090                         snprintf(host, hostlen, "%s", ent->h_name);
1091                 else if (flags & NI_NAMEREQD)
1092                         return EAI_NONAME;
1093                 else
1094                         snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1095         }
1097         if (serv && servlen > 0) {
1098                 struct servent *ent = NULL;
1099                 if (!(flags & NI_NUMERICSERV))
1100                         ent = getservbyport(sin->sin_port,
1101                                             flags & NI_DGRAM ? "udp" : "tcp");
1103                 if (ent)
1104                         snprintf(serv, servlen, "%s", ent->s_name);
1105                 else
1106                         snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1107         }
1109         return 0;
1112 static HMODULE ipv6_dll = NULL;
1113 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1114 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1115                                       const struct addrinfo *hints,
1116                                       struct addrinfo **res);
1117 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1118                                       char *host, DWORD hostlen,
1119                                       char *serv, DWORD servlen, int flags);
1120 /*
1121  * gai_strerror is an inline function in the ws2tcpip.h header, so we
1122  * don't need to try to load that one dynamically.
1123  */
1125 static void socket_cleanup(void)
1127         WSACleanup();
1128         if (ipv6_dll)
1129                 FreeLibrary(ipv6_dll);
1130         ipv6_dll = NULL;
1131         ipv6_freeaddrinfo = freeaddrinfo_stub;
1132         ipv6_getaddrinfo = getaddrinfo_stub;
1133         ipv6_getnameinfo = getnameinfo_stub;
1136 static void ensure_socket_initialization(void)
1138         WSADATA wsa;
1139         static int initialized = 0;
1140         const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1141         const char **name;
1143         if (initialized)
1144                 return;
1146         if (WSAStartup(MAKEWORD(2,2), &wsa))
1147                 die("unable to initialize winsock subsystem, error %d",
1148                         WSAGetLastError());
1150         for (name = libraries; *name; name++) {
1151                 ipv6_dll = LoadLibrary(*name);
1152                 if (!ipv6_dll)
1153                         continue;
1155                 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1156                         GetProcAddress(ipv6_dll, "freeaddrinfo");
1157                 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1158                                                    const struct addrinfo *,
1159                                                    struct addrinfo **))
1160                         GetProcAddress(ipv6_dll, "getaddrinfo");
1161                 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1162                                                    socklen_t, char *, DWORD,
1163                                                    char *, DWORD, int))
1164                         GetProcAddress(ipv6_dll, "getnameinfo");
1165                 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1166                         FreeLibrary(ipv6_dll);
1167                         ipv6_dll = NULL;
1168                 } else
1169                         break;
1170         }
1171         if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1172                 ipv6_freeaddrinfo = freeaddrinfo_stub;
1173                 ipv6_getaddrinfo = getaddrinfo_stub;
1174                 ipv6_getnameinfo = getnameinfo_stub;
1175         }
1177         atexit(socket_cleanup);
1178         initialized = 1;
1181 #undef gethostbyname
1182 struct hostent *mingw_gethostbyname(const char *host)
1184         ensure_socket_initialization();
1185         return gethostbyname(host);
1188 void mingw_freeaddrinfo(struct addrinfo *res)
1190         ipv6_freeaddrinfo(res);
1193 int mingw_getaddrinfo(const char *node, const char *service,
1194                       const struct addrinfo *hints, struct addrinfo **res)
1196         ensure_socket_initialization();
1197         return ipv6_getaddrinfo(node, service, hints, res);
1200 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1201                       char *host, DWORD hostlen, char *serv, DWORD servlen,
1202                       int flags)
1204         ensure_socket_initialization();
1205         return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1208 int mingw_socket(int domain, int type, int protocol)
1210         int sockfd;
1211         SOCKET s;
1213         ensure_socket_initialization();
1214         s = WSASocket(domain, type, protocol, NULL, 0, 0);
1215         if (s == INVALID_SOCKET) {
1216                 /*
1217                  * WSAGetLastError() values are regular BSD error codes
1218                  * biased by WSABASEERR.
1219                  * However, strerror() does not know about networking
1220                  * specific errors, which are values beginning at 38 or so.
1221                  * Therefore, we choose to leave the biased error code
1222                  * in errno so that _if_ someone looks up the code somewhere,
1223                  * then it is at least the number that are usually listed.
1224                  */
1225                 errno = WSAGetLastError();
1226                 return -1;
1227         }
1228         /* convert into a file descriptor */
1229         if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1230                 closesocket(s);
1231                 return error("unable to make a socket file descriptor: %s",
1232                         strerror(errno));
1233         }
1234         return sockfd;
1237 #undef connect
1238 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1240         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1241         return connect(s, sa, sz);
1244 #undef bind
1245 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1247         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1248         return bind(s, sa, sz);
1251 #undef setsockopt
1252 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1254         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1255         return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1258 #undef listen
1259 int mingw_listen(int sockfd, int backlog)
1261         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1262         return listen(s, backlog);
1265 #undef accept
1266 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1268         int sockfd2;
1270         SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1271         SOCKET s2 = accept(s1, sa, sz);
1273         /* convert into a file descriptor */
1274         if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1275                 int err = errno;
1276                 closesocket(s2);
1277                 return error("unable to make a socket file descriptor: %s",
1278                         strerror(err));
1279         }
1280         return sockfd2;
1283 #undef rename
1284 int mingw_rename(const char *pold, const char *pnew)
1286         DWORD attrs, gle;
1287         int tries = 0;
1289         /*
1290          * Try native rename() first to get errno right.
1291          * It is based on MoveFile(), which cannot overwrite existing files.
1292          */
1293         if (!rename(pold, pnew))
1294                 return 0;
1295         if (errno != EEXIST)
1296                 return -1;
1297 repeat:
1298         if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1299                 return 0;
1300         /* TODO: translate more errors */
1301         gle = GetLastError();
1302         if (gle == ERROR_ACCESS_DENIED &&
1303             (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1304                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1305                         errno = EISDIR;
1306                         return -1;
1307                 }
1308                 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1309                     SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1310                         if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1311                                 return 0;
1312                         gle = GetLastError();
1313                         /* revert file attributes on failure */
1314                         SetFileAttributes(pnew, attrs);
1315                 }
1316         }
1317         if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1318                 /*
1319                  * We assume that some other process had the source or
1320                  * destination file open at the wrong moment and retry.
1321                  * In order to give the other process a higher chance to
1322                  * complete its operation, we give up our time slice now.
1323                  * If we have to retry again, we do sleep a bit.
1324                  */
1325                 Sleep(delay[tries]);
1326                 tries++;
1327                 goto repeat;
1328         }
1329         errno = EACCES;
1330         return -1;
1333 /*
1334  * Note that this doesn't return the actual pagesize, but
1335  * the allocation granularity. If future Windows specific git code
1336  * needs the real getpagesize function, we need to find another solution.
1337  */
1338 int mingw_getpagesize(void)
1340         SYSTEM_INFO si;
1341         GetSystemInfo(&si);
1342         return si.dwAllocationGranularity;
1345 struct passwd *getpwuid(int uid)
1347         static char user_name[100];
1348         static struct passwd p;
1350         DWORD len = sizeof(user_name);
1351         if (!GetUserName(user_name, &len))
1352                 return NULL;
1353         p.pw_name = user_name;
1354         p.pw_gecos = "unknown";
1355         p.pw_dir = NULL;
1356         return &p;
1359 static HANDLE timer_event;
1360 static HANDLE timer_thread;
1361 static int timer_interval;
1362 static int one_shot;
1363 static sig_handler_t timer_fn = SIG_DFL;
1365 /* The timer works like this:
1366  * The thread, ticktack(), is a trivial routine that most of the time
1367  * only waits to receive the signal to terminate. The main thread tells
1368  * the thread to terminate by setting the timer_event to the signalled
1369  * state.
1370  * But ticktack() interrupts the wait state after the timer's interval
1371  * length to call the signal handler.
1372  */
1374 static unsigned __stdcall ticktack(void *dummy)
1376         while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1377                 if (timer_fn == SIG_DFL)
1378                         die("Alarm");
1379                 if (timer_fn != SIG_IGN)
1380                         timer_fn(SIGALRM);
1381                 if (one_shot)
1382                         break;
1383         }
1384         return 0;
1387 static int start_timer_thread(void)
1389         timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1390         if (timer_event) {
1391                 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1392                 if (!timer_thread )
1393                         return errno = ENOMEM,
1394                                 error("cannot start timer thread");
1395         } else
1396                 return errno = ENOMEM,
1397                         error("cannot allocate resources for timer");
1398         return 0;
1401 static void stop_timer_thread(void)
1403         if (timer_event)
1404                 SetEvent(timer_event);  /* tell thread to terminate */
1405         if (timer_thread) {
1406                 int rc = WaitForSingleObject(timer_thread, 1000);
1407                 if (rc == WAIT_TIMEOUT)
1408                         error("timer thread did not terminate timely");
1409                 else if (rc != WAIT_OBJECT_0)
1410                         error("waiting for timer thread failed: %lu",
1411                               GetLastError());
1412                 CloseHandle(timer_thread);
1413         }
1414         if (timer_event)
1415                 CloseHandle(timer_event);
1416         timer_event = NULL;
1417         timer_thread = NULL;
1420 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1422         return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1425 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1427         static const struct timeval zero;
1428         static int atexit_done;
1430         if (out != NULL)
1431                 return errno = EINVAL,
1432                         error("setitimer param 3 != NULL not implemented");
1433         if (!is_timeval_eq(&in->it_interval, &zero) &&
1434             !is_timeval_eq(&in->it_interval, &in->it_value))
1435                 return errno = EINVAL,
1436                         error("setitimer: it_interval must be zero or eq it_value");
1438         if (timer_thread)
1439                 stop_timer_thread();
1441         if (is_timeval_eq(&in->it_value, &zero) &&
1442             is_timeval_eq(&in->it_interval, &zero))
1443                 return 0;
1445         timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1446         one_shot = is_timeval_eq(&in->it_interval, &zero);
1447         if (!atexit_done) {
1448                 atexit(stop_timer_thread);
1449                 atexit_done = 1;
1450         }
1451         return start_timer_thread();
1454 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1456         if (sig != SIGALRM)
1457                 return errno = EINVAL,
1458                         error("sigaction only implemented for SIGALRM");
1459         if (out != NULL)
1460                 return errno = EINVAL,
1461                         error("sigaction: param 3 != NULL not implemented");
1463         timer_fn = in->sa_handler;
1464         return 0;
1467 #undef signal
1468 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1470         sig_handler_t old = timer_fn;
1471         if (sig != SIGALRM)
1472                 return signal(sig, handler);
1473         timer_fn = handler;
1474         return old;
1477 static const char *make_backslash_path(const char *path)
1479         static char buf[PATH_MAX + 1];
1480         char *c;
1482         if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1483                 die("Too long path: %.*s", 60, path);
1485         for (c = buf; *c; c++) {
1486                 if (*c == '/')
1487                         *c = '\\';
1488         }
1489         return buf;
1492 void mingw_open_html(const char *unixpath)
1494         const char *htmlpath = make_backslash_path(unixpath);
1495         typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1496                         const char *, const char *, const char *, INT);
1497         T ShellExecute;
1498         HMODULE shell32;
1499         int r;
1501         shell32 = LoadLibrary("shell32.dll");
1502         if (!shell32)
1503                 die("cannot load shell32.dll");
1504         ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1505         if (!ShellExecute)
1506                 die("cannot run browser");
1508         printf("Launching default browser to display HTML ...\n");
1509         r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1510         FreeLibrary(shell32);
1511         /* see the MSDN documentation referring to the result codes here */
1512         if (r <= 32) {
1513                 die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1514         }
1517 int link(const char *oldpath, const char *newpath)
1519         typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1520         static T create_hard_link = NULL;
1521         if (!create_hard_link) {
1522                 create_hard_link = (T) GetProcAddress(
1523                         GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1524                 if (!create_hard_link)
1525                         create_hard_link = (T)-1;
1526         }
1527         if (create_hard_link == (T)-1) {
1528                 errno = ENOSYS;
1529                 return -1;
1530         }
1531         if (!create_hard_link(newpath, oldpath, NULL)) {
1532                 errno = err_win_to_posix(GetLastError());
1533                 return -1;
1534         }
1535         return 0;
1538 char *getpass(const char *prompt)
1540         struct strbuf buf = STRBUF_INIT;
1542         fputs(prompt, stderr);
1543         for (;;) {
1544                 char c = _getch();
1545                 if (c == '\r' || c == '\n')
1546                         break;
1547                 strbuf_addch(&buf, c);
1548         }
1549         fputs("\n", stderr);
1550         return strbuf_detach(&buf, NULL);
1553 pid_t waitpid(pid_t pid, int *status, unsigned options)
1555         HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
1556             FALSE, pid);
1557         if (!h) {
1558                 errno = ECHILD;
1559                 return -1;
1560         }
1562         if (pid > 0 && options & WNOHANG) {
1563                 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
1564                         CloseHandle(h);
1565                         return 0;
1566                 }
1567                 options &= ~WNOHANG;
1568         }
1570         if (options == 0) {
1571                 struct pinfo_t **ppinfo;
1572                 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
1573                         CloseHandle(h);
1574                         return 0;
1575                 }
1577                 if (status)
1578                         GetExitCodeProcess(h, (LPDWORD)status);
1580                 EnterCriticalSection(&pinfo_cs);
1582                 ppinfo = &pinfo;
1583                 while (*ppinfo) {
1584                         struct pinfo_t *info = *ppinfo;
1585                         if (info->pid == pid) {
1586                                 CloseHandle(info->proc);
1587                                 *ppinfo = info->next;
1588                                 free(info);
1589                                 break;
1590                         }
1591                         ppinfo = &info->next;
1592                 }
1594                 LeaveCriticalSection(&pinfo_cs);
1596                 CloseHandle(h);
1597                 return pid;
1598         }
1599         CloseHandle(h);
1601         errno = EINVAL;
1602         return -1;