mingw: fix st_mode for symlink dirs
[git/dscho.git] / compat / mingw.c
blob6e04c55ce406f39b7ac979482e098fde69844206
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include <winioctl.h>
5 #include <shellapi.h>
6 #include "../strbuf.h"
7 #include "../cache.h"
8 #include "../run-command.h"
10 unsigned int _CRT_fmode = _O_BINARY;
11 static const int delay[] = { 0, 1, 10, 20, 40 };
13 int err_win_to_posix(DWORD winerr)
15 int error = ENOSYS;
16 switch(winerr) {
17 case ERROR_ACCESS_DENIED: error = EACCES; break;
18 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
19 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
20 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
21 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
22 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
23 case ERROR_BAD_COMMAND: error = EIO; break;
24 case ERROR_BAD_DEVICE: error = ENODEV; break;
25 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
26 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
27 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
28 case ERROR_BAD_LENGTH: error = EINVAL; break;
29 case ERROR_BAD_PATHNAME: error = ENOENT; break;
30 case ERROR_BAD_PIPE: error = EPIPE; break;
31 case ERROR_BAD_UNIT: error = ENODEV; break;
32 case ERROR_BAD_USERNAME: error = EINVAL; break;
33 case ERROR_BROKEN_PIPE: error = EPIPE; break;
34 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
35 case ERROR_BUSY: error = EBUSY; break;
36 case ERROR_BUSY_DRIVE: error = EBUSY; break;
37 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
38 case ERROR_CANNOT_MAKE: error = EACCES; break;
39 case ERROR_CANTOPEN: error = EIO; break;
40 case ERROR_CANTREAD: error = EIO; break;
41 case ERROR_CANTWRITE: error = EIO; break;
42 case ERROR_CRC: error = EIO; break;
43 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
44 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
45 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
46 case ERROR_DIRECTORY: error = EINVAL; break;
47 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
48 case ERROR_DISK_CHANGE: error = EIO; break;
49 case ERROR_DISK_FULL: error = ENOSPC; break;
50 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
51 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
52 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
53 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
54 case ERROR_FILE_EXISTS: error = EEXIST; break;
55 case ERROR_FILE_INVALID: error = ENODEV; break;
56 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
57 case ERROR_GEN_FAILURE: error = EIO; break;
58 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
59 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
60 case ERROR_INVALID_ACCESS: error = EACCES; break;
61 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
62 case ERROR_INVALID_BLOCK: error = EFAULT; break;
63 case ERROR_INVALID_DATA: error = EINVAL; break;
64 case ERROR_INVALID_DRIVE: error = ENODEV; break;
65 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
66 case ERROR_INVALID_FLAGS: error = EINVAL; break;
67 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
68 case ERROR_INVALID_HANDLE: error = EBADF; break;
69 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
70 case ERROR_INVALID_NAME: error = EINVAL; break;
71 case ERROR_INVALID_OWNER: error = EINVAL; break;
72 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
73 case ERROR_INVALID_PASSWORD: error = EPERM; break;
74 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
75 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
76 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
77 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
78 case ERROR_IO_DEVICE: error = EIO; break;
79 case ERROR_IO_INCOMPLETE: error = EINTR; break;
80 case ERROR_LOCKED: error = EBUSY; break;
81 case ERROR_LOCK_VIOLATION: error = EACCES; break;
82 case ERROR_LOGON_FAILURE: error = EACCES; break;
83 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
84 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
85 case ERROR_MORE_DATA: error = EPIPE; break;
86 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
87 case ERROR_NOACCESS: error = EFAULT; break;
88 case ERROR_NONE_MAPPED: error = EINVAL; break;
89 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
90 case ERROR_NOT_READY: error = EAGAIN; break;
91 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
92 case ERROR_NO_DATA: error = EPIPE; break;
93 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
94 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
95 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
96 case ERROR_OPEN_FAILED: error = EIO; break;
97 case ERROR_OPEN_FILES: error = EBUSY; break;
98 case ERROR_OPERATION_ABORTED: error = EINTR; break;
99 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
100 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
101 case ERROR_PATH_BUSY: error = EBUSY; break;
102 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
103 case ERROR_PIPE_BUSY: error = EBUSY; break;
104 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
105 case ERROR_PIPE_LISTENING: error = EPIPE; break;
106 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
107 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
108 case ERROR_READ_FAULT: error = EIO; break;
109 case ERROR_SEEK: error = EIO; break;
110 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
111 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
112 case ERROR_SHARING_VIOLATION: error = EACCES; break;
113 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
114 case ERROR_SWAPERROR: error = ENOENT; break;
115 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
116 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
117 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
118 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
119 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
120 case ERROR_WRITE_FAULT: error = EIO; break;
121 case ERROR_WRITE_PROTECT: error = EROFS; break;
123 return error;
126 static int make_hidden(const char *path)
128 DWORD attribs = GetFileAttributes(path);
129 if (SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN | attribs))
130 return 0;
131 errno = err_win_to_posix(GetLastError());
132 return -1;
135 void mingw_mark_as_git_dir(const char *dir)
137 if (hide_dotfiles != HIDE_DOTFILES_FALSE && !is_bare_repository() &&
138 make_hidden(dir))
139 warning("Failed to make '%s' hidden", dir);
140 git_config_set("core.hideDotFiles",
141 hide_dotfiles == HIDE_DOTFILES_FALSE ? "false" :
142 (hide_dotfiles == HIDE_DOTFILES_DOTGITONLY ?
143 "dotGitOnly" : "true"));
146 #undef mkdir
147 int mingw_mkdir(const char *path, int mode)
149 int ret = mkdir(path);
150 if (!ret && hide_dotfiles == HIDE_DOTFILES_TRUE) {
152 * In Windows a file or dir starting with a dot is not
153 * automatically hidden. So lets mark it as hidden when
154 * such a directory is created.
156 const char *start = basename((char*)path);
157 if (*start == '.')
158 return make_hidden(path);
160 return ret;
163 static int ask_user_yes_no(const char *format, ...)
165 char answer[5];
166 char question[4096];
167 const char *retry_hook[] = { NULL, NULL, NULL };
168 va_list args;
170 if ((retry_hook[0] = getenv("GIT_ASK_YESNO"))) {
172 va_start(args, format);
173 vsnprintf(question, sizeof(question), format, args);
174 va_end(args);
176 retry_hook[1] = question;
177 return !run_command_v_opt(retry_hook, 0);
180 if (!isatty(_fileno(stdin)))
181 return 0;
183 while (1) {
184 va_start(args, format);
185 vfprintf(stderr, format, args);
186 va_end(args);
187 fprintf(stderr, " (y/n)? ");
189 if (fgets(answer, sizeof(answer), stdin)) {
190 /* remove the newline */
191 if (answer[strlen(answer)-2] == '\r')
192 answer[strlen(answer)-2] = '\0';
193 if (answer[strlen(answer)-1] == '\n')
194 answer[strlen(answer)-1] = '\0';
195 } else
196 return 0;
198 if (answer[0] == 'y' && strlen(answer) == 1)
199 return 1;
200 if (!strncasecmp(answer, "yes", sizeof(answer)))
201 return 1;
202 if (answer[0] == 'n' && strlen(answer) == 1)
203 return 0;
204 if (!strncasecmp(answer, "no", sizeof(answer)))
205 return 0;
206 fprintf(stderr, "I did not understand your answer: '%s'\n",
207 answer);
211 #undef unlink
212 int mingw_unlink(const char *pathname)
214 int ret, tries = 0;
216 /* read-only files cannot be removed */
217 chmod(pathname, 0666);
218 while ((ret = unlink(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
219 if (errno != EACCES)
220 break;
222 * We assume that some other process had the source or
223 * destination file open at the wrong moment and retry.
224 * In order to give the other process a higher chance to
225 * complete its operation, we give up our time slice now.
226 * If we have to retry again, we do sleep a bit.
228 Sleep(delay[tries]);
229 tries++;
231 while (ret == -1 && errno == EACCES &&
232 ask_user_yes_no("Unlink of file '%s' failed. "
233 "Should I try again?", pathname))
234 ret = unlink(pathname);
235 return ret;
238 #undef rmdir
239 int mingw_rmdir(const char *pathname)
241 int ret, tries = 0;
243 while ((ret = rmdir(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
244 if (errno != EACCES)
245 break;
247 * We assume that some other process had the source or
248 * destination file open at the wrong moment and retry.
249 * In order to give the other process a higher chance to
250 * complete its operation, we give up our time slice now.
251 * If we have to retry again, we do sleep a bit.
253 Sleep(delay[tries]);
254 tries++;
256 while (ret == -1 && errno == EACCES &&
257 ask_user_yes_no("Deletion of directory '%s' failed. "
258 "Should I try again?", pathname))
259 ret = rmdir(pathname);
260 return ret;
263 #undef open
264 int mingw_open (const char *filename, int oflags, ...)
266 va_list args;
267 unsigned mode;
268 int fd;
270 va_start(args, oflags);
271 mode = va_arg(args, int);
272 va_end(args);
274 if (!strcmp(filename, "/dev/null"))
275 filename = "nul";
277 fd = open(filename, oflags | O_BINARY, mode);
279 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
280 DWORD attrs = GetFileAttributes(filename);
281 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
282 errno = EISDIR;
284 if ((oflags & O_CREAT) && fd >= 0 &&
285 hide_dotfiles == HIDE_DOTFILES_TRUE) {
287 * In Windows a file or dir starting with a dot is not
288 * automatically hidden. So lets mark it as hidden when
289 * such a file is created.
291 const char *start = basename((char*)filename);
292 if (*start == '.' && make_hidden(filename))
293 warning("Could not mark '%s' as hidden.", filename);
295 return fd;
298 #undef fopen
299 FILE *mingw_fopen (const char *filename, const char *mode)
301 int hide = 0;
302 FILE *file;
303 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
304 basename((char*)filename)[0] == '.')
305 hide = access(filename, F_OK);
307 file = fopen(strcmp(filename, "/dev/null") ? filename : "NUL", mode);
309 * In Windows a file or dir starting with a dot is not
310 * automatically hidden. So lets mark it as hidden when
311 * such a file is created.
313 if (file && hide && make_hidden(filename))
314 warning("Could not mark '%s' as hidden.", filename);
315 return file;
319 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
320 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
322 static inline long long filetime_to_hnsec(const FILETIME *ft)
324 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
325 /* Windows to Unix Epoch conversion */
326 return winTime - 116444736000000000LL;
329 static inline time_t filetime_to_time_t(const FILETIME *ft)
331 return (time_t)(filetime_to_hnsec(ft) / 10000000);
335 * We keep the do_lstat code in a separate function to avoid recursion.
336 * When a path ends with a slash, the stat will fail with ENOENT. In
337 * this case, we strip the trailing slashes and stat again.
339 * If follow is true then act like stat() and report on the link
340 * target. Otherwise report on the link itself.
342 static int do_lstat(int follow, const char *file_name, struct stat *buf)
344 WIN32_FILE_ATTRIBUTE_DATA fdata;
346 if (!(errno = get_file_attr(file_name, &fdata))) {
347 buf->st_ino = 0;
348 buf->st_gid = 0;
349 buf->st_uid = 0;
350 buf->st_nlink = 1;
351 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
352 buf->st_size = fdata.nFileSizeLow |
353 (((off_t)fdata.nFileSizeHigh)<<32);
354 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
355 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
356 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
357 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
358 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
359 WIN32_FIND_DATAA findbuf;
360 HANDLE handle = FindFirstFileA(file_name, &findbuf);
361 if (handle != INVALID_HANDLE_VALUE) {
362 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
363 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
364 if (follow) {
365 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
366 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
367 } else {
368 buf->st_mode = S_IFLNK;
370 buf->st_mode |= S_IREAD;
371 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
372 buf->st_mode |= S_IWRITE;
374 FindClose(handle);
377 return 0;
379 return -1;
383 * We provide our own lstat/fstat functions, since the provided
384 * lstat/fstat functions are so slow. These stat functions are
385 * tailored for Git's usage (read: fast), and are not meant to be
386 * complete. Note that Git stat()s are redirected to mingw_lstat()
387 * too, since Windows doesn't really handle symlinks that well.
389 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
391 int namelen;
392 static char alt_name[PATH_MAX];
394 if (!do_lstat(follow, file_name, buf))
395 return 0;
398 * if file_name ended in a '/', Windows returned ENOENT;
399 * try again without trailing slashes
401 if (errno != ENOENT)
402 return -1;
404 namelen = strlen(file_name);
405 if (namelen && file_name[namelen-1] != '/')
406 return -1;
407 while (namelen && file_name[namelen-1] == '/')
408 --namelen;
409 if (!namelen || namelen >= PATH_MAX)
410 return -1;
412 memcpy(alt_name, file_name, namelen);
413 alt_name[namelen] = 0;
414 return do_lstat(follow, alt_name, buf);
417 int mingw_lstat(const char *file_name, struct stat *buf)
419 return do_stat_internal(0, file_name, buf);
421 int mingw_stat(const char *file_name, struct stat *buf)
423 return do_stat_internal(1, file_name, buf);
426 #undef fstat
427 int mingw_fstat(int fd, struct stat *buf)
429 HANDLE fh = (HANDLE)_get_osfhandle(fd);
430 BY_HANDLE_FILE_INFORMATION fdata;
432 if (fh == INVALID_HANDLE_VALUE) {
433 errno = EBADF;
434 return -1;
436 /* direct non-file handles to MS's fstat() */
437 if (GetFileType(fh) != FILE_TYPE_DISK)
438 return _fstati64(fd, buf);
440 if (GetFileInformationByHandle(fh, &fdata)) {
441 buf->st_ino = 0;
442 buf->st_gid = 0;
443 buf->st_uid = 0;
444 buf->st_nlink = 1;
445 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
446 buf->st_size = fdata.nFileSizeLow |
447 (((off_t)fdata.nFileSizeHigh)<<32);
448 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
449 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
450 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
451 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
452 return 0;
454 errno = EBADF;
455 return -1;
458 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
460 long long winTime = t * 10000000LL + 116444736000000000LL;
461 ft->dwLowDateTime = winTime;
462 ft->dwHighDateTime = winTime >> 32;
465 int mingw_utime (const char *file_name, const struct utimbuf *times)
467 FILETIME mft, aft;
468 int fh, rc;
470 /* must have write permission */
471 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
472 return -1;
474 time_t_to_filetime(times->modtime, &mft);
475 time_t_to_filetime(times->actime, &aft);
476 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
477 errno = EINVAL;
478 rc = -1;
479 } else
480 rc = 0;
481 close(fh);
482 return rc;
485 unsigned int sleep (unsigned int seconds)
487 Sleep(seconds*1000);
488 return 0;
491 int mkstemp(char *template)
493 char *filename = mktemp(template);
494 if (filename == NULL)
495 return -1;
496 return open(filename, O_RDWR | O_CREAT | O_BINARY, 0600);
499 int gettimeofday(struct timeval *tv, void *tz)
501 FILETIME ft;
502 long long hnsec;
504 GetSystemTimeAsFileTime(&ft);
505 hnsec = filetime_to_hnsec(&ft);
506 tv->tv_sec = hnsec / 10000000;
507 tv->tv_usec = (hnsec % 10000000) / 10;
508 return 0;
511 int pipe(int filedes[2])
513 HANDLE h[2];
515 /* this creates non-inheritable handles */
516 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
517 errno = err_win_to_posix(GetLastError());
518 return -1;
520 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
521 if (filedes[0] < 0) {
522 CloseHandle(h[0]);
523 CloseHandle(h[1]);
524 return -1;
526 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
527 if (filedes[0] < 0) {
528 close(filedes[0]);
529 CloseHandle(h[1]);
530 return -1;
532 return 0;
535 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
537 int i, pending;
539 if (timeout >= 0) {
540 if (nfds == 0) {
541 Sleep(timeout);
542 return 0;
544 return errno = EINVAL, error("poll timeout not supported");
548 * When there is only one fd to wait for, then we pretend that
549 * input is available and let the actual wait happen when the
550 * caller invokes read().
552 if (nfds == 1) {
553 if (!(ufds[0].events & POLLIN))
554 return errno = EINVAL, error("POLLIN not set");
555 ufds[0].revents = POLLIN;
556 return 0;
559 repeat:
560 pending = 0;
561 for (i = 0; i < nfds; i++) {
562 DWORD avail = 0;
563 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
564 if (h == INVALID_HANDLE_VALUE)
565 return -1; /* errno was set */
567 if (!(ufds[i].events & POLLIN))
568 return errno = EINVAL, error("POLLIN not set");
570 /* this emulation works only for pipes */
571 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
572 int err = GetLastError();
573 if (err == ERROR_BROKEN_PIPE) {
574 ufds[i].revents = POLLHUP;
575 pending++;
576 } else {
577 errno = EINVAL;
578 return error("PeekNamedPipe failed,"
579 " GetLastError: %u", err);
581 } else if (avail) {
582 ufds[i].revents = POLLIN;
583 pending++;
584 } else
585 ufds[i].revents = 0;
587 if (!pending) {
589 * The only times that we spin here is when the process
590 * that is connected through the pipes is waiting for
591 * its own input data to become available. But since
592 * the process (pack-objects) is itself CPU intensive,
593 * it will happily pick up the time slice that we are
594 * relinquishing here.
596 Sleep(0);
597 goto repeat;
599 return 0;
602 struct tm *gmtime_r(const time_t *timep, struct tm *result)
604 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
605 memcpy(result, gmtime(timep), sizeof(struct tm));
606 return result;
609 struct tm *localtime_r(const time_t *timep, struct tm *result)
611 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
612 memcpy(result, localtime(timep), sizeof(struct tm));
613 return result;
616 #undef getcwd
617 char *mingw_getcwd(char *pointer, int len)
619 int i;
620 char *ret = getcwd(pointer, len);
621 if (!ret)
622 return ret;
623 for (i = 0; pointer[i]; i++)
624 if (pointer[i] == '\\')
625 pointer[i] = '/';
626 return ret;
629 #undef getenv
630 char *mingw_getenv(const char *name)
632 char *result = getenv(name);
633 if (!result && !strcmp(name, "TMPDIR")) {
634 /* on Windows it is TMP and TEMP */
635 result = getenv("TMP");
636 if (!result)
637 result = getenv("TEMP");
639 return result;
643 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
644 * (Parsing C++ Command-Line Arguments)
646 static const char *quote_arg(const char *arg)
648 /* count chars to quote */
649 int len = 0, n = 0;
650 int force_quotes = 0;
651 char *q, *d;
652 const char *p = arg;
653 if (!*p) force_quotes = 1;
654 while (*p) {
655 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
656 force_quotes = 1;
657 else if (*p == '"')
658 n++;
659 else if (*p == '\\') {
660 int count = 0;
661 while (*p == '\\') {
662 count++;
663 p++;
664 len++;
666 if (*p == '"')
667 n += count*2 + 1;
668 continue;
670 len++;
671 p++;
673 if (!force_quotes && n == 0)
674 return arg;
676 /* insert \ where necessary */
677 d = q = xmalloc(len+n+3);
678 *d++ = '"';
679 while (*arg) {
680 if (*arg == '"')
681 *d++ = '\\';
682 else if (*arg == '\\') {
683 int count = 0;
684 while (*arg == '\\') {
685 count++;
686 *d++ = *arg++;
688 if (*arg == '"') {
689 while (count-- > 0)
690 *d++ = '\\';
691 *d++ = '\\';
694 *d++ = *arg++;
696 *d++ = '"';
697 *d++ = 0;
698 return q;
701 static const char *parse_interpreter(const char *cmd)
703 static char buf[100];
704 char *p, *opt;
705 int n, fd;
707 /* don't even try a .exe */
708 n = strlen(cmd);
709 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
710 return NULL;
712 fd = open(cmd, O_RDONLY);
713 if (fd < 0)
714 return NULL;
715 n = read(fd, buf, sizeof(buf)-1);
716 close(fd);
717 if (n < 4) /* at least '#!/x' and not error */
718 return NULL;
720 if (buf[0] != '#' || buf[1] != '!')
721 return NULL;
722 buf[n] = '\0';
723 p = buf + strcspn(buf, "\r\n");
724 if (!*p)
725 return NULL;
727 *p = '\0';
728 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
729 return NULL;
730 /* strip options */
731 if ((opt = strchr(p+1, ' ')))
732 *opt = '\0';
733 return p+1;
737 * Splits the PATH into parts.
739 static char **get_path_split(void)
741 char *p, **path, *envpath = getenv("PATH");
742 int i, n = 0;
744 if (!envpath || !*envpath)
745 return NULL;
747 envpath = xstrdup(envpath);
748 p = envpath;
749 while (p) {
750 char *dir = p;
751 p = strchr(p, ';');
752 if (p) *p++ = '\0';
753 if (*dir) { /* not earlier, catches series of ; */
754 ++n;
757 if (!n)
758 return NULL;
760 path = xmalloc((n+1)*sizeof(char *));
761 p = envpath;
762 i = 0;
763 do {
764 if (*p)
765 path[i++] = xstrdup(p);
766 p = p+strlen(p)+1;
767 } while (i < n);
768 path[i] = NULL;
770 free(envpath);
772 return path;
775 static void free_path_split(char **path)
777 char **p = path;
779 if (!path)
780 return;
782 while (*p)
783 free(*p++);
784 free(path);
788 * exe_only means that we only want to detect .exe files, but not scripts
789 * (which do not have an extension)
791 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
793 char path[MAX_PATH];
794 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
796 if (!isexe && access(path, F_OK) == 0)
797 return xstrdup(path);
798 path[strlen(path)-4] = '\0';
799 if ((!exe_only || isexe) && access(path, F_OK) == 0)
800 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
801 return xstrdup(path);
802 return NULL;
806 * Determines the absolute path of cmd using the the split path in path.
807 * If cmd contains a slash or backslash, no lookup is performed.
809 static char *path_lookup(const char *cmd, char **path, int exe_only)
811 char *prog = NULL;
812 int len = strlen(cmd);
813 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
815 if (strchr(cmd, '/') || strchr(cmd, '\\'))
816 prog = xstrdup(cmd);
818 while (!prog && *path)
819 prog = lookup_prog(*path++, cmd, isexe, exe_only);
821 return prog;
824 static int env_compare(const void *a, const void *b)
826 char *const *ea = a;
827 char *const *eb = b;
828 return strcasecmp(*ea, *eb);
831 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
832 int prepend_cmd, int fhin, int fhout, int fherr)
834 STARTUPINFO si;
835 PROCESS_INFORMATION pi;
836 struct strbuf envblk, args;
837 unsigned flags;
838 BOOL ret;
840 /* Determine whether or not we are associated to a console */
841 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
842 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
843 FILE_ATTRIBUTE_NORMAL, NULL);
844 if (cons == INVALID_HANDLE_VALUE) {
846 * There is no console associated with this process.
847 * Since the child is a console process, Windows
848 * would normally create a console window. But
849 * since we'll be redirecting std streams, we do
850 * not need the console.
851 * It is necessary to use DETACHED_PROCESS
852 * instead of CREATE_NO_WINDOW to make ssh
853 * recognize that it has no console.
855 flags = DETACHED_PROCESS;
856 } else {
858 * There is already a console. If we specified
859 * DETACHED_PROCESS here, too, Windows would
860 * disassociate the child from the console.
861 * The same is true for CREATE_NO_WINDOW.
862 * Go figure!
864 flags = 0;
865 CloseHandle(cons);
867 memset(&si, 0, sizeof(si));
868 si.cb = sizeof(si);
869 si.dwFlags = STARTF_USESTDHANDLES;
870 si.hStdInput = (HANDLE) _get_osfhandle(fhin);
871 si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
872 si.hStdError = (HANDLE) _get_osfhandle(fherr);
874 /* concatenate argv, quoting args as we go */
875 strbuf_init(&args, 0);
876 if (prepend_cmd) {
877 char *quoted = (char *)quote_arg(cmd);
878 strbuf_addstr(&args, quoted);
879 if (quoted != cmd)
880 free(quoted);
882 for (; *argv; argv++) {
883 char *quoted = (char *)quote_arg(*argv);
884 if (*args.buf)
885 strbuf_addch(&args, ' ');
886 strbuf_addstr(&args, quoted);
887 if (quoted != *argv)
888 free(quoted);
891 if (env) {
892 int count = 0;
893 char **e, **sorted_env;
895 for (e = env; *e; e++)
896 count++;
898 /* environment must be sorted */
899 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
900 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
901 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
903 strbuf_init(&envblk, 0);
904 for (e = sorted_env; *e; e++) {
905 strbuf_addstr(&envblk, *e);
906 strbuf_addch(&envblk, '\0');
908 free(sorted_env);
911 memset(&pi, 0, sizeof(pi));
912 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
913 env ? envblk.buf : NULL, NULL, &si, &pi);
915 if (env)
916 strbuf_release(&envblk);
917 strbuf_release(&args);
919 if (!ret) {
920 errno = ENOENT;
921 return -1;
923 CloseHandle(pi.hThread);
924 return (pid_t)pi.hProcess;
927 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
928 int prepend_cmd)
930 return mingw_spawnve_fd(cmd, argv, env, prepend_cmd, 0, 1, 2);
933 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
934 int fhin, int fhout, int fherr)
936 pid_t pid;
937 char **path = get_path_split();
938 char *prog = path_lookup(cmd, path, 0);
940 if (!prog) {
941 errno = ENOENT;
942 pid = -1;
944 else {
945 const char *interpr = parse_interpreter(prog);
947 if (interpr) {
948 const char *argv0 = argv[0];
949 char *iprog = path_lookup(interpr, path, 1);
950 argv[0] = prog;
951 if (!iprog) {
952 errno = ENOENT;
953 pid = -1;
955 else {
956 pid = mingw_spawnve_fd(iprog, argv, env, 1,
957 fhin, fhout, fherr);
958 free(iprog);
960 argv[0] = argv0;
962 else
963 pid = mingw_spawnve_fd(prog, argv, env, 0,
964 fhin, fhout, fherr);
965 free(prog);
967 free_path_split(path);
968 return pid;
971 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
973 const char *interpr = parse_interpreter(cmd);
974 char **path;
975 char *prog;
976 int pid = 0;
978 if (!interpr)
979 return 0;
980 path = get_path_split();
981 prog = path_lookup(interpr, path, 1);
982 if (prog) {
983 int argc = 0;
984 const char **argv2;
985 while (argv[argc]) argc++;
986 argv2 = xmalloc(sizeof(*argv) * (argc+1));
987 argv2[0] = (char *)cmd; /* full path to the script file */
988 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
989 pid = mingw_spawnve(prog, argv2, env, 1);
990 if (pid >= 0) {
991 int status;
992 if (waitpid(pid, &status, 0) < 0)
993 status = 255;
994 exit(status);
996 pid = 1; /* indicate that we tried but failed */
997 free(prog);
998 free(argv2);
1000 free_path_split(path);
1001 return pid;
1004 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
1006 /* check if git_command is a shell script */
1007 if (!try_shell_exec(cmd, argv, (char **)env)) {
1008 int pid, status;
1010 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
1011 if (pid < 0)
1012 return;
1013 if (waitpid(pid, &status, 0) < 0)
1014 status = 255;
1015 exit(status);
1019 void mingw_execvp(const char *cmd, char *const *argv)
1021 char **path = get_path_split();
1022 char *prog = path_lookup(cmd, path, 0);
1024 if (prog) {
1025 mingw_execve(prog, argv, environ);
1026 free(prog);
1027 } else
1028 errno = ENOENT;
1030 free_path_split(path);
1033 static char **copy_environ(void)
1035 char **env;
1036 int i = 0;
1037 while (environ[i])
1038 i++;
1039 env = xmalloc((i+1)*sizeof(*env));
1040 for (i = 0; environ[i]; i++)
1041 env[i] = xstrdup(environ[i]);
1042 env[i] = NULL;
1043 return env;
1046 void free_environ(char **env)
1048 int i;
1049 for (i = 0; env[i]; i++)
1050 free(env[i]);
1051 free(env);
1054 static int lookup_env(char **env, const char *name, size_t nmln)
1056 int i;
1058 for (i = 0; env[i]; i++) {
1059 if (0 == strncmp(env[i], name, nmln)
1060 && '=' == env[i][nmln])
1061 /* matches */
1062 return i;
1064 return -1;
1068 * If name contains '=', then sets the variable, otherwise it unsets it
1070 static char **env_setenv(char **env, const char *name)
1072 char *eq = strchrnul(name, '=');
1073 int i = lookup_env(env, name, eq-name);
1075 if (i < 0) {
1076 if (*eq) {
1077 for (i = 0; env[i]; i++)
1079 env = xrealloc(env, (i+2)*sizeof(*env));
1080 env[i] = xstrdup(name);
1081 env[i+1] = NULL;
1084 else {
1085 free(env[i]);
1086 if (*eq)
1087 env[i] = xstrdup(name);
1088 else
1089 for (; env[i]; i++)
1090 env[i] = env[i+1];
1092 return env;
1096 * Copies global environ and adjusts variables as specified by vars.
1098 char **make_augmented_environ(const char *const *vars)
1100 char **env = copy_environ();
1102 while (*vars)
1103 env = env_setenv(env, *vars++);
1104 return env;
1108 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1109 * that service contains a numerical port, or that it it is null. It
1110 * does a simple search using gethostbyname, and returns one IPv4 host
1111 * if one was found.
1113 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1114 const struct addrinfo *hints,
1115 struct addrinfo **res)
1117 struct hostent *h = gethostbyname(node);
1118 struct addrinfo *ai;
1119 struct sockaddr_in *sin;
1121 if (!h)
1122 return WSAGetLastError();
1124 ai = xmalloc(sizeof(struct addrinfo));
1125 *res = ai;
1126 ai->ai_flags = 0;
1127 ai->ai_family = AF_INET;
1128 ai->ai_socktype = hints->ai_socktype;
1129 switch (hints->ai_socktype) {
1130 case SOCK_STREAM:
1131 ai->ai_protocol = IPPROTO_TCP;
1132 break;
1133 case SOCK_DGRAM:
1134 ai->ai_protocol = IPPROTO_UDP;
1135 break;
1136 default:
1137 ai->ai_protocol = 0;
1138 break;
1140 ai->ai_addrlen = sizeof(struct sockaddr_in);
1141 ai->ai_canonname = strdup(h->h_name);
1143 sin = xmalloc(ai->ai_addrlen);
1144 memset(sin, 0, ai->ai_addrlen);
1145 sin->sin_family = AF_INET;
1146 if (service)
1147 sin->sin_port = htons(atoi(service));
1148 sin->sin_addr = *(struct in_addr *)h->h_addr;
1149 ai->ai_addr = (struct sockaddr *)sin;
1150 ai->ai_next = 0;
1151 return 0;
1154 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1156 free(res->ai_canonname);
1157 free(res->ai_addr);
1158 free(res);
1161 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1162 char *host, DWORD hostlen,
1163 char *serv, DWORD servlen, int flags)
1165 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1166 if (sa->sa_family != AF_INET)
1167 return EAI_FAMILY;
1168 if (!host && !serv)
1169 return EAI_NONAME;
1171 if (host && hostlen > 0) {
1172 struct hostent *ent = NULL;
1173 if (!(flags & NI_NUMERICHOST))
1174 ent = gethostbyaddr((const char *)&sin->sin_addr,
1175 sizeof(sin->sin_addr), AF_INET);
1177 if (ent)
1178 snprintf(host, hostlen, "%s", ent->h_name);
1179 else if (flags & NI_NAMEREQD)
1180 return EAI_NONAME;
1181 else
1182 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1185 if (serv && servlen > 0) {
1186 struct servent *ent = NULL;
1187 if (!(flags & NI_NUMERICSERV))
1188 ent = getservbyport(sin->sin_port,
1189 flags & NI_DGRAM ? "udp" : "tcp");
1191 if (ent)
1192 snprintf(serv, servlen, "%s", ent->s_name);
1193 else
1194 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1197 return 0;
1200 static HMODULE ipv6_dll = NULL;
1201 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1202 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1203 const struct addrinfo *hints,
1204 struct addrinfo **res);
1205 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1206 char *host, DWORD hostlen,
1207 char *serv, DWORD servlen, int flags);
1209 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1210 * don't need to try to load that one dynamically.
1213 static void socket_cleanup(void)
1215 WSACleanup();
1216 if (ipv6_dll)
1217 FreeLibrary(ipv6_dll);
1218 ipv6_dll = NULL;
1219 ipv6_freeaddrinfo = freeaddrinfo_stub;
1220 ipv6_getaddrinfo = getaddrinfo_stub;
1221 ipv6_getnameinfo = getnameinfo_stub;
1224 static void ensure_socket_initialization(void)
1226 WSADATA wsa;
1227 static int initialized = 0;
1228 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1229 const char **name;
1231 if (initialized)
1232 return;
1234 if (WSAStartup(MAKEWORD(2,2), &wsa))
1235 die("unable to initialize winsock subsystem, error %d",
1236 WSAGetLastError());
1238 for (name = libraries; *name; name++) {
1239 ipv6_dll = LoadLibrary(*name);
1240 if (!ipv6_dll)
1241 continue;
1243 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1244 GetProcAddress(ipv6_dll, "freeaddrinfo");
1245 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1246 const struct addrinfo *,
1247 struct addrinfo **))
1248 GetProcAddress(ipv6_dll, "getaddrinfo");
1249 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1250 socklen_t, char *, DWORD,
1251 char *, DWORD, int))
1252 GetProcAddress(ipv6_dll, "getnameinfo");
1253 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1254 FreeLibrary(ipv6_dll);
1255 ipv6_dll = NULL;
1256 } else
1257 break;
1259 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1260 ipv6_freeaddrinfo = freeaddrinfo_stub;
1261 ipv6_getaddrinfo = getaddrinfo_stub;
1262 ipv6_getnameinfo = getnameinfo_stub;
1265 atexit(socket_cleanup);
1266 initialized = 1;
1269 #undef gethostbyname
1270 struct hostent *mingw_gethostbyname(const char *host)
1272 ensure_socket_initialization();
1273 return gethostbyname(host);
1276 void mingw_freeaddrinfo(struct addrinfo *res)
1278 ipv6_freeaddrinfo(res);
1281 int mingw_getaddrinfo(const char *node, const char *service,
1282 const struct addrinfo *hints, struct addrinfo **res)
1284 ensure_socket_initialization();
1285 return ipv6_getaddrinfo(node, service, hints, res);
1288 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1289 char *host, DWORD hostlen, char *serv, DWORD servlen,
1290 int flags)
1292 ensure_socket_initialization();
1293 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1296 int mingw_socket(int domain, int type, int protocol)
1298 int sockfd;
1299 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
1300 if (s == INVALID_SOCKET) {
1302 * WSAGetLastError() values are regular BSD error codes
1303 * biased by WSABASEERR.
1304 * However, strerror() does not know about networking
1305 * specific errors, which are values beginning at 38 or so.
1306 * Therefore, we choose to leave the biased error code
1307 * in errno so that _if_ someone looks up the code somewhere,
1308 * then it is at least the number that are usually listed.
1310 errno = WSAGetLastError();
1311 return -1;
1313 /* convert into a file descriptor */
1314 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1315 closesocket(s);
1316 return error("unable to make a socket file descriptor: %s",
1317 strerror(errno));
1319 return sockfd;
1322 #undef connect
1323 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1325 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1326 return connect(s, sa, sz);
1329 #undef rename
1330 int mingw_rename(const char *pold, const char *pnew)
1332 DWORD attrs, gle;
1333 int tries = 0;
1336 * Try native rename() first to get errno right.
1337 * It is based on MoveFile(), which cannot overwrite existing files.
1339 if (!rename(pold, pnew))
1340 return 0;
1341 if (errno != EEXIST)
1342 return -1;
1343 repeat:
1344 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1345 return 0;
1346 /* TODO: translate more errors */
1347 gle = GetLastError();
1348 if (gle == ERROR_ACCESS_DENIED &&
1349 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1350 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1351 errno = EISDIR;
1352 return -1;
1354 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1355 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1356 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1357 return 0;
1358 gle = GetLastError();
1359 /* revert file attributes on failure */
1360 SetFileAttributes(pnew, attrs);
1363 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1365 * We assume that some other process had the source or
1366 * destination file open at the wrong moment and retry.
1367 * In order to give the other process a higher chance to
1368 * complete its operation, we give up our time slice now.
1369 * If we have to retry again, we do sleep a bit.
1371 Sleep(delay[tries]);
1372 tries++;
1373 goto repeat;
1375 if (gle == ERROR_ACCESS_DENIED &&
1376 ask_user_yes_no("Rename from '%s' to '%s' failed. "
1377 "Should I try again?", pold, pnew))
1378 goto repeat;
1380 errno = EACCES;
1381 return -1;
1385 * Note that this doesn't return the actual pagesize, but
1386 * the allocation granularity. If future Windows specific git code
1387 * needs the real getpagesize function, we need to find another solution.
1389 int mingw_getpagesize(void)
1391 SYSTEM_INFO si;
1392 GetSystemInfo(&si);
1393 return si.dwAllocationGranularity;
1396 struct passwd *getpwuid(int uid)
1398 static char user_name[100];
1399 static struct passwd p;
1401 DWORD len = sizeof(user_name);
1402 if (!GetUserName(user_name, &len))
1403 return NULL;
1404 p.pw_name = user_name;
1405 p.pw_gecos = "unknown";
1406 p.pw_dir = NULL;
1407 return &p;
1410 static HANDLE timer_event;
1411 static HANDLE timer_thread;
1412 static int timer_interval;
1413 static int one_shot;
1414 static sig_handler_t timer_fn = SIG_DFL;
1417 * The timer works like this:
1418 * The thread, ticktack(), is a trivial routine that most of the time
1419 * only waits to receive the signal to terminate. The main thread tells
1420 * the thread to terminate by setting the timer_event to the signalled
1421 * state.
1422 * But ticktack() interrupts the wait state after the timer's interval
1423 * length to call the signal handler.
1426 static unsigned __stdcall ticktack(void *dummy)
1428 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1429 if (timer_fn == SIG_DFL)
1430 die("Alarm");
1431 if (timer_fn != SIG_IGN)
1432 timer_fn(SIGALRM);
1433 if (one_shot)
1434 break;
1436 return 0;
1439 static int start_timer_thread(void)
1441 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1442 if (timer_event) {
1443 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1444 if (!timer_thread )
1445 return errno = ENOMEM,
1446 error("cannot start timer thread");
1447 } else
1448 return errno = ENOMEM,
1449 error("cannot allocate resources for timer");
1450 return 0;
1453 static void stop_timer_thread(void)
1455 if (timer_event)
1456 SetEvent(timer_event); /* tell thread to terminate */
1457 if (timer_thread) {
1458 int rc = WaitForSingleObject(timer_thread, 1000);
1459 if (rc == WAIT_TIMEOUT)
1460 error("timer thread did not terminate timely");
1461 else if (rc != WAIT_OBJECT_0)
1462 error("waiting for timer thread failed: %lu",
1463 GetLastError());
1464 CloseHandle(timer_thread);
1466 if (timer_event)
1467 CloseHandle(timer_event);
1468 timer_event = NULL;
1469 timer_thread = NULL;
1472 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1474 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1477 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1479 static const struct timeval zero;
1480 static int atexit_done;
1482 if (out != NULL)
1483 return errno = EINVAL,
1484 error("setitimer param 3 != NULL not implemented");
1485 if (!is_timeval_eq(&in->it_interval, &zero) &&
1486 !is_timeval_eq(&in->it_interval, &in->it_value))
1487 return errno = EINVAL,
1488 error("setitimer: it_interval must be zero or eq it_value");
1490 if (timer_thread)
1491 stop_timer_thread();
1493 if (is_timeval_eq(&in->it_value, &zero) &&
1494 is_timeval_eq(&in->it_interval, &zero))
1495 return 0;
1497 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1498 one_shot = is_timeval_eq(&in->it_interval, &zero);
1499 if (!atexit_done) {
1500 atexit(stop_timer_thread);
1501 atexit_done = 1;
1503 return start_timer_thread();
1506 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1508 if (sig != SIGALRM)
1509 return errno = EINVAL,
1510 error("sigaction only implemented for SIGALRM");
1511 if (out != NULL)
1512 return errno = EINVAL,
1513 error("sigaction: param 3 != NULL not implemented");
1515 timer_fn = in->sa_handler;
1516 return 0;
1519 #undef signal
1520 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1522 sig_handler_t old = timer_fn;
1523 if (sig != SIGALRM)
1524 return signal(sig, handler);
1525 timer_fn = handler;
1526 return old;
1529 static const char *make_backslash_path(const char *path, char *buf)
1531 char *c;
1533 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1534 die("Too long path: %.*s", 60, path);
1536 for (c = buf; *c; c++) {
1537 if (*c == '/')
1538 *c = '\\';
1540 return buf;
1543 void mingw_open_html(const char *unixpath)
1545 char buf[PATH_MAX + 1];
1546 const char *htmlpath = make_backslash_path(unixpath, buf);
1547 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1548 const char *, const char *, const char *, INT);
1549 T ShellExecute;
1550 HMODULE shell32;
1551 int r;
1553 shell32 = LoadLibrary("shell32.dll");
1554 if (!shell32)
1555 die("cannot load shell32.dll");
1556 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1557 if (!ShellExecute)
1558 die("cannot run browser");
1560 printf("Launching default browser to display HTML ...\n");
1561 r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1562 FreeLibrary(shell32);
1563 /* see the MSDN documentation referring to the result codes here */
1564 if (r <= 32) {
1565 die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1569 int link(const char *oldpath, const char *newpath)
1571 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1572 static T create_hard_link = NULL;
1573 if (!create_hard_link) {
1574 create_hard_link = (T) GetProcAddress(
1575 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1576 if (!create_hard_link)
1577 create_hard_link = (T)-1;
1579 if (create_hard_link == (T)-1) {
1580 errno = ENOSYS;
1581 return -1;
1583 if (!create_hard_link(newpath, oldpath, NULL)) {
1584 errno = err_win_to_posix(GetLastError());
1585 return -1;
1587 return 0;
1590 int symlink(const char *oldpath, const char *newpath)
1592 typedef BOOL WINAPI (*symlink_fn)(const char*, const char*, DWORD);
1593 static symlink_fn create_symbolic_link = NULL;
1594 char buf[PATH_MAX + 1];
1596 if (!create_symbolic_link) {
1597 create_symbolic_link = (symlink_fn) GetProcAddress(
1598 GetModuleHandle("kernel32.dll"), "CreateSymbolicLinkA");
1599 if (!create_symbolic_link)
1600 create_symbolic_link = (symlink_fn)-1;
1602 if (create_symbolic_link == (symlink_fn)-1) {
1603 errno = ENOSYS;
1604 return -1;
1607 if (!create_symbolic_link(newpath, make_backslash_path(oldpath, buf), 0)) {
1608 errno = err_win_to_posix(GetLastError());
1609 return -1;
1611 return 0;
1614 int readlink(const char *path, char *buf, size_t bufsiz)
1616 HANDLE handle = CreateFile(path, GENERIC_READ,
1617 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1618 NULL, OPEN_EXISTING,
1619 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1620 NULL);
1622 if (handle != INVALID_HANDLE_VALUE) {
1623 unsigned char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1624 DWORD dummy = 0;
1625 if (DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0, buffer,
1626 MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dummy, NULL)) {
1627 REPARSE_DATA_BUFFER *b = (REPARSE_DATA_BUFFER *) buffer;
1628 if (b->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
1629 int len = b->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
1630 int offset = b->SymbolicLinkReparseBuffer.SubstituteNameOffset / sizeof(wchar_t);
1631 int i;
1632 snprintf(buf, bufsiz, "%*ls", len, & b->SymbolicLinkReparseBuffer.PathBuffer[offset]);
1633 for (i = 0; i < len; i++)
1634 if (buf[i] == '\\')
1635 buf[i] = '/';
1636 CloseHandle(handle);
1637 return len;
1641 CloseHandle(handle);
1644 errno = EINVAL;
1645 return -1;
1648 char *getpass(const char *prompt)
1650 struct strbuf buf = STRBUF_INIT;
1652 fputs(prompt, stderr);
1653 for (;;) {
1654 char c = _getch();
1655 if (c == '\r' || c == '\n')
1656 break;
1657 strbuf_addch(&buf, c);
1659 fputs("\n", stderr);
1660 return strbuf_detach(&buf, NULL);
1663 #ifndef NO_MINGW_REPLACE_READDIR
1664 /* MinGW readdir implementation to avoid extra lstats for Git */
1665 struct mingw_DIR
1667 struct _finddata_t dd_dta; /* disk transfer area for this dir */
1668 struct mingw_dirent dd_dir; /* Our own implementation, including d_type */
1669 long dd_handle; /* _findnext handle */
1670 int dd_stat; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1671 char dd_name[1]; /* given path for dir with search pattern (struct is extended) */
1674 struct dirent *mingw_readdir(DIR *dir)
1676 WIN32_FIND_DATAA buf;
1677 HANDLE handle;
1678 struct mingw_DIR *mdir = (struct mingw_DIR*)dir;
1680 if (!dir->dd_handle) {
1681 errno = EBADF; /* No set_errno for mingw */
1682 return NULL;
1685 if (dir->dd_handle == (long)INVALID_HANDLE_VALUE && dir->dd_stat == 0)
1687 DWORD lasterr;
1688 handle = FindFirstFileA(dir->dd_name, &buf);
1689 lasterr = GetLastError();
1690 dir->dd_handle = (long)handle;
1691 if (handle == INVALID_HANDLE_VALUE && (lasterr != ERROR_NO_MORE_FILES)) {
1692 errno = err_win_to_posix(lasterr);
1693 return NULL;
1695 } else if (dir->dd_handle == (long)INVALID_HANDLE_VALUE) {
1696 return NULL;
1697 } else if (!FindNextFileA((HANDLE)dir->dd_handle, &buf)) {
1698 DWORD lasterr = GetLastError();
1699 FindClose((HANDLE)dir->dd_handle);
1700 dir->dd_handle = (long)INVALID_HANDLE_VALUE;
1702 * POSIX says you shouldn't set errno when readdir can't
1703 * find any more files; so, if another error we leave it set.
1705 if (lasterr != ERROR_NO_MORE_FILES)
1706 errno = err_win_to_posix(lasterr);
1707 return NULL;
1710 /* We get here if `buf' contains valid data. */
1711 strcpy(dir->dd_dir.d_name, buf.cFileName);
1712 ++dir->dd_stat;
1714 /* Set file type, based on WIN32_FIND_DATA */
1715 mdir->dd_dir.d_type = 0;
1716 if ((buf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1717 (buf.dwReserved0 == IO_REPARSE_TAG_SYMLINK))
1718 mdir->dd_dir.d_type |= DT_LNK;
1719 else if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1720 mdir->dd_dir.d_type |= DT_DIR;
1721 else
1722 mdir->dd_dir.d_type |= DT_REG;
1724 return (struct dirent*)&dir->dd_dir;
1726 #endif // !NO_MINGW_REPLACE_READDIR