Merge remote branch 'origin/hv/win-interactive-unlink' into work/1.7.0.2
[git/mingw/4msysgit.git] / compat / mingw.c
blob0df1a3d5ea6a90be77dc420969ece820378beaac
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 && make_hidden(dir))
138 warning("Failed to make '%s' hidden", dir);
139 git_config_set("core.hideDotFiles",
140 hide_dotfiles == HIDE_DOTFILES_FALSE ? "false" :
141 (hide_dotfiles == HIDE_DOTFILES_DOTGITONLY ?
142 "dotGitOnly" : "true"));
145 #undef mkdir
146 int mingw_mkdir(const char *path, int mode)
148 int ret = mkdir(path);
149 if (!ret && hide_dotfiles == HIDE_DOTFILES_TRUE) {
151 * In Windows a file or dir starting with a dot is not
152 * automatically hidden. So lets mark it as hidden when
153 * such a directory is created.
155 const char *start = basename((char*)path);
156 if (*start == '.')
157 return make_hidden(path);
159 return ret;
162 static int ask_user_yes_no(const char *format, ...)
164 char answer[5];
165 char question[4096];
166 const char *retry_hook[] = { NULL, NULL, NULL };
167 va_list args;
169 if ((retry_hook[0] = getenv("GIT_ASK_YESNO"))) {
171 va_start(args, format);
172 vsnprintf(question, sizeof(question), format, args);
173 va_end(args);
175 retry_hook[1] = question;
176 return !run_command_v_opt(retry_hook, 0);
179 if (!isatty(_fileno(stdin)))
180 return 0;
182 while (1) {
183 va_start(args, format);
184 vfprintf(stderr, format, args);
185 va_end(args);
186 fprintf(stderr, " (y/n)? ");
188 if (fgets(answer, sizeof(answer), stdin)) {
189 /* remove the newline */
190 if (answer[strlen(answer)-2] == '\r')
191 answer[strlen(answer)-2] = '\0';
192 if (answer[strlen(answer)-1] == '\n')
193 answer[strlen(answer)-1] = '\0';
194 } else
195 return 0;
197 if (answer[0] == 'y' && strlen(answer) == 1)
198 return 1;
199 if (!strncasecmp(answer, "yes", sizeof(answer)))
200 return 1;
201 if (answer[0] == 'n' && strlen(answer) == 1)
202 return 0;
203 if (!strncasecmp(answer, "no", sizeof(answer)))
204 return 0;
205 fprintf(stderr, "I did not understand your answer: '%s'\n",
206 answer);
210 #undef unlink
211 int mingw_unlink(const char *pathname)
213 int ret, tries = 0;
215 /* read-only files cannot be removed */
216 chmod(pathname, 0666);
217 while ((ret = unlink(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
218 if (errno != EACCES)
219 break;
221 * We assume that some other process had the source or
222 * destination file open at the wrong moment and retry.
223 * In order to give the other process a higher chance to
224 * complete its operation, we give up our time slice now.
225 * If we have to retry again, we do sleep a bit.
227 Sleep(delay[tries]);
228 tries++;
230 while (ret == -1 && errno == EACCES &&
231 ask_user_yes_no("Unlink of file '%s' failed. "
232 "Should I try again?", pathname))
233 ret = unlink(pathname);
234 return ret;
237 #undef rmdir
238 int mingw_rmdir(const char *pathname)
240 int ret, tries = 0;
242 while ((ret = rmdir(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
243 if (errno != EACCES)
244 break;
246 * We assume that some other process had the source or
247 * destination file open at the wrong moment and retry.
248 * In order to give the other process a higher chance to
249 * complete its operation, we give up our time slice now.
250 * If we have to retry again, we do sleep a bit.
252 Sleep(delay[tries]);
253 tries++;
255 while (ret == -1 && errno == EACCES &&
256 ask_user_yes_no("Deletion of directory '%s' failed. "
257 "Should I try again?", pathname))
258 ret = rmdir(pathname);
259 return ret;
262 #undef open
263 int mingw_open (const char *filename, int oflags, ...)
265 va_list args;
266 unsigned mode;
267 int fd;
269 va_start(args, oflags);
270 mode = va_arg(args, int);
271 va_end(args);
273 if (!strcmp(filename, "/dev/null"))
274 filename = "nul";
276 fd = open(filename, oflags | O_BINARY, mode);
278 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
279 DWORD attrs = GetFileAttributes(filename);
280 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
281 errno = EISDIR;
283 if ((oflags & O_CREAT) && fd >= 0 &&
284 hide_dotfiles == HIDE_DOTFILES_TRUE) {
286 * In Windows a file or dir starting with a dot is not
287 * automatically hidden. So lets mark it as hidden when
288 * such a file is created.
290 const char *start = basename((char*)filename);
291 if (*start == '.' && make_hidden(filename))
292 warning("Could not mark '%s' as hidden.", filename);
294 return fd;
297 #undef fopen
298 FILE *mingw_fopen (const char *filename, const char *mode)
300 int hide = 0;
301 FILE *file;
302 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
303 basename((char*)filename)[0] == '.')
304 hide = access(filename, F_OK);
306 file = fopen(strcmp(filename, "/dev/null") ? filename : "NUL", mode);
308 * In Windows a file or dir starting with a dot is not
309 * automatically hidden. So lets mark it as hidden when
310 * such a file is created.
312 if (file && hide && make_hidden(filename))
313 warning("Could not mark '%s' as hidden.", filename);
314 return file;
318 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
319 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
321 static inline long long filetime_to_hnsec(const FILETIME *ft)
323 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
324 /* Windows to Unix Epoch conversion */
325 return winTime - 116444736000000000LL;
328 static inline time_t filetime_to_time_t(const FILETIME *ft)
330 return (time_t)(filetime_to_hnsec(ft) / 10000000);
334 * We keep the do_lstat code in a separate function to avoid recursion.
335 * When a path ends with a slash, the stat will fail with ENOENT. In
336 * this case, we strip the trailing slashes and stat again.
338 static int do_lstat(const char *file_name, struct stat *buf)
340 WIN32_FILE_ATTRIBUTE_DATA fdata;
342 if (!(errno = get_file_attr(file_name, &fdata))) {
343 buf->st_ino = 0;
344 buf->st_gid = 0;
345 buf->st_uid = 0;
346 buf->st_nlink = 1;
347 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
348 buf->st_size = fdata.nFileSizeLow |
349 (((off_t)fdata.nFileSizeHigh)<<32);
350 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
351 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
352 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
353 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
354 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
355 WIN32_FIND_DATAA findbuf;
356 HANDLE handle = FindFirstFileA(file_name, &findbuf);
357 if (handle != INVALID_HANDLE_VALUE) {
358 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
359 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
360 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
361 buf->st_mode = S_IREAD | S_IFLNK;
362 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
363 buf->st_mode |= S_IWRITE;
364 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
366 FindClose(handle);
369 return 0;
371 return -1;
375 * We provide our own lstat/fstat functions, since the provided
376 * lstat/fstat functions are so slow. These stat functions are
377 * tailored for Git's usage (read: fast), and are not meant to be
378 * complete. Note that Git stat()s are redirected to mingw_lstat()
379 * too, since Windows doesn't really handle symlinks that well.
381 int mingw_lstat(const char *file_name, struct stat *buf)
383 int namelen;
384 static char alt_name[PATH_MAX];
386 if (!do_lstat(file_name, buf))
387 return 0;
390 * if file_name ended in a '/', Windows returned ENOENT;
391 * try again without trailing slashes
393 if (errno != ENOENT)
394 return -1;
396 namelen = strlen(file_name);
397 if (namelen && file_name[namelen-1] != '/')
398 return -1;
399 while (namelen && file_name[namelen-1] == '/')
400 --namelen;
401 if (!namelen || namelen >= PATH_MAX)
402 return -1;
404 memcpy(alt_name, file_name, namelen);
405 alt_name[namelen] = 0;
406 return do_lstat(alt_name, buf);
409 #undef fstat
410 int mingw_fstat(int fd, struct stat *buf)
412 HANDLE fh = (HANDLE)_get_osfhandle(fd);
413 BY_HANDLE_FILE_INFORMATION fdata;
415 if (fh == INVALID_HANDLE_VALUE) {
416 errno = EBADF;
417 return -1;
419 /* direct non-file handles to MS's fstat() */
420 if (GetFileType(fh) != FILE_TYPE_DISK)
421 return _fstati64(fd, buf);
423 if (GetFileInformationByHandle(fh, &fdata)) {
424 buf->st_ino = 0;
425 buf->st_gid = 0;
426 buf->st_uid = 0;
427 buf->st_nlink = 1;
428 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
429 buf->st_size = fdata.nFileSizeLow |
430 (((off_t)fdata.nFileSizeHigh)<<32);
431 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
432 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
433 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
434 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
435 return 0;
437 errno = EBADF;
438 return -1;
441 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
443 long long winTime = t * 10000000LL + 116444736000000000LL;
444 ft->dwLowDateTime = winTime;
445 ft->dwHighDateTime = winTime >> 32;
448 int mingw_utime (const char *file_name, const struct utimbuf *times)
450 FILETIME mft, aft;
451 int fh, rc;
453 /* must have write permission */
454 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
455 return -1;
457 time_t_to_filetime(times->modtime, &mft);
458 time_t_to_filetime(times->actime, &aft);
459 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
460 errno = EINVAL;
461 rc = -1;
462 } else
463 rc = 0;
464 close(fh);
465 return rc;
468 unsigned int sleep (unsigned int seconds)
470 Sleep(seconds*1000);
471 return 0;
474 int mkstemp(char *template)
476 char *filename = mktemp(template);
477 if (filename == NULL)
478 return -1;
479 return open(filename, O_RDWR | O_CREAT | O_BINARY, 0600);
482 int gettimeofday(struct timeval *tv, void *tz)
484 FILETIME ft;
485 long long hnsec;
487 GetSystemTimeAsFileTime(&ft);
488 hnsec = filetime_to_hnsec(&ft);
489 tv->tv_sec = hnsec / 10000000;
490 tv->tv_usec = (hnsec % 10000000) / 10;
491 return 0;
494 int pipe(int filedes[2])
496 HANDLE h[2];
498 /* this creates non-inheritable handles */
499 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
500 errno = err_win_to_posix(GetLastError());
501 return -1;
503 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
504 if (filedes[0] < 0) {
505 CloseHandle(h[0]);
506 CloseHandle(h[1]);
507 return -1;
509 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
510 if (filedes[0] < 0) {
511 close(filedes[0]);
512 CloseHandle(h[1]);
513 return -1;
515 return 0;
518 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
520 int i, pending;
522 if (timeout >= 0) {
523 if (nfds == 0) {
524 Sleep(timeout);
525 return 0;
527 return errno = EINVAL, error("poll timeout not supported");
531 * When there is only one fd to wait for, then we pretend that
532 * input is available and let the actual wait happen when the
533 * caller invokes read().
535 if (nfds == 1) {
536 if (!(ufds[0].events & POLLIN))
537 return errno = EINVAL, error("POLLIN not set");
538 ufds[0].revents = POLLIN;
539 return 0;
542 repeat:
543 pending = 0;
544 for (i = 0; i < nfds; i++) {
545 DWORD avail = 0;
546 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
547 if (h == INVALID_HANDLE_VALUE)
548 return -1; /* errno was set */
550 if (!(ufds[i].events & POLLIN))
551 return errno = EINVAL, error("POLLIN not set");
553 /* this emulation works only for pipes */
554 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
555 int err = GetLastError();
556 if (err == ERROR_BROKEN_PIPE) {
557 ufds[i].revents = POLLHUP;
558 pending++;
559 } else {
560 errno = EINVAL;
561 return error("PeekNamedPipe failed,"
562 " GetLastError: %u", err);
564 } else if (avail) {
565 ufds[i].revents = POLLIN;
566 pending++;
567 } else
568 ufds[i].revents = 0;
570 if (!pending) {
572 * The only times that we spin here is when the process
573 * that is connected through the pipes is waiting for
574 * its own input data to become available. But since
575 * the process (pack-objects) is itself CPU intensive,
576 * it will happily pick up the time slice that we are
577 * relinquishing here.
579 Sleep(0);
580 goto repeat;
582 return 0;
585 struct tm *gmtime_r(const time_t *timep, struct tm *result)
587 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
588 memcpy(result, gmtime(timep), sizeof(struct tm));
589 return result;
592 struct tm *localtime_r(const time_t *timep, struct tm *result)
594 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
595 memcpy(result, localtime(timep), sizeof(struct tm));
596 return result;
599 #undef getcwd
600 char *mingw_getcwd(char *pointer, int len)
602 int i;
603 char *ret = getcwd(pointer, len);
604 if (!ret)
605 return ret;
606 for (i = 0; pointer[i]; i++)
607 if (pointer[i] == '\\')
608 pointer[i] = '/';
609 return ret;
612 #undef getenv
613 char *mingw_getenv(const char *name)
615 char *result = getenv(name);
616 if (!result && !strcmp(name, "TMPDIR")) {
617 /* on Windows it is TMP and TEMP */
618 result = getenv("TMP");
619 if (!result)
620 result = getenv("TEMP");
622 return result;
626 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
627 * (Parsing C++ Command-Line Arguments)
629 static const char *quote_arg(const char *arg)
631 /* count chars to quote */
632 int len = 0, n = 0;
633 int force_quotes = 0;
634 char *q, *d;
635 const char *p = arg;
636 if (!*p) force_quotes = 1;
637 while (*p) {
638 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
639 force_quotes = 1;
640 else if (*p == '"')
641 n++;
642 else if (*p == '\\') {
643 int count = 0;
644 while (*p == '\\') {
645 count++;
646 p++;
647 len++;
649 if (*p == '"')
650 n += count*2 + 1;
651 continue;
653 len++;
654 p++;
656 if (!force_quotes && n == 0)
657 return arg;
659 /* insert \ where necessary */
660 d = q = xmalloc(len+n+3);
661 *d++ = '"';
662 while (*arg) {
663 if (*arg == '"')
664 *d++ = '\\';
665 else if (*arg == '\\') {
666 int count = 0;
667 while (*arg == '\\') {
668 count++;
669 *d++ = *arg++;
671 if (*arg == '"') {
672 while (count-- > 0)
673 *d++ = '\\';
674 *d++ = '\\';
677 *d++ = *arg++;
679 *d++ = '"';
680 *d++ = 0;
681 return q;
684 static const char *parse_interpreter(const char *cmd)
686 static char buf[100];
687 char *p, *opt;
688 int n, fd;
690 /* don't even try a .exe */
691 n = strlen(cmd);
692 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
693 return NULL;
695 fd = open(cmd, O_RDONLY);
696 if (fd < 0)
697 return NULL;
698 n = read(fd, buf, sizeof(buf)-1);
699 close(fd);
700 if (n < 4) /* at least '#!/x' and not error */
701 return NULL;
703 if (buf[0] != '#' || buf[1] != '!')
704 return NULL;
705 buf[n] = '\0';
706 p = buf + strcspn(buf, "\r\n");
707 if (!*p)
708 return NULL;
710 *p = '\0';
711 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
712 return NULL;
713 /* strip options */
714 if ((opt = strchr(p+1, ' ')))
715 *opt = '\0';
716 return p+1;
720 * Splits the PATH into parts.
722 static char **get_path_split(void)
724 char *p, **path, *envpath = getenv("PATH");
725 int i, n = 0;
727 if (!envpath || !*envpath)
728 return NULL;
730 envpath = xstrdup(envpath);
731 p = envpath;
732 while (p) {
733 char *dir = p;
734 p = strchr(p, ';');
735 if (p) *p++ = '\0';
736 if (*dir) { /* not earlier, catches series of ; */
737 ++n;
740 if (!n)
741 return NULL;
743 path = xmalloc((n+1)*sizeof(char *));
744 p = envpath;
745 i = 0;
746 do {
747 if (*p)
748 path[i++] = xstrdup(p);
749 p = p+strlen(p)+1;
750 } while (i < n);
751 path[i] = NULL;
753 free(envpath);
755 return path;
758 static void free_path_split(char **path)
760 char **p = path;
762 if (!path)
763 return;
765 while (*p)
766 free(*p++);
767 free(path);
771 * exe_only means that we only want to detect .exe files, but not scripts
772 * (which do not have an extension)
774 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
776 char path[MAX_PATH];
777 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
779 if (!isexe && access(path, F_OK) == 0)
780 return xstrdup(path);
781 path[strlen(path)-4] = '\0';
782 if ((!exe_only || isexe) && access(path, F_OK) == 0)
783 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
784 return xstrdup(path);
785 return NULL;
789 * Determines the absolute path of cmd using the the split path in path.
790 * If cmd contains a slash or backslash, no lookup is performed.
792 static char *path_lookup(const char *cmd, char **path, int exe_only)
794 char *prog = NULL;
795 int len = strlen(cmd);
796 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
798 if (strchr(cmd, '/') || strchr(cmd, '\\'))
799 prog = xstrdup(cmd);
801 while (!prog && *path)
802 prog = lookup_prog(*path++, cmd, isexe, exe_only);
804 return prog;
807 static int env_compare(const void *a, const void *b)
809 char *const *ea = a;
810 char *const *eb = b;
811 return strcasecmp(*ea, *eb);
814 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
815 int prepend_cmd, int fhin, int fhout, int fherr)
817 STARTUPINFO si;
818 PROCESS_INFORMATION pi;
819 struct strbuf envblk, args;
820 unsigned flags;
821 BOOL ret;
823 /* Determine whether or not we are associated to a console */
824 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
825 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
826 FILE_ATTRIBUTE_NORMAL, NULL);
827 if (cons == INVALID_HANDLE_VALUE) {
829 * There is no console associated with this process.
830 * Since the child is a console process, Windows
831 * would normally create a console window. But
832 * since we'll be redirecting std streams, we do
833 * not need the console.
834 * It is necessary to use DETACHED_PROCESS
835 * instead of CREATE_NO_WINDOW to make ssh
836 * recognize that it has no console.
838 flags = DETACHED_PROCESS;
839 } else {
841 * There is already a console. If we specified
842 * DETACHED_PROCESS here, too, Windows would
843 * disassociate the child from the console.
844 * The same is true for CREATE_NO_WINDOW.
845 * Go figure!
847 flags = 0;
848 CloseHandle(cons);
850 memset(&si, 0, sizeof(si));
851 si.cb = sizeof(si);
852 si.dwFlags = STARTF_USESTDHANDLES;
853 si.hStdInput = (HANDLE) _get_osfhandle(fhin);
854 si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
855 si.hStdError = (HANDLE) _get_osfhandle(fherr);
857 /* concatenate argv, quoting args as we go */
858 strbuf_init(&args, 0);
859 if (prepend_cmd) {
860 char *quoted = (char *)quote_arg(cmd);
861 strbuf_addstr(&args, quoted);
862 if (quoted != cmd)
863 free(quoted);
865 for (; *argv; argv++) {
866 char *quoted = (char *)quote_arg(*argv);
867 if (*args.buf)
868 strbuf_addch(&args, ' ');
869 strbuf_addstr(&args, quoted);
870 if (quoted != *argv)
871 free(quoted);
874 if (env) {
875 int count = 0;
876 char **e, **sorted_env;
878 for (e = env; *e; e++)
879 count++;
881 /* environment must be sorted */
882 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
883 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
884 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
886 strbuf_init(&envblk, 0);
887 for (e = sorted_env; *e; e++) {
888 strbuf_addstr(&envblk, *e);
889 strbuf_addch(&envblk, '\0');
891 free(sorted_env);
894 memset(&pi, 0, sizeof(pi));
895 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
896 env ? envblk.buf : NULL, NULL, &si, &pi);
898 if (env)
899 strbuf_release(&envblk);
900 strbuf_release(&args);
902 if (!ret) {
903 errno = ENOENT;
904 return -1;
906 CloseHandle(pi.hThread);
907 return (pid_t)pi.hProcess;
910 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
911 int prepend_cmd)
913 return mingw_spawnve_fd(cmd, argv, env, prepend_cmd, 0, 1, 2);
916 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
917 int fhin, int fhout, int fherr)
919 pid_t pid;
920 char **path = get_path_split();
921 char *prog = path_lookup(cmd, path, 0);
923 if (!prog) {
924 errno = ENOENT;
925 pid = -1;
927 else {
928 const char *interpr = parse_interpreter(prog);
930 if (interpr) {
931 const char *argv0 = argv[0];
932 char *iprog = path_lookup(interpr, path, 1);
933 argv[0] = prog;
934 if (!iprog) {
935 errno = ENOENT;
936 pid = -1;
938 else {
939 pid = mingw_spawnve_fd(iprog, argv, env, 1,
940 fhin, fhout, fherr);
941 free(iprog);
943 argv[0] = argv0;
945 else
946 pid = mingw_spawnve_fd(prog, argv, env, 0,
947 fhin, fhout, fherr);
948 free(prog);
950 free_path_split(path);
951 return pid;
954 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
956 const char *interpr = parse_interpreter(cmd);
957 char **path;
958 char *prog;
959 int pid = 0;
961 if (!interpr)
962 return 0;
963 path = get_path_split();
964 prog = path_lookup(interpr, path, 1);
965 if (prog) {
966 int argc = 0;
967 const char **argv2;
968 while (argv[argc]) argc++;
969 argv2 = xmalloc(sizeof(*argv) * (argc+1));
970 argv2[0] = (char *)cmd; /* full path to the script file */
971 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
972 pid = mingw_spawnve(prog, argv2, env, 1);
973 if (pid >= 0) {
974 int status;
975 if (waitpid(pid, &status, 0) < 0)
976 status = 255;
977 exit(status);
979 pid = 1; /* indicate that we tried but failed */
980 free(prog);
981 free(argv2);
983 free_path_split(path);
984 return pid;
987 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
989 /* check if git_command is a shell script */
990 if (!try_shell_exec(cmd, argv, (char **)env)) {
991 int pid, status;
993 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
994 if (pid < 0)
995 return;
996 if (waitpid(pid, &status, 0) < 0)
997 status = 255;
998 exit(status);
1002 void mingw_execvp(const char *cmd, char *const *argv)
1004 char **path = get_path_split();
1005 char *prog = path_lookup(cmd, path, 0);
1007 if (prog) {
1008 mingw_execve(prog, argv, environ);
1009 free(prog);
1010 } else
1011 errno = ENOENT;
1013 free_path_split(path);
1016 static char **copy_environ(void)
1018 char **env;
1019 int i = 0;
1020 while (environ[i])
1021 i++;
1022 env = xmalloc((i+1)*sizeof(*env));
1023 for (i = 0; environ[i]; i++)
1024 env[i] = xstrdup(environ[i]);
1025 env[i] = NULL;
1026 return env;
1029 void free_environ(char **env)
1031 int i;
1032 for (i = 0; env[i]; i++)
1033 free(env[i]);
1034 free(env);
1037 static int lookup_env(char **env, const char *name, size_t nmln)
1039 int i;
1041 for (i = 0; env[i]; i++) {
1042 if (0 == strncmp(env[i], name, nmln)
1043 && '=' == env[i][nmln])
1044 /* matches */
1045 return i;
1047 return -1;
1051 * If name contains '=', then sets the variable, otherwise it unsets it
1053 static char **env_setenv(char **env, const char *name)
1055 char *eq = strchrnul(name, '=');
1056 int i = lookup_env(env, name, eq-name);
1058 if (i < 0) {
1059 if (*eq) {
1060 for (i = 0; env[i]; i++)
1062 env = xrealloc(env, (i+2)*sizeof(*env));
1063 env[i] = xstrdup(name);
1064 env[i+1] = NULL;
1067 else {
1068 free(env[i]);
1069 if (*eq)
1070 env[i] = xstrdup(name);
1071 else
1072 for (; env[i]; i++)
1073 env[i] = env[i+1];
1075 return env;
1079 * Copies global environ and adjusts variables as specified by vars.
1081 char **make_augmented_environ(const char *const *vars)
1083 char **env = copy_environ();
1085 while (*vars)
1086 env = env_setenv(env, *vars++);
1087 return env;
1091 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1092 * that service contains a numerical port, or that it it is null. It
1093 * does a simple search using gethostbyname, and returns one IPv4 host
1094 * if one was found.
1096 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1097 const struct addrinfo *hints,
1098 struct addrinfo **res)
1100 struct hostent *h = gethostbyname(node);
1101 struct addrinfo *ai;
1102 struct sockaddr_in *sin;
1104 if (!h)
1105 return WSAGetLastError();
1107 ai = xmalloc(sizeof(struct addrinfo));
1108 *res = ai;
1109 ai->ai_flags = 0;
1110 ai->ai_family = AF_INET;
1111 ai->ai_socktype = hints->ai_socktype;
1112 switch (hints->ai_socktype) {
1113 case SOCK_STREAM:
1114 ai->ai_protocol = IPPROTO_TCP;
1115 break;
1116 case SOCK_DGRAM:
1117 ai->ai_protocol = IPPROTO_UDP;
1118 break;
1119 default:
1120 ai->ai_protocol = 0;
1121 break;
1123 ai->ai_addrlen = sizeof(struct sockaddr_in);
1124 ai->ai_canonname = strdup(h->h_name);
1126 sin = xmalloc(ai->ai_addrlen);
1127 memset(sin, 0, ai->ai_addrlen);
1128 sin->sin_family = AF_INET;
1129 if (service)
1130 sin->sin_port = htons(atoi(service));
1131 sin->sin_addr = *(struct in_addr *)h->h_addr;
1132 ai->ai_addr = (struct sockaddr *)sin;
1133 ai->ai_next = 0;
1134 return 0;
1137 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1139 free(res->ai_canonname);
1140 free(res->ai_addr);
1141 free(res);
1144 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1145 char *host, DWORD hostlen,
1146 char *serv, DWORD servlen, int flags)
1148 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1149 if (sa->sa_family != AF_INET)
1150 return EAI_FAMILY;
1151 if (!host && !serv)
1152 return EAI_NONAME;
1154 if (host && hostlen > 0) {
1155 struct hostent *ent = NULL;
1156 if (!(flags & NI_NUMERICHOST))
1157 ent = gethostbyaddr((const char *)&sin->sin_addr,
1158 sizeof(sin->sin_addr), AF_INET);
1160 if (ent)
1161 snprintf(host, hostlen, "%s", ent->h_name);
1162 else if (flags & NI_NAMEREQD)
1163 return EAI_NONAME;
1164 else
1165 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1168 if (serv && servlen > 0) {
1169 struct servent *ent = NULL;
1170 if (!(flags & NI_NUMERICSERV))
1171 ent = getservbyport(sin->sin_port,
1172 flags & NI_DGRAM ? "udp" : "tcp");
1174 if (ent)
1175 snprintf(serv, servlen, "%s", ent->s_name);
1176 else
1177 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1180 return 0;
1183 static HMODULE ipv6_dll = NULL;
1184 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1185 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1186 const struct addrinfo *hints,
1187 struct addrinfo **res);
1188 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1189 char *host, DWORD hostlen,
1190 char *serv, DWORD servlen, int flags);
1192 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1193 * don't need to try to load that one dynamically.
1196 static void socket_cleanup(void)
1198 WSACleanup();
1199 if (ipv6_dll)
1200 FreeLibrary(ipv6_dll);
1201 ipv6_dll = NULL;
1202 ipv6_freeaddrinfo = freeaddrinfo_stub;
1203 ipv6_getaddrinfo = getaddrinfo_stub;
1204 ipv6_getnameinfo = getnameinfo_stub;
1207 static void ensure_socket_initialization(void)
1209 WSADATA wsa;
1210 static int initialized = 0;
1211 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1212 const char **name;
1214 if (initialized)
1215 return;
1217 if (WSAStartup(MAKEWORD(2,2), &wsa))
1218 die("unable to initialize winsock subsystem, error %d",
1219 WSAGetLastError());
1221 for (name = libraries; *name; name++) {
1222 ipv6_dll = LoadLibrary(*name);
1223 if (!ipv6_dll)
1224 continue;
1226 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1227 GetProcAddress(ipv6_dll, "freeaddrinfo");
1228 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1229 const struct addrinfo *,
1230 struct addrinfo **))
1231 GetProcAddress(ipv6_dll, "getaddrinfo");
1232 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1233 socklen_t, char *, DWORD,
1234 char *, DWORD, int))
1235 GetProcAddress(ipv6_dll, "getnameinfo");
1236 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1237 FreeLibrary(ipv6_dll);
1238 ipv6_dll = NULL;
1239 } else
1240 break;
1242 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1243 ipv6_freeaddrinfo = freeaddrinfo_stub;
1244 ipv6_getaddrinfo = getaddrinfo_stub;
1245 ipv6_getnameinfo = getnameinfo_stub;
1248 atexit(socket_cleanup);
1249 initialized = 1;
1252 #undef gethostbyname
1253 struct hostent *mingw_gethostbyname(const char *host)
1255 ensure_socket_initialization();
1256 return gethostbyname(host);
1259 void mingw_freeaddrinfo(struct addrinfo *res)
1261 ipv6_freeaddrinfo(res);
1264 int mingw_getaddrinfo(const char *node, const char *service,
1265 const struct addrinfo *hints, struct addrinfo **res)
1267 ensure_socket_initialization();
1268 return ipv6_getaddrinfo(node, service, hints, res);
1271 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1272 char *host, DWORD hostlen, char *serv, DWORD servlen,
1273 int flags)
1275 ensure_socket_initialization();
1276 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1279 int mingw_socket(int domain, int type, int protocol)
1281 int sockfd;
1282 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
1283 if (s == INVALID_SOCKET) {
1285 * WSAGetLastError() values are regular BSD error codes
1286 * biased by WSABASEERR.
1287 * However, strerror() does not know about networking
1288 * specific errors, which are values beginning at 38 or so.
1289 * Therefore, we choose to leave the biased error code
1290 * in errno so that _if_ someone looks up the code somewhere,
1291 * then it is at least the number that are usually listed.
1293 errno = WSAGetLastError();
1294 return -1;
1296 /* convert into a file descriptor */
1297 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1298 closesocket(s);
1299 return error("unable to make a socket file descriptor: %s",
1300 strerror(errno));
1302 return sockfd;
1305 #undef connect
1306 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1308 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1309 return connect(s, sa, sz);
1312 #undef rename
1313 int mingw_rename(const char *pold, const char *pnew)
1315 DWORD attrs, gle;
1316 int tries = 0;
1319 * Try native rename() first to get errno right.
1320 * It is based on MoveFile(), which cannot overwrite existing files.
1322 if (!rename(pold, pnew))
1323 return 0;
1324 if (errno != EEXIST)
1325 return -1;
1326 repeat:
1327 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1328 return 0;
1329 /* TODO: translate more errors */
1330 gle = GetLastError();
1331 if (gle == ERROR_ACCESS_DENIED &&
1332 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1333 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1334 errno = EISDIR;
1335 return -1;
1337 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1338 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1339 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1340 return 0;
1341 gle = GetLastError();
1342 /* revert file attributes on failure */
1343 SetFileAttributes(pnew, attrs);
1346 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1348 * We assume that some other process had the source or
1349 * destination file open at the wrong moment and retry.
1350 * In order to give the other process a higher chance to
1351 * complete its operation, we give up our time slice now.
1352 * If we have to retry again, we do sleep a bit.
1354 Sleep(delay[tries]);
1355 tries++;
1356 goto repeat;
1358 if (gle == ERROR_ACCESS_DENIED &&
1359 ask_user_yes_no("Rename from '%s' to '%s' failed. "
1360 "Should I try again?", pold, pnew))
1361 goto repeat;
1363 errno = EACCES;
1364 return -1;
1368 * Note that this doesn't return the actual pagesize, but
1369 * the allocation granularity. If future Windows specific git code
1370 * needs the real getpagesize function, we need to find another solution.
1372 int mingw_getpagesize(void)
1374 SYSTEM_INFO si;
1375 GetSystemInfo(&si);
1376 return si.dwAllocationGranularity;
1379 struct passwd *getpwuid(int uid)
1381 static char user_name[100];
1382 static struct passwd p;
1384 DWORD len = sizeof(user_name);
1385 if (!GetUserName(user_name, &len))
1386 return NULL;
1387 p.pw_name = user_name;
1388 p.pw_gecos = "unknown";
1389 p.pw_dir = NULL;
1390 return &p;
1393 static HANDLE timer_event;
1394 static HANDLE timer_thread;
1395 static int timer_interval;
1396 static int one_shot;
1397 static sig_handler_t timer_fn = SIG_DFL;
1400 * The timer works like this:
1401 * The thread, ticktack(), is a trivial routine that most of the time
1402 * only waits to receive the signal to terminate. The main thread tells
1403 * the thread to terminate by setting the timer_event to the signalled
1404 * state.
1405 * But ticktack() interrupts the wait state after the timer's interval
1406 * length to call the signal handler.
1409 static unsigned __stdcall ticktack(void *dummy)
1411 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1412 if (timer_fn == SIG_DFL)
1413 die("Alarm");
1414 if (timer_fn != SIG_IGN)
1415 timer_fn(SIGALRM);
1416 if (one_shot)
1417 break;
1419 return 0;
1422 static int start_timer_thread(void)
1424 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1425 if (timer_event) {
1426 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1427 if (!timer_thread )
1428 return errno = ENOMEM,
1429 error("cannot start timer thread");
1430 } else
1431 return errno = ENOMEM,
1432 error("cannot allocate resources for timer");
1433 return 0;
1436 static void stop_timer_thread(void)
1438 if (timer_event)
1439 SetEvent(timer_event); /* tell thread to terminate */
1440 if (timer_thread) {
1441 int rc = WaitForSingleObject(timer_thread, 1000);
1442 if (rc == WAIT_TIMEOUT)
1443 error("timer thread did not terminate timely");
1444 else if (rc != WAIT_OBJECT_0)
1445 error("waiting for timer thread failed: %lu",
1446 GetLastError());
1447 CloseHandle(timer_thread);
1449 if (timer_event)
1450 CloseHandle(timer_event);
1451 timer_event = NULL;
1452 timer_thread = NULL;
1455 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1457 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1460 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1462 static const struct timeval zero;
1463 static int atexit_done;
1465 if (out != NULL)
1466 return errno = EINVAL,
1467 error("setitimer param 3 != NULL not implemented");
1468 if (!is_timeval_eq(&in->it_interval, &zero) &&
1469 !is_timeval_eq(&in->it_interval, &in->it_value))
1470 return errno = EINVAL,
1471 error("setitimer: it_interval must be zero or eq it_value");
1473 if (timer_thread)
1474 stop_timer_thread();
1476 if (is_timeval_eq(&in->it_value, &zero) &&
1477 is_timeval_eq(&in->it_interval, &zero))
1478 return 0;
1480 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1481 one_shot = is_timeval_eq(&in->it_interval, &zero);
1482 if (!atexit_done) {
1483 atexit(stop_timer_thread);
1484 atexit_done = 1;
1486 return start_timer_thread();
1489 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1491 if (sig != SIGALRM)
1492 return errno = EINVAL,
1493 error("sigaction only implemented for SIGALRM");
1494 if (out != NULL)
1495 return errno = EINVAL,
1496 error("sigaction: param 3 != NULL not implemented");
1498 timer_fn = in->sa_handler;
1499 return 0;
1502 #undef signal
1503 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1505 sig_handler_t old = timer_fn;
1506 if (sig != SIGALRM)
1507 return signal(sig, handler);
1508 timer_fn = handler;
1509 return old;
1512 static const char *make_backslash_path(const char *path, char *buf)
1514 char *c;
1516 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1517 die("Too long path: %.*s", 60, path);
1519 for (c = buf; *c; c++) {
1520 if (*c == '/')
1521 *c = '\\';
1523 return buf;
1526 void mingw_open_html(const char *unixpath)
1528 char buf[PATH_MAX + 1];
1529 const char *htmlpath = make_backslash_path(unixpath, buf);
1530 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1531 const char *, const char *, const char *, INT);
1532 T ShellExecute;
1533 HMODULE shell32;
1535 shell32 = LoadLibrary("shell32.dll");
1536 if (!shell32)
1537 die("cannot load shell32.dll");
1538 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1539 if (!ShellExecute)
1540 die("cannot run browser");
1542 printf("Launching default browser to display HTML ...\n");
1543 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);
1545 FreeLibrary(shell32);
1548 int link(const char *oldpath, const char *newpath)
1550 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1551 static T create_hard_link = NULL;
1552 if (!create_hard_link) {
1553 create_hard_link = (T) GetProcAddress(
1554 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1555 if (!create_hard_link)
1556 create_hard_link = (T)-1;
1558 if (create_hard_link == (T)-1) {
1559 errno = ENOSYS;
1560 return -1;
1562 if (!create_hard_link(newpath, oldpath, NULL)) {
1563 errno = err_win_to_posix(GetLastError());
1564 return -1;
1566 return 0;
1569 int symlink(const char *oldpath, const char *newpath)
1571 typedef BOOL WINAPI (*symlink_fn)(const char*, const char*, DWORD);
1572 static symlink_fn create_symbolic_link = NULL;
1573 char buf[PATH_MAX + 1];
1575 if (!create_symbolic_link) {
1576 create_symbolic_link = (symlink_fn) GetProcAddress(
1577 GetModuleHandle("kernel32.dll"), "CreateSymbolicLinkA");
1578 if (!create_symbolic_link)
1579 create_symbolic_link = (symlink_fn)-1;
1581 if (create_symbolic_link == (symlink_fn)-1) {
1582 errno = ENOSYS;
1583 return -1;
1586 if (!create_symbolic_link(newpath, make_backslash_path(oldpath, buf), 0)) {
1587 errno = err_win_to_posix(GetLastError());
1588 return -1;
1590 return 0;
1593 int readlink(const char *path, char *buf, size_t bufsiz)
1595 HANDLE handle = CreateFile(path, GENERIC_READ,
1596 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1597 NULL, OPEN_EXISTING,
1598 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1599 NULL);
1601 if (handle != INVALID_HANDLE_VALUE) {
1602 unsigned char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1603 DWORD dummy = 0;
1604 if (DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0, buffer,
1605 MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dummy, NULL)) {
1606 REPARSE_DATA_BUFFER *b = (REPARSE_DATA_BUFFER *) buffer;
1607 if (b->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
1608 int len = b->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
1609 int offset = b->SymbolicLinkReparseBuffer.SubstituteNameOffset / sizeof(wchar_t);
1610 int i;
1611 snprintf(buf, bufsiz, "%*ls", len, & b->SymbolicLinkReparseBuffer.PathBuffer[offset]);
1612 for (i = 0; i < len; i++)
1613 if (buf[i] == '\\')
1614 buf[i] = '/';
1615 CloseHandle(handle);
1616 return len;
1620 CloseHandle(handle);
1623 errno = EINVAL;
1624 return -1;
1627 char *getpass(const char *prompt)
1629 struct strbuf buf = STRBUF_INIT;
1631 fputs(prompt, stderr);
1632 for (;;) {
1633 char c = _getch();
1634 if (c == '\r' || c == '\n')
1635 break;
1636 strbuf_addch(&buf, c);
1638 fputs("\n", stderr);
1639 return strbuf_detach(&buf, NULL);
1642 #ifndef NO_MINGW_REPLACE_READDIR
1643 /* MinGW readdir implementation to avoid extra lstats for Git */
1644 struct mingw_DIR
1646 struct _finddata_t dd_dta; /* disk transfer area for this dir */
1647 struct mingw_dirent dd_dir; /* Our own implementation, including d_type */
1648 long dd_handle; /* _findnext handle */
1649 int dd_stat; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1650 char dd_name[1]; /* given path for dir with search pattern (struct is extended) */
1653 struct dirent *mingw_readdir(DIR *dir)
1655 WIN32_FIND_DATAA buf;
1656 HANDLE handle;
1657 struct mingw_DIR *mdir = (struct mingw_DIR*)dir;
1659 if (!dir->dd_handle) {
1660 errno = EBADF; /* No set_errno for mingw */
1661 return NULL;
1664 if (dir->dd_handle == (long)INVALID_HANDLE_VALUE && dir->dd_stat == 0)
1666 DWORD lasterr;
1667 handle = FindFirstFileA(dir->dd_name, &buf);
1668 lasterr = GetLastError();
1669 dir->dd_handle = (long)handle;
1670 if (handle == INVALID_HANDLE_VALUE && (lasterr != ERROR_NO_MORE_FILES)) {
1671 errno = err_win_to_posix(lasterr);
1672 return NULL;
1674 } else if (dir->dd_handle == (long)INVALID_HANDLE_VALUE) {
1675 return NULL;
1676 } else if (!FindNextFileA((HANDLE)dir->dd_handle, &buf)) {
1677 DWORD lasterr = GetLastError();
1678 FindClose((HANDLE)dir->dd_handle);
1679 dir->dd_handle = (long)INVALID_HANDLE_VALUE;
1681 * POSIX says you shouldn't set errno when readdir can't
1682 * find any more files; so, if another error we leave it set.
1684 if (lasterr != ERROR_NO_MORE_FILES)
1685 errno = err_win_to_posix(lasterr);
1686 return NULL;
1689 /* We get here if `buf' contains valid data. */
1690 strcpy(dir->dd_dir.d_name, buf.cFileName);
1691 ++dir->dd_stat;
1693 /* Set file type, based on WIN32_FIND_DATA */
1694 mdir->dd_dir.d_type = 0;
1695 if ((buf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1696 (buf.dwReserved0 == IO_REPARSE_TAG_SYMLINK))
1697 mdir->dd_dir.d_type |= DT_LNK;
1698 else if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1699 mdir->dd_dir.d_type |= DT_DIR;
1700 else
1701 mdir->dd_dir.d_type |= DT_REG;
1703 return (struct dirent*)&dir->dd_dir;
1705 #endif // !NO_MINGW_REPLACE_READDIR