core.hidedotfiles: hide '.git' dir by default
[git/mingw/4msysgit.git] / compat / mingw.c
blob710150f4429bf697cc48ab260da2da48495df016
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include "../strbuf.h"
5 #include "../cache.h"
7 unsigned int _CRT_fmode = _O_BINARY;
9 int err_win_to_posix(DWORD winerr)
11 int error = ENOSYS;
12 switch(winerr) {
13 case ERROR_ACCESS_DENIED: error = EACCES; break;
14 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
15 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
16 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
17 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
18 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
19 case ERROR_BAD_COMMAND: error = EIO; break;
20 case ERROR_BAD_DEVICE: error = ENODEV; break;
21 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
22 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
23 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
24 case ERROR_BAD_LENGTH: error = EINVAL; break;
25 case ERROR_BAD_PATHNAME: error = ENOENT; break;
26 case ERROR_BAD_PIPE: error = EPIPE; break;
27 case ERROR_BAD_UNIT: error = ENODEV; break;
28 case ERROR_BAD_USERNAME: error = EINVAL; break;
29 case ERROR_BROKEN_PIPE: error = EPIPE; break;
30 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
31 case ERROR_BUSY: error = EBUSY; break;
32 case ERROR_BUSY_DRIVE: error = EBUSY; break;
33 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
34 case ERROR_CANNOT_MAKE: error = EACCES; break;
35 case ERROR_CANTOPEN: error = EIO; break;
36 case ERROR_CANTREAD: error = EIO; break;
37 case ERROR_CANTWRITE: error = EIO; break;
38 case ERROR_CRC: error = EIO; break;
39 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
40 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
41 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
42 case ERROR_DIRECTORY: error = EINVAL; break;
43 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
44 case ERROR_DISK_CHANGE: error = EIO; break;
45 case ERROR_DISK_FULL: error = ENOSPC; break;
46 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
47 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
48 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
49 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
50 case ERROR_FILE_EXISTS: error = EEXIST; break;
51 case ERROR_FILE_INVALID: error = ENODEV; break;
52 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
53 case ERROR_GEN_FAILURE: error = EIO; break;
54 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
55 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
56 case ERROR_INVALID_ACCESS: error = EACCES; break;
57 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
58 case ERROR_INVALID_BLOCK: error = EFAULT; break;
59 case ERROR_INVALID_DATA: error = EINVAL; break;
60 case ERROR_INVALID_DRIVE: error = ENODEV; break;
61 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
62 case ERROR_INVALID_FLAGS: error = EINVAL; break;
63 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
64 case ERROR_INVALID_HANDLE: error = EBADF; break;
65 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
66 case ERROR_INVALID_NAME: error = EINVAL; break;
67 case ERROR_INVALID_OWNER: error = EINVAL; break;
68 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
69 case ERROR_INVALID_PASSWORD: error = EPERM; break;
70 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
71 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
72 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
73 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
74 case ERROR_IO_DEVICE: error = EIO; break;
75 case ERROR_IO_INCOMPLETE: error = EINTR; break;
76 case ERROR_LOCKED: error = EBUSY; break;
77 case ERROR_LOCK_VIOLATION: error = EACCES; break;
78 case ERROR_LOGON_FAILURE: error = EACCES; break;
79 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
80 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
81 case ERROR_MORE_DATA: error = EPIPE; break;
82 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
83 case ERROR_NOACCESS: error = EFAULT; break;
84 case ERROR_NONE_MAPPED: error = EINVAL; break;
85 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
86 case ERROR_NOT_READY: error = EAGAIN; break;
87 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
88 case ERROR_NO_DATA: error = EPIPE; break;
89 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
90 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
91 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
92 case ERROR_OPEN_FAILED: error = EIO; break;
93 case ERROR_OPEN_FILES: error = EBUSY; break;
94 case ERROR_OPERATION_ABORTED: error = EINTR; break;
95 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
96 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
97 case ERROR_PATH_BUSY: error = EBUSY; break;
98 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
99 case ERROR_PIPE_BUSY: error = EBUSY; break;
100 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
101 case ERROR_PIPE_LISTENING: error = EPIPE; break;
102 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
103 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
104 case ERROR_READ_FAULT: error = EIO; break;
105 case ERROR_SEEK: error = EIO; break;
106 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
107 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
108 case ERROR_SHARING_VIOLATION: error = EACCES; break;
109 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
110 case ERROR_SWAPERROR: error = ENOENT; break;
111 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
112 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
113 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
114 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
115 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
116 case ERROR_WRITE_FAULT: error = EIO; break;
117 case ERROR_WRITE_PROTECT: error = EROFS; break;
119 return error;
122 static int make_hidden(const char *path)
124 DWORD attribs = GetFileAttributes(path);
125 if (SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN | attribs))
126 return 0;
127 errno = err_win_to_posix(GetLastError());
128 return -1;
131 void mingw_mark_as_git_dir(const char *dir)
133 if (hide_dotfiles != HIDE_DOTFILES_FALSE && make_hidden(dir))
134 warning("Failed to make '%s' hidden", dir);
137 #undef mkdir
138 int mingw_mkdir(const char *path, int mode)
140 int ret = mkdir(path);
141 if (!ret && hide_dotfiles == HIDE_DOTFILES_TRUE) {
143 * In Windows a file or dir starting with a dot is not
144 * automatically hidden. So lets mark it as hidden when
145 * such a directory is created.
147 const char *start = basename((char*)path);
148 if (*start == '.')
149 return make_hidden(path);
151 return ret;
154 #undef open
155 int mingw_open (const char *filename, int oflags, ...)
157 va_list args;
158 unsigned mode;
159 int fd;
161 va_start(args, oflags);
162 mode = va_arg(args, int);
163 va_end(args);
165 if (filename && !strcmp(filename, "/dev/null"))
166 filename = "nul";
168 fd = open(filename, oflags, mode);
170 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
171 DWORD attrs = GetFileAttributes(filename);
172 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
173 errno = EISDIR;
175 if ((oflags & O_CREAT) && fd >= 0 &&
176 hide_dotfiles == HIDE_DOTFILES_TRUE) {
178 * In Windows a file or dir starting with a dot is not
179 * automatically hidden. So lets mark it as hidden when
180 * such a file is created.
182 const char *start = basename((char*)filename);
183 if (*start == '.' && make_hidden(filename))
184 warning("Could not mark '%s' as hidden.", filename);
186 return fd;
189 #undef write
190 ssize_t mingw_write(int fd, const void *buf, size_t count)
193 * While write() calls to a file on a local disk are translated
194 * into WriteFile() calls with a maximum size of 64KB on Windows
195 * XP and 256KB on Vista, no such cap is placed on writes to
196 * files over the network on Windows XP. Unfortunately, there
197 * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
198 * bigger writes fail on Windows XP.
199 * So we cap to a nice 31MB here to avoid write failures over
200 * the net without changing the number of WriteFile() calls in
201 * the local case.
203 return write(fd, buf, min(count, 31 * 1024 * 1024));
206 #undef fopen
207 FILE *mingw_fopen (const char *filename, const char *otype)
209 int hide = 0;
210 FILE *file;
211 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
212 basename((char*)filename)[0] == '.')
213 hide = access(filename, F_OK);
214 if (filename && !strcmp(filename, "/dev/null"))
215 filename = "nul";
216 file = fopen(filename, otype);
217 if (file && hide && make_hidden(filename))
218 warning("Could not mark '%s' as hidden.", filename);
219 return file;
222 #undef freopen
223 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
225 int hide = 0;
226 FILE *file;
227 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
228 basename((char*)filename)[0] == '.')
229 hide = access(filename, F_OK);
230 if (filename && !strcmp(filename, "/dev/null"))
231 filename = "nul";
232 file = freopen(filename, otype, stream);
233 if (file && hide && make_hidden(filename))
234 warning("Could not mark '%s' as hidden.", filename);
235 return file;
239 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
240 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
242 static inline long long filetime_to_hnsec(const FILETIME *ft)
244 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
245 /* Windows to Unix Epoch conversion */
246 return winTime - 116444736000000000LL;
249 static inline time_t filetime_to_time_t(const FILETIME *ft)
251 return (time_t)(filetime_to_hnsec(ft) / 10000000);
254 /* We keep the do_lstat code in a separate function to avoid recursion.
255 * When a path ends with a slash, the stat will fail with ENOENT. In
256 * this case, we strip the trailing slashes and stat again.
258 * If follow is true then act like stat() and report on the link
259 * target. Otherwise report on the link itself.
261 static int do_lstat(int follow, const char *file_name, struct stat *buf)
263 WIN32_FILE_ATTRIBUTE_DATA fdata;
265 if (!(errno = get_file_attr(file_name, &fdata))) {
266 buf->st_ino = 0;
267 buf->st_gid = 0;
268 buf->st_uid = 0;
269 buf->st_nlink = 1;
270 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
271 buf->st_size = fdata.nFileSizeLow |
272 (((off_t)fdata.nFileSizeHigh)<<32);
273 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
274 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
275 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
276 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
277 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
278 WIN32_FIND_DATAA findbuf;
279 HANDLE handle = FindFirstFileA(file_name, &findbuf);
280 if (handle != INVALID_HANDLE_VALUE) {
281 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
282 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
283 if (follow) {
284 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
285 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
286 } else {
287 buf->st_mode = S_IFLNK;
289 buf->st_mode |= S_IREAD;
290 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
291 buf->st_mode |= S_IWRITE;
293 FindClose(handle);
296 return 0;
298 return -1;
301 /* We provide our own lstat/fstat functions, since the provided
302 * lstat/fstat functions are so slow. These stat functions are
303 * tailored for Git's usage (read: fast), and are not meant to be
304 * complete. Note that Git stat()s are redirected to mingw_lstat()
305 * too, since Windows doesn't really handle symlinks that well.
307 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
309 int namelen;
310 static char alt_name[PATH_MAX];
312 if (!do_lstat(follow, file_name, buf))
313 return 0;
315 /* if file_name ended in a '/', Windows returned ENOENT;
316 * try again without trailing slashes
318 if (errno != ENOENT)
319 return -1;
321 namelen = strlen(file_name);
322 if (namelen && file_name[namelen-1] != '/')
323 return -1;
324 while (namelen && file_name[namelen-1] == '/')
325 --namelen;
326 if (!namelen || namelen >= PATH_MAX)
327 return -1;
329 memcpy(alt_name, file_name, namelen);
330 alt_name[namelen] = 0;
331 return do_lstat(follow, alt_name, buf);
334 int mingw_lstat(const char *file_name, struct stat *buf)
336 return do_stat_internal(0, file_name, buf);
338 int mingw_stat(const char *file_name, struct stat *buf)
340 return do_stat_internal(1, file_name, buf);
343 #undef fstat
344 int mingw_fstat(int fd, struct stat *buf)
346 HANDLE fh = (HANDLE)_get_osfhandle(fd);
347 BY_HANDLE_FILE_INFORMATION fdata;
349 if (fh == INVALID_HANDLE_VALUE) {
350 errno = EBADF;
351 return -1;
353 /* direct non-file handles to MS's fstat() */
354 if (GetFileType(fh) != FILE_TYPE_DISK)
355 return _fstati64(fd, buf);
357 if (GetFileInformationByHandle(fh, &fdata)) {
358 buf->st_ino = 0;
359 buf->st_gid = 0;
360 buf->st_uid = 0;
361 buf->st_nlink = 1;
362 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
363 buf->st_size = fdata.nFileSizeLow |
364 (((off_t)fdata.nFileSizeHigh)<<32);
365 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
366 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
367 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
368 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
369 return 0;
371 errno = EBADF;
372 return -1;
375 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
377 long long winTime = t * 10000000LL + 116444736000000000LL;
378 ft->dwLowDateTime = winTime;
379 ft->dwHighDateTime = winTime >> 32;
382 int mingw_utime (const char *file_name, const struct utimbuf *times)
384 FILETIME mft, aft;
385 int fh, rc;
387 /* must have write permission */
388 DWORD attrs = GetFileAttributes(file_name);
389 if (attrs != INVALID_FILE_ATTRIBUTES &&
390 (attrs & FILE_ATTRIBUTE_READONLY)) {
391 /* ignore errors here; open() will report them */
392 SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
395 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
396 rc = -1;
397 goto revert_attrs;
400 if (times) {
401 time_t_to_filetime(times->modtime, &mft);
402 time_t_to_filetime(times->actime, &aft);
403 } else {
404 GetSystemTimeAsFileTime(&mft);
405 aft = mft;
407 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
408 errno = EINVAL;
409 rc = -1;
410 } else
411 rc = 0;
412 close(fh);
414 revert_attrs:
415 if (attrs != INVALID_FILE_ATTRIBUTES &&
416 (attrs & FILE_ATTRIBUTE_READONLY)) {
417 /* ignore errors again */
418 SetFileAttributes(file_name, attrs);
420 return rc;
423 unsigned int sleep (unsigned int seconds)
425 Sleep(seconds*1000);
426 return 0;
429 int mkstemp(char *template)
431 char *filename = mktemp(template);
432 if (filename == NULL)
433 return -1;
434 return open(filename, O_RDWR | O_CREAT, 0600);
437 int gettimeofday(struct timeval *tv, void *tz)
439 FILETIME ft;
440 long long hnsec;
442 GetSystemTimeAsFileTime(&ft);
443 hnsec = filetime_to_hnsec(&ft);
444 tv->tv_sec = hnsec / 10000000;
445 tv->tv_usec = (hnsec % 10000000) / 10;
446 return 0;
449 int pipe(int filedes[2])
451 HANDLE h[2];
453 /* this creates non-inheritable handles */
454 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
455 errno = err_win_to_posix(GetLastError());
456 return -1;
458 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
459 if (filedes[0] < 0) {
460 CloseHandle(h[0]);
461 CloseHandle(h[1]);
462 return -1;
464 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
465 if (filedes[0] < 0) {
466 close(filedes[0]);
467 CloseHandle(h[1]);
468 return -1;
470 return 0;
473 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
475 int i, pending;
477 if (timeout >= 0) {
478 if (nfds == 0) {
479 Sleep(timeout);
480 return 0;
482 return errno = EINVAL, error("poll timeout not supported");
485 /* When there is only one fd to wait for, then we pretend that
486 * input is available and let the actual wait happen when the
487 * caller invokes read().
489 if (nfds == 1) {
490 if (!(ufds[0].events & POLLIN))
491 return errno = EINVAL, error("POLLIN not set");
492 ufds[0].revents = POLLIN;
493 return 0;
496 repeat:
497 pending = 0;
498 for (i = 0; i < nfds; i++) {
499 DWORD avail = 0;
500 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
501 if (h == INVALID_HANDLE_VALUE)
502 return -1; /* errno was set */
504 if (!(ufds[i].events & POLLIN))
505 return errno = EINVAL, error("POLLIN not set");
507 /* this emulation works only for pipes */
508 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
509 int err = GetLastError();
510 if (err == ERROR_BROKEN_PIPE) {
511 ufds[i].revents = POLLHUP;
512 pending++;
513 } else {
514 errno = EINVAL;
515 return error("PeekNamedPipe failed,"
516 " GetLastError: %u", err);
518 } else if (avail) {
519 ufds[i].revents = POLLIN;
520 pending++;
521 } else
522 ufds[i].revents = 0;
524 if (!pending) {
525 /* The only times that we spin here is when the process
526 * that is connected through the pipes is waiting for
527 * its own input data to become available. But since
528 * the process (pack-objects) is itself CPU intensive,
529 * it will happily pick up the time slice that we are
530 * relinquishing here.
532 Sleep(0);
533 goto repeat;
535 return 0;
538 struct tm *gmtime_r(const time_t *timep, struct tm *result)
540 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
541 memcpy(result, gmtime(timep), sizeof(struct tm));
542 return result;
545 struct tm *localtime_r(const time_t *timep, struct tm *result)
547 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
548 memcpy(result, localtime(timep), sizeof(struct tm));
549 return result;
552 #undef getcwd
553 char *mingw_getcwd(char *pointer, int len)
555 int i;
556 char *ret = getcwd(pointer, len);
557 if (!ret)
558 return ret;
559 for (i = 0; pointer[i]; i++)
560 if (pointer[i] == '\\')
561 pointer[i] = '/';
562 return ret;
565 #undef getenv
566 char *mingw_getenv(const char *name)
568 char *result = getenv(name);
569 if (!result && !strcmp(name, "TMPDIR")) {
570 /* on Windows it is TMP and TEMP */
571 result = getenv("TMP");
572 if (!result)
573 result = getenv("TEMP");
575 return result;
579 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
580 * (Parsing C++ Command-Line Arguments)
582 static const char *quote_arg(const char *arg)
584 /* count chars to quote */
585 int len = 0, n = 0;
586 int force_quotes = 0;
587 char *q, *d;
588 const char *p = arg;
589 if (!*p) force_quotes = 1;
590 while (*p) {
591 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
592 force_quotes = 1;
593 else if (*p == '"')
594 n++;
595 else if (*p == '\\') {
596 int count = 0;
597 while (*p == '\\') {
598 count++;
599 p++;
600 len++;
602 if (*p == '"')
603 n += count*2 + 1;
604 continue;
606 len++;
607 p++;
609 if (!force_quotes && n == 0)
610 return arg;
612 /* insert \ where necessary */
613 d = q = xmalloc(len+n+3);
614 *d++ = '"';
615 while (*arg) {
616 if (*arg == '"')
617 *d++ = '\\';
618 else if (*arg == '\\') {
619 int count = 0;
620 while (*arg == '\\') {
621 count++;
622 *d++ = *arg++;
624 if (*arg == '"') {
625 while (count-- > 0)
626 *d++ = '\\';
627 *d++ = '\\';
630 *d++ = *arg++;
632 *d++ = '"';
633 *d++ = 0;
634 return q;
637 static const char *parse_interpreter(const char *cmd)
639 static char buf[100];
640 char *p, *opt;
641 int n, fd;
643 /* don't even try a .exe */
644 n = strlen(cmd);
645 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
646 return NULL;
648 fd = open(cmd, O_RDONLY);
649 if (fd < 0)
650 return NULL;
651 n = read(fd, buf, sizeof(buf)-1);
652 close(fd);
653 if (n < 4) /* at least '#!/x' and not error */
654 return NULL;
656 if (buf[0] != '#' || buf[1] != '!')
657 return NULL;
658 buf[n] = '\0';
659 p = buf + strcspn(buf, "\r\n");
660 if (!*p)
661 return NULL;
663 *p = '\0';
664 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
665 return NULL;
666 /* strip options */
667 if ((opt = strchr(p+1, ' ')))
668 *opt = '\0';
669 return p+1;
673 * Splits the PATH into parts.
675 static char **get_path_split(void)
677 char *p, **path, *envpath = getenv("PATH");
678 int i, n = 0;
680 if (!envpath || !*envpath)
681 return NULL;
683 envpath = xstrdup(envpath);
684 p = envpath;
685 while (p) {
686 char *dir = p;
687 p = strchr(p, ';');
688 if (p) *p++ = '\0';
689 if (*dir) { /* not earlier, catches series of ; */
690 ++n;
693 if (!n)
694 return NULL;
696 path = xmalloc((n+1)*sizeof(char *));
697 p = envpath;
698 i = 0;
699 do {
700 if (*p)
701 path[i++] = xstrdup(p);
702 p = p+strlen(p)+1;
703 } while (i < n);
704 path[i] = NULL;
706 free(envpath);
708 return path;
711 static void free_path_split(char **path)
713 char **p = path;
715 if (!path)
716 return;
718 while (*p)
719 free(*p++);
720 free(path);
724 * exe_only means that we only want to detect .exe files, but not scripts
725 * (which do not have an extension)
727 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
729 char path[MAX_PATH];
730 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
732 if (!isexe && access(path, F_OK) == 0)
733 return xstrdup(path);
734 path[strlen(path)-4] = '\0';
735 if ((!exe_only || isexe) && access(path, F_OK) == 0)
736 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
737 return xstrdup(path);
738 return NULL;
742 * Determines the absolute path of cmd using the split path in path.
743 * If cmd contains a slash or backslash, no lookup is performed.
745 static char *path_lookup(const char *cmd, char **path, int exe_only)
747 char *prog = NULL;
748 int len = strlen(cmd);
749 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
751 if (strchr(cmd, '/') || strchr(cmd, '\\'))
752 prog = xstrdup(cmd);
754 while (!prog && *path)
755 prog = lookup_prog(*path++, cmd, isexe, exe_only);
757 return prog;
760 static int env_compare(const void *a, const void *b)
762 char *const *ea = a;
763 char *const *eb = b;
764 return strcasecmp(*ea, *eb);
767 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
768 const char *dir,
769 int prepend_cmd, int fhin, int fhout, int fherr)
771 STARTUPINFO si;
772 PROCESS_INFORMATION pi;
773 struct strbuf envblk, args;
774 unsigned flags;
775 BOOL ret;
777 /* Determine whether or not we are associated to a console */
778 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
779 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
780 FILE_ATTRIBUTE_NORMAL, NULL);
781 if (cons == INVALID_HANDLE_VALUE) {
782 /* There is no console associated with this process.
783 * Since the child is a console process, Windows
784 * would normally create a console window. But
785 * since we'll be redirecting std streams, we do
786 * not need the console.
787 * It is necessary to use DETACHED_PROCESS
788 * instead of CREATE_NO_WINDOW to make ssh
789 * recognize that it has no console.
791 flags = DETACHED_PROCESS;
792 } else {
793 /* There is already a console. If we specified
794 * DETACHED_PROCESS here, too, Windows would
795 * disassociate the child from the console.
796 * The same is true for CREATE_NO_WINDOW.
797 * Go figure!
799 flags = 0;
800 CloseHandle(cons);
802 memset(&si, 0, sizeof(si));
803 si.cb = sizeof(si);
804 si.dwFlags = STARTF_USESTDHANDLES;
805 si.hStdInput = (HANDLE) _get_osfhandle(fhin);
806 si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
807 si.hStdError = (HANDLE) _get_osfhandle(fherr);
809 /* concatenate argv, quoting args as we go */
810 strbuf_init(&args, 0);
811 if (prepend_cmd) {
812 char *quoted = (char *)quote_arg(cmd);
813 strbuf_addstr(&args, quoted);
814 if (quoted != cmd)
815 free(quoted);
817 for (; *argv; argv++) {
818 char *quoted = (char *)quote_arg(*argv);
819 if (*args.buf)
820 strbuf_addch(&args, ' ');
821 strbuf_addstr(&args, quoted);
822 if (quoted != *argv)
823 free(quoted);
826 if (env) {
827 int count = 0;
828 char **e, **sorted_env;
830 for (e = env; *e; e++)
831 count++;
833 /* environment must be sorted */
834 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
835 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
836 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
838 strbuf_init(&envblk, 0);
839 for (e = sorted_env; *e; e++) {
840 strbuf_addstr(&envblk, *e);
841 strbuf_addch(&envblk, '\0');
843 free(sorted_env);
846 memset(&pi, 0, sizeof(pi));
847 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
848 env ? envblk.buf : NULL, dir, &si, &pi);
850 if (env)
851 strbuf_release(&envblk);
852 strbuf_release(&args);
854 if (!ret) {
855 errno = ENOENT;
856 return -1;
858 CloseHandle(pi.hThread);
859 return (pid_t)pi.hProcess;
862 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
863 int prepend_cmd)
865 return mingw_spawnve_fd(cmd, argv, env, NULL, prepend_cmd, 0, 1, 2);
868 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
869 const char *dir,
870 int fhin, int fhout, int fherr)
872 pid_t pid;
873 char **path = get_path_split();
874 char *prog = path_lookup(cmd, path, 0);
876 if (!prog) {
877 errno = ENOENT;
878 pid = -1;
880 else {
881 const char *interpr = parse_interpreter(prog);
883 if (interpr) {
884 const char *argv0 = argv[0];
885 char *iprog = path_lookup(interpr, path, 1);
886 argv[0] = prog;
887 if (!iprog) {
888 errno = ENOENT;
889 pid = -1;
891 else {
892 pid = mingw_spawnve_fd(iprog, argv, env, dir, 1,
893 fhin, fhout, fherr);
894 free(iprog);
896 argv[0] = argv0;
898 else
899 pid = mingw_spawnve_fd(prog, argv, env, dir, 0,
900 fhin, fhout, fherr);
901 free(prog);
903 free_path_split(path);
904 return pid;
907 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
909 const char *interpr = parse_interpreter(cmd);
910 char **path;
911 char *prog;
912 int pid = 0;
914 if (!interpr)
915 return 0;
916 path = get_path_split();
917 prog = path_lookup(interpr, path, 1);
918 if (prog) {
919 int argc = 0;
920 const char **argv2;
921 while (argv[argc]) argc++;
922 argv2 = xmalloc(sizeof(*argv) * (argc+1));
923 argv2[0] = (char *)cmd; /* full path to the script file */
924 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
925 pid = mingw_spawnve(prog, argv2, env, 1);
926 if (pid >= 0) {
927 int status;
928 if (waitpid(pid, &status, 0) < 0)
929 status = 255;
930 exit(status);
932 pid = 1; /* indicate that we tried but failed */
933 free(prog);
934 free(argv2);
936 free_path_split(path);
937 return pid;
940 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
942 /* check if git_command is a shell script */
943 if (!try_shell_exec(cmd, argv, (char **)env)) {
944 int pid, status;
946 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
947 if (pid < 0)
948 return;
949 if (waitpid(pid, &status, 0) < 0)
950 status = 255;
951 exit(status);
955 void mingw_execvp(const char *cmd, char *const *argv)
957 char **path = get_path_split();
958 char *prog = path_lookup(cmd, path, 0);
960 if (prog) {
961 mingw_execve(prog, argv, environ);
962 free(prog);
963 } else
964 errno = ENOENT;
966 free_path_split(path);
969 static char **copy_environ(void)
971 char **env;
972 int i = 0;
973 while (environ[i])
974 i++;
975 env = xmalloc((i+1)*sizeof(*env));
976 for (i = 0; environ[i]; i++)
977 env[i] = xstrdup(environ[i]);
978 env[i] = NULL;
979 return env;
982 void free_environ(char **env)
984 int i;
985 for (i = 0; env[i]; i++)
986 free(env[i]);
987 free(env);
990 static int lookup_env(char **env, const char *name, size_t nmln)
992 int i;
994 for (i = 0; env[i]; i++) {
995 if (0 == strncmp(env[i], name, nmln)
996 && '=' == env[i][nmln])
997 /* matches */
998 return i;
1000 return -1;
1004 * If name contains '=', then sets the variable, otherwise it unsets it
1006 static char **env_setenv(char **env, const char *name)
1008 char *eq = strchrnul(name, '=');
1009 int i = lookup_env(env, name, eq-name);
1011 if (i < 0) {
1012 if (*eq) {
1013 for (i = 0; env[i]; i++)
1015 env = xrealloc(env, (i+2)*sizeof(*env));
1016 env[i] = xstrdup(name);
1017 env[i+1] = NULL;
1020 else {
1021 free(env[i]);
1022 if (*eq)
1023 env[i] = xstrdup(name);
1024 else
1025 for (; env[i]; i++)
1026 env[i] = env[i+1];
1028 return env;
1032 * Copies global environ and adjusts variables as specified by vars.
1034 char **make_augmented_environ(const char *const *vars)
1036 char **env = copy_environ();
1038 while (*vars)
1039 env = env_setenv(env, *vars++);
1040 return env;
1044 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1045 * that service contains a numerical port, or that it it is null. It
1046 * does a simple search using gethostbyname, and returns one IPv4 host
1047 * if one was found.
1049 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1050 const struct addrinfo *hints,
1051 struct addrinfo **res)
1053 struct hostent *h = gethostbyname(node);
1054 struct addrinfo *ai;
1055 struct sockaddr_in *sin;
1057 if (!h)
1058 return WSAGetLastError();
1060 ai = xmalloc(sizeof(struct addrinfo));
1061 *res = ai;
1062 ai->ai_flags = 0;
1063 ai->ai_family = AF_INET;
1064 ai->ai_socktype = hints->ai_socktype;
1065 switch (hints->ai_socktype) {
1066 case SOCK_STREAM:
1067 ai->ai_protocol = IPPROTO_TCP;
1068 break;
1069 case SOCK_DGRAM:
1070 ai->ai_protocol = IPPROTO_UDP;
1071 break;
1072 default:
1073 ai->ai_protocol = 0;
1074 break;
1076 ai->ai_addrlen = sizeof(struct sockaddr_in);
1077 ai->ai_canonname = strdup(h->h_name);
1079 sin = xmalloc(ai->ai_addrlen);
1080 memset(sin, 0, ai->ai_addrlen);
1081 sin->sin_family = AF_INET;
1082 if (service)
1083 sin->sin_port = htons(atoi(service));
1084 sin->sin_addr = *(struct in_addr *)h->h_addr;
1085 ai->ai_addr = (struct sockaddr *)sin;
1086 ai->ai_next = 0;
1087 return 0;
1090 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1092 free(res->ai_canonname);
1093 free(res->ai_addr);
1094 free(res);
1097 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1098 char *host, DWORD hostlen,
1099 char *serv, DWORD servlen, int flags)
1101 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1102 if (sa->sa_family != AF_INET)
1103 return EAI_FAMILY;
1104 if (!host && !serv)
1105 return EAI_NONAME;
1107 if (host && hostlen > 0) {
1108 struct hostent *ent = NULL;
1109 if (!(flags & NI_NUMERICHOST))
1110 ent = gethostbyaddr((const char *)&sin->sin_addr,
1111 sizeof(sin->sin_addr), AF_INET);
1113 if (ent)
1114 snprintf(host, hostlen, "%s", ent->h_name);
1115 else if (flags & NI_NAMEREQD)
1116 return EAI_NONAME;
1117 else
1118 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1121 if (serv && servlen > 0) {
1122 struct servent *ent = NULL;
1123 if (!(flags & NI_NUMERICSERV))
1124 ent = getservbyport(sin->sin_port,
1125 flags & NI_DGRAM ? "udp" : "tcp");
1127 if (ent)
1128 snprintf(serv, servlen, "%s", ent->s_name);
1129 else
1130 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1133 return 0;
1136 static HMODULE ipv6_dll = NULL;
1137 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1138 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1139 const struct addrinfo *hints,
1140 struct addrinfo **res);
1141 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1142 char *host, DWORD hostlen,
1143 char *serv, DWORD servlen, int flags);
1145 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1146 * don't need to try to load that one dynamically.
1149 static void socket_cleanup(void)
1151 WSACleanup();
1152 if (ipv6_dll)
1153 FreeLibrary(ipv6_dll);
1154 ipv6_dll = NULL;
1155 ipv6_freeaddrinfo = freeaddrinfo_stub;
1156 ipv6_getaddrinfo = getaddrinfo_stub;
1157 ipv6_getnameinfo = getnameinfo_stub;
1160 static void ensure_socket_initialization(void)
1162 WSADATA wsa;
1163 static int initialized = 0;
1164 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1165 const char **name;
1167 if (initialized)
1168 return;
1170 if (WSAStartup(MAKEWORD(2,2), &wsa))
1171 die("unable to initialize winsock subsystem, error %d",
1172 WSAGetLastError());
1174 for (name = libraries; *name; name++) {
1175 ipv6_dll = LoadLibrary(*name);
1176 if (!ipv6_dll)
1177 continue;
1179 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1180 GetProcAddress(ipv6_dll, "freeaddrinfo");
1181 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1182 const struct addrinfo *,
1183 struct addrinfo **))
1184 GetProcAddress(ipv6_dll, "getaddrinfo");
1185 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1186 socklen_t, char *, DWORD,
1187 char *, DWORD, int))
1188 GetProcAddress(ipv6_dll, "getnameinfo");
1189 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1190 FreeLibrary(ipv6_dll);
1191 ipv6_dll = NULL;
1192 } else
1193 break;
1195 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1196 ipv6_freeaddrinfo = freeaddrinfo_stub;
1197 ipv6_getaddrinfo = getaddrinfo_stub;
1198 ipv6_getnameinfo = getnameinfo_stub;
1201 atexit(socket_cleanup);
1202 initialized = 1;
1205 #undef gethostbyname
1206 struct hostent *mingw_gethostbyname(const char *host)
1208 ensure_socket_initialization();
1209 return gethostbyname(host);
1212 void mingw_freeaddrinfo(struct addrinfo *res)
1214 ipv6_freeaddrinfo(res);
1217 int mingw_getaddrinfo(const char *node, const char *service,
1218 const struct addrinfo *hints, struct addrinfo **res)
1220 ensure_socket_initialization();
1221 return ipv6_getaddrinfo(node, service, hints, res);
1224 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1225 char *host, DWORD hostlen, char *serv, DWORD servlen,
1226 int flags)
1228 ensure_socket_initialization();
1229 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1232 int mingw_socket(int domain, int type, int protocol)
1234 int sockfd;
1235 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
1236 if (s == INVALID_SOCKET) {
1238 * WSAGetLastError() values are regular BSD error codes
1239 * biased by WSABASEERR.
1240 * However, strerror() does not know about networking
1241 * specific errors, which are values beginning at 38 or so.
1242 * Therefore, we choose to leave the biased error code
1243 * in errno so that _if_ someone looks up the code somewhere,
1244 * then it is at least the number that are usually listed.
1246 errno = WSAGetLastError();
1247 return -1;
1249 /* convert into a file descriptor */
1250 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1251 closesocket(s);
1252 return error("unable to make a socket file descriptor: %s",
1253 strerror(errno));
1255 return sockfd;
1258 #undef connect
1259 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1261 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1262 return connect(s, sa, sz);
1265 #undef rename
1266 int mingw_rename(const char *pold, const char *pnew)
1268 DWORD attrs, gle;
1269 int tries = 0;
1270 static const int delay[] = { 0, 1, 10, 20, 40 };
1273 * Try native rename() first to get errno right.
1274 * It is based on MoveFile(), which cannot overwrite existing files.
1276 if (!rename(pold, pnew))
1277 return 0;
1278 if (errno != EEXIST)
1279 return -1;
1280 repeat:
1281 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1282 return 0;
1283 /* TODO: translate more errors */
1284 gle = GetLastError();
1285 if (gle == ERROR_ACCESS_DENIED &&
1286 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1287 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1288 errno = EISDIR;
1289 return -1;
1291 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1292 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1293 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1294 return 0;
1295 gle = GetLastError();
1296 /* revert file attributes on failure */
1297 SetFileAttributes(pnew, attrs);
1300 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1302 * We assume that some other process had the source or
1303 * destination file open at the wrong moment and retry.
1304 * In order to give the other process a higher chance to
1305 * complete its operation, we give up our time slice now.
1306 * If we have to retry again, we do sleep a bit.
1308 Sleep(delay[tries]);
1309 tries++;
1310 goto repeat;
1312 errno = EACCES;
1313 return -1;
1317 * Note that this doesn't return the actual pagesize, but
1318 * the allocation granularity. If future Windows specific git code
1319 * needs the real getpagesize function, we need to find another solution.
1321 int mingw_getpagesize(void)
1323 SYSTEM_INFO si;
1324 GetSystemInfo(&si);
1325 return si.dwAllocationGranularity;
1328 struct passwd *getpwuid(int uid)
1330 static char user_name[100];
1331 static struct passwd p;
1333 DWORD len = sizeof(user_name);
1334 if (!GetUserName(user_name, &len))
1335 return NULL;
1336 p.pw_name = user_name;
1337 p.pw_gecos = "unknown";
1338 p.pw_dir = NULL;
1339 return &p;
1342 static HANDLE timer_event;
1343 static HANDLE timer_thread;
1344 static int timer_interval;
1345 static int one_shot;
1346 static sig_handler_t timer_fn = SIG_DFL;
1348 /* The timer works like this:
1349 * The thread, ticktack(), is a trivial routine that most of the time
1350 * only waits to receive the signal to terminate. The main thread tells
1351 * the thread to terminate by setting the timer_event to the signalled
1352 * state.
1353 * But ticktack() interrupts the wait state after the timer's interval
1354 * length to call the signal handler.
1357 static unsigned __stdcall ticktack(void *dummy)
1359 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1360 if (timer_fn == SIG_DFL)
1361 die("Alarm");
1362 if (timer_fn != SIG_IGN)
1363 timer_fn(SIGALRM);
1364 if (one_shot)
1365 break;
1367 return 0;
1370 static int start_timer_thread(void)
1372 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1373 if (timer_event) {
1374 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1375 if (!timer_thread )
1376 return errno = ENOMEM,
1377 error("cannot start timer thread");
1378 } else
1379 return errno = ENOMEM,
1380 error("cannot allocate resources for timer");
1381 return 0;
1384 static void stop_timer_thread(void)
1386 if (timer_event)
1387 SetEvent(timer_event); /* tell thread to terminate */
1388 if (timer_thread) {
1389 int rc = WaitForSingleObject(timer_thread, 1000);
1390 if (rc == WAIT_TIMEOUT)
1391 error("timer thread did not terminate timely");
1392 else if (rc != WAIT_OBJECT_0)
1393 error("waiting for timer thread failed: %lu",
1394 GetLastError());
1395 CloseHandle(timer_thread);
1397 if (timer_event)
1398 CloseHandle(timer_event);
1399 timer_event = NULL;
1400 timer_thread = NULL;
1403 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1405 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1408 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1410 static const struct timeval zero;
1411 static int atexit_done;
1413 if (out != NULL)
1414 return errno = EINVAL,
1415 error("setitimer param 3 != NULL not implemented");
1416 if (!is_timeval_eq(&in->it_interval, &zero) &&
1417 !is_timeval_eq(&in->it_interval, &in->it_value))
1418 return errno = EINVAL,
1419 error("setitimer: it_interval must be zero or eq it_value");
1421 if (timer_thread)
1422 stop_timer_thread();
1424 if (is_timeval_eq(&in->it_value, &zero) &&
1425 is_timeval_eq(&in->it_interval, &zero))
1426 return 0;
1428 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1429 one_shot = is_timeval_eq(&in->it_interval, &zero);
1430 if (!atexit_done) {
1431 atexit(stop_timer_thread);
1432 atexit_done = 1;
1434 return start_timer_thread();
1437 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1439 if (sig != SIGALRM)
1440 return errno = EINVAL,
1441 error("sigaction only implemented for SIGALRM");
1442 if (out != NULL)
1443 return errno = EINVAL,
1444 error("sigaction: param 3 != NULL not implemented");
1446 timer_fn = in->sa_handler;
1447 return 0;
1450 #undef signal
1451 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1453 sig_handler_t old = timer_fn;
1454 if (sig != SIGALRM)
1455 return signal(sig, handler);
1456 timer_fn = handler;
1457 return old;
1460 static const char *make_backslash_path(const char *path)
1462 static char buf[PATH_MAX + 1];
1463 char *c;
1465 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1466 die("Too long path: %.*s", 60, path);
1468 for (c = buf; *c; c++) {
1469 if (*c == '/')
1470 *c = '\\';
1472 return buf;
1475 void mingw_open_html(const char *unixpath)
1477 const char *htmlpath = make_backslash_path(unixpath);
1478 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1479 const char *, const char *, const char *, INT);
1480 T ShellExecute;
1481 HMODULE shell32;
1482 int r;
1484 shell32 = LoadLibrary("shell32.dll");
1485 if (!shell32)
1486 die("cannot load shell32.dll");
1487 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1488 if (!ShellExecute)
1489 die("cannot run browser");
1491 printf("Launching default browser to display HTML ...\n");
1492 r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1493 FreeLibrary(shell32);
1494 /* see the MSDN documentation referring to the result codes here */
1495 if (r <= 32) {
1496 die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1500 int link(const char *oldpath, const char *newpath)
1502 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1503 static T create_hard_link = NULL;
1504 if (!create_hard_link) {
1505 create_hard_link = (T) GetProcAddress(
1506 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1507 if (!create_hard_link)
1508 create_hard_link = (T)-1;
1510 if (create_hard_link == (T)-1) {
1511 errno = ENOSYS;
1512 return -1;
1514 if (!create_hard_link(newpath, oldpath, NULL)) {
1515 errno = err_win_to_posix(GetLastError());
1516 return -1;
1518 return 0;
1521 char *getpass(const char *prompt)
1523 struct strbuf buf = STRBUF_INIT;
1525 fputs(prompt, stderr);
1526 for (;;) {
1527 char c = _getch();
1528 if (c == '\r' || c == '\n')
1529 break;
1530 strbuf_addch(&buf, c);
1532 fputs("\n", stderr);
1533 return strbuf_detach(&buf, NULL);
1536 #ifndef NO_MINGW_REPLACE_READDIR
1537 /* MinGW readdir implementation to avoid extra lstats for Git */
1538 struct mingw_DIR
1540 struct _finddata_t dd_dta; /* disk transfer area for this dir */
1541 struct mingw_dirent dd_dir; /* Our own implementation, including d_type */
1542 long dd_handle; /* _findnext handle */
1543 int dd_stat; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1544 char dd_name[1]; /* given path for dir with search pattern (struct is extended) */
1547 struct dirent *mingw_readdir(DIR *dir)
1549 WIN32_FIND_DATAA buf;
1550 HANDLE handle;
1551 struct mingw_DIR *mdir = (struct mingw_DIR*)dir;
1553 if (!dir->dd_handle) {
1554 errno = EBADF; /* No set_errno for mingw */
1555 return NULL;
1558 if (dir->dd_handle == (long)INVALID_HANDLE_VALUE && dir->dd_stat == 0)
1560 DWORD lasterr;
1561 handle = FindFirstFileA(dir->dd_name, &buf);
1562 lasterr = GetLastError();
1563 dir->dd_handle = (long)handle;
1564 if (handle == INVALID_HANDLE_VALUE && (lasterr != ERROR_NO_MORE_FILES)) {
1565 errno = err_win_to_posix(lasterr);
1566 return NULL;
1568 } else if (dir->dd_handle == (long)INVALID_HANDLE_VALUE) {
1569 return NULL;
1570 } else if (!FindNextFileA((HANDLE)dir->dd_handle, &buf)) {
1571 DWORD lasterr = GetLastError();
1572 FindClose((HANDLE)dir->dd_handle);
1573 dir->dd_handle = (long)INVALID_HANDLE_VALUE;
1574 /* POSIX says you shouldn't set errno when readdir can't
1575 find any more files; so, if another error we leave it set. */
1576 if (lasterr != ERROR_NO_MORE_FILES)
1577 errno = err_win_to_posix(lasterr);
1578 return NULL;
1581 /* We get here if `buf' contains valid data. */
1582 strcpy(dir->dd_dir.d_name, buf.cFileName);
1583 ++dir->dd_stat;
1585 /* Set file type, based on WIN32_FIND_DATA */
1586 mdir->dd_dir.d_type = 0;
1587 if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1588 mdir->dd_dir.d_type |= DT_DIR;
1589 else
1590 mdir->dd_dir.d_type |= DT_REG;
1592 return (struct dirent*)&dir->dd_dir;
1594 #endif // !NO_MINGW_REPLACE_READDIR