mingw: do not hide bare repositories
[git/dscho.git] / compat / mingw.c
blobf6b29a49cba30e6aab3b08fa8e1d605e759251e5
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include "../strbuf.h"
5 #include "../cache.h"
6 #include "../run-command.h"
8 unsigned int _CRT_fmode = _O_BINARY;
9 static const int delay[] = { 0, 1, 10, 20, 40 };
11 int err_win_to_posix(DWORD winerr)
13 int error = ENOSYS;
14 switch(winerr) {
15 case ERROR_ACCESS_DENIED: error = EACCES; break;
16 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
17 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
18 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
19 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
20 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
21 case ERROR_BAD_COMMAND: error = EIO; break;
22 case ERROR_BAD_DEVICE: error = ENODEV; break;
23 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
24 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
25 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
26 case ERROR_BAD_LENGTH: error = EINVAL; break;
27 case ERROR_BAD_PATHNAME: error = ENOENT; break;
28 case ERROR_BAD_PIPE: error = EPIPE; break;
29 case ERROR_BAD_UNIT: error = ENODEV; break;
30 case ERROR_BAD_USERNAME: error = EINVAL; break;
31 case ERROR_BROKEN_PIPE: error = EPIPE; break;
32 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
33 case ERROR_BUSY: error = EBUSY; break;
34 case ERROR_BUSY_DRIVE: error = EBUSY; break;
35 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
36 case ERROR_CANNOT_MAKE: error = EACCES; break;
37 case ERROR_CANTOPEN: error = EIO; break;
38 case ERROR_CANTREAD: error = EIO; break;
39 case ERROR_CANTWRITE: error = EIO; break;
40 case ERROR_CRC: error = EIO; break;
41 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
42 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
43 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
44 case ERROR_DIRECTORY: error = EINVAL; break;
45 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
46 case ERROR_DISK_CHANGE: error = EIO; break;
47 case ERROR_DISK_FULL: error = ENOSPC; break;
48 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
49 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
50 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
51 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
52 case ERROR_FILE_EXISTS: error = EEXIST; break;
53 case ERROR_FILE_INVALID: error = ENODEV; break;
54 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
55 case ERROR_GEN_FAILURE: error = EIO; break;
56 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
57 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
58 case ERROR_INVALID_ACCESS: error = EACCES; break;
59 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
60 case ERROR_INVALID_BLOCK: error = EFAULT; break;
61 case ERROR_INVALID_DATA: error = EINVAL; break;
62 case ERROR_INVALID_DRIVE: error = ENODEV; break;
63 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
64 case ERROR_INVALID_FLAGS: error = EINVAL; break;
65 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
66 case ERROR_INVALID_HANDLE: error = EBADF; break;
67 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
68 case ERROR_INVALID_NAME: error = EINVAL; break;
69 case ERROR_INVALID_OWNER: error = EINVAL; break;
70 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
71 case ERROR_INVALID_PASSWORD: error = EPERM; break;
72 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
73 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
74 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
75 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
76 case ERROR_IO_DEVICE: error = EIO; break;
77 case ERROR_IO_INCOMPLETE: error = EINTR; break;
78 case ERROR_LOCKED: error = EBUSY; break;
79 case ERROR_LOCK_VIOLATION: error = EACCES; break;
80 case ERROR_LOGON_FAILURE: error = EACCES; break;
81 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
82 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
83 case ERROR_MORE_DATA: error = EPIPE; break;
84 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
85 case ERROR_NOACCESS: error = EFAULT; break;
86 case ERROR_NONE_MAPPED: error = EINVAL; break;
87 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
88 case ERROR_NOT_READY: error = EAGAIN; break;
89 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
90 case ERROR_NO_DATA: error = EPIPE; break;
91 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
92 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
93 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
94 case ERROR_OPEN_FAILED: error = EIO; break;
95 case ERROR_OPEN_FILES: error = EBUSY; break;
96 case ERROR_OPERATION_ABORTED: error = EINTR; break;
97 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
98 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
99 case ERROR_PATH_BUSY: error = EBUSY; break;
100 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
101 case ERROR_PIPE_BUSY: error = EBUSY; break;
102 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
103 case ERROR_PIPE_LISTENING: error = EPIPE; break;
104 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
105 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
106 case ERROR_READ_FAULT: error = EIO; break;
107 case ERROR_SEEK: error = EIO; break;
108 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
109 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
110 case ERROR_SHARING_VIOLATION: error = EACCES; break;
111 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
112 case ERROR_SWAPERROR: error = ENOENT; break;
113 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
114 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
115 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
116 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
117 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
118 case ERROR_WRITE_FAULT: error = EIO; break;
119 case ERROR_WRITE_PROTECT: error = EROFS; break;
121 return error;
124 static int make_hidden(const char *path)
126 DWORD attribs = GetFileAttributes(path);
127 if (SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN | attribs))
128 return 0;
129 errno = err_win_to_posix(GetLastError());
130 return -1;
133 void mingw_mark_as_git_dir(const char *dir)
135 if (hide_dotfiles != HIDE_DOTFILES_FALSE && !is_bare_repository() &&
136 make_hidden(dir))
137 warning("Failed to make '%s' hidden", dir);
138 git_config_set("core.hideDotFiles",
139 hide_dotfiles == HIDE_DOTFILES_FALSE ? "false" :
140 (hide_dotfiles == HIDE_DOTFILES_DOTGITONLY ?
141 "dotGitOnly" : "true"));
144 #undef mkdir
145 int mingw_mkdir(const char *path, int mode)
147 int ret = mkdir(path);
148 if (!ret && hide_dotfiles == HIDE_DOTFILES_TRUE) {
150 * In Windows a file or dir starting with a dot is not
151 * automatically hidden. So lets mark it as hidden when
152 * such a directory is created.
154 const char *start = basename((char*)path);
155 if (*start == '.')
156 return make_hidden(path);
158 return ret;
161 static int ask_user_yes_no(const char *format, ...)
163 char answer[5];
164 char question[4096];
165 const char *retry_hook[] = { NULL, NULL, NULL };
166 va_list args;
168 if ((retry_hook[0] = getenv("GIT_ASK_YESNO"))) {
170 va_start(args, format);
171 vsnprintf(question, sizeof(question), format, args);
172 va_end(args);
174 retry_hook[1] = question;
175 return !run_command_v_opt(retry_hook, 0);
178 if (!isatty(_fileno(stdin)))
179 return 0;
181 while (1) {
182 va_start(args, format);
183 vfprintf(stderr, format, args);
184 va_end(args);
185 fprintf(stderr, " (y/n)? ");
187 if (fgets(answer, sizeof(answer), stdin)) {
188 /* remove the newline */
189 if (answer[strlen(answer)-2] == '\r')
190 answer[strlen(answer)-2] = '\0';
191 if (answer[strlen(answer)-1] == '\n')
192 answer[strlen(answer)-1] = '\0';
193 } else
194 return 0;
196 if (answer[0] == 'y' && strlen(answer) == 1)
197 return 1;
198 if (!strncasecmp(answer, "yes", sizeof(answer)))
199 return 1;
200 if (answer[0] == 'n' && strlen(answer) == 1)
201 return 0;
202 if (!strncasecmp(answer, "no", sizeof(answer)))
203 return 0;
204 fprintf(stderr, "I did not understand your answer: '%s'\n",
205 answer);
209 #undef unlink
210 int mingw_unlink(const char *pathname)
212 int ret, tries = 0;
214 /* read-only files cannot be removed */
215 chmod(pathname, 0666);
216 while ((ret = unlink(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
217 if (errno != EACCES)
218 break;
220 * We assume that some other process had the source or
221 * destination file open at the wrong moment and retry.
222 * In order to give the other process a higher chance to
223 * complete its operation, we give up our time slice now.
224 * If we have to retry again, we do sleep a bit.
226 Sleep(delay[tries]);
227 tries++;
229 while (ret == -1 && errno == EACCES &&
230 ask_user_yes_no("Unlink of file '%s' failed. "
231 "Should I try again?", pathname))
232 ret = unlink(pathname);
233 return ret;
236 #undef rmdir
237 int mingw_rmdir(const char *pathname)
239 int ret, tries = 0;
241 while ((ret = rmdir(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
242 if (errno != EACCES)
243 break;
245 * We assume that some other process had the source or
246 * destination file open at the wrong moment and retry.
247 * In order to give the other process a higher chance to
248 * complete its operation, we give up our time slice now.
249 * If we have to retry again, we do sleep a bit.
251 Sleep(delay[tries]);
252 tries++;
254 while (ret == -1 && errno == EACCES &&
255 ask_user_yes_no("Deletion of directory '%s' failed. "
256 "Should I try again?", pathname))
257 ret = rmdir(pathname);
258 return ret;
261 #undef open
262 int mingw_open (const char *filename, int oflags, ...)
264 va_list args;
265 unsigned mode;
266 int fd;
268 va_start(args, oflags);
269 mode = va_arg(args, int);
270 va_end(args);
272 if (filename && !strcmp(filename, "/dev/null"))
273 filename = "nul";
275 fd = open(filename, oflags, mode);
277 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
278 DWORD attrs = GetFileAttributes(filename);
279 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
280 errno = EISDIR;
282 if ((oflags & O_CREAT) && fd >= 0 &&
283 hide_dotfiles == HIDE_DOTFILES_TRUE) {
285 * In Windows a file or dir starting with a dot is not
286 * automatically hidden. So lets mark it as hidden when
287 * such a file is created.
289 const char *start = basename((char*)filename);
290 if (*start == '.' && make_hidden(filename))
291 warning("Could not mark '%s' as hidden.", filename);
293 return fd;
296 #undef write
297 ssize_t mingw_write(int fd, const void *buf, size_t count)
300 * While write() calls to a file on a local disk are translated
301 * into WriteFile() calls with a maximum size of 64KB on Windows
302 * XP and 256KB on Vista, no such cap is placed on writes to
303 * files over the network on Windows XP. Unfortunately, there
304 * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
305 * bigger writes fail on Windows XP.
306 * So we cap to a nice 31MB here to avoid write failures over
307 * the net without changing the number of WriteFile() calls in
308 * the local case.
310 return write(fd, buf, min(count, 31 * 1024 * 1024));
313 #undef fopen
314 FILE *mingw_fopen (const char *filename, const char *otype)
316 int hide = 0;
317 FILE *file;
318 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
319 basename((char*)filename)[0] == '.')
320 hide = access(filename, F_OK);
321 if (filename && !strcmp(filename, "/dev/null"))
322 filename = "nul";
323 file = fopen(filename, otype);
324 if (file && hide && make_hidden(filename))
325 warning("Could not mark '%s' as hidden.", filename);
326 return file;
329 #undef freopen
330 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
332 int hide = 0;
333 FILE *file;
334 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
335 basename((char*)filename)[0] == '.')
336 hide = access(filename, F_OK);
337 if (filename && !strcmp(filename, "/dev/null"))
338 filename = "nul";
339 file = freopen(filename, otype, stream);
340 if (file && hide && make_hidden(filename))
341 warning("Could not mark '%s' as hidden.", filename);
342 return file;
346 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
347 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
349 static inline long long filetime_to_hnsec(const FILETIME *ft)
351 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
352 /* Windows to Unix Epoch conversion */
353 return winTime - 116444736000000000LL;
356 static inline time_t filetime_to_time_t(const FILETIME *ft)
358 return (time_t)(filetime_to_hnsec(ft) / 10000000);
361 /* We keep the do_lstat code in a separate function to avoid recursion.
362 * When a path ends with a slash, the stat will fail with ENOENT. In
363 * this case, we strip the trailing slashes and stat again.
365 * If follow is true then act like stat() and report on the link
366 * target. Otherwise report on the link itself.
368 static int do_lstat(int follow, const char *file_name, struct stat *buf)
370 int err;
371 WIN32_FILE_ATTRIBUTE_DATA fdata;
373 if (!(err = get_file_attr(file_name, &fdata))) {
374 buf->st_ino = 0;
375 buf->st_gid = 0;
376 buf->st_uid = 0;
377 buf->st_nlink = 1;
378 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
379 buf->st_size = fdata.nFileSizeLow |
380 (((off_t)fdata.nFileSizeHigh)<<32);
381 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
382 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
383 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
384 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
385 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
386 WIN32_FIND_DATAA findbuf;
387 HANDLE handle = FindFirstFileA(file_name, &findbuf);
388 if (handle != INVALID_HANDLE_VALUE) {
389 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
390 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
391 if (follow) {
392 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
393 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
394 } else {
395 buf->st_mode = S_IFLNK;
397 buf->st_mode |= S_IREAD;
398 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
399 buf->st_mode |= S_IWRITE;
401 FindClose(handle);
404 return 0;
406 errno = err;
407 return -1;
410 /* We provide our own lstat/fstat functions, since the provided
411 * lstat/fstat functions are so slow. These stat functions are
412 * tailored for Git's usage (read: fast), and are not meant to be
413 * complete. Note that Git stat()s are redirected to mingw_lstat()
414 * too, since Windows doesn't really handle symlinks that well.
416 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
418 int namelen;
419 static char alt_name[PATH_MAX];
421 if (!do_lstat(follow, file_name, buf))
422 return 0;
424 /* if file_name ended in a '/', Windows returned ENOENT;
425 * try again without trailing slashes
427 if (errno != ENOENT)
428 return -1;
430 namelen = strlen(file_name);
431 if (namelen && file_name[namelen-1] != '/')
432 return -1;
433 while (namelen && file_name[namelen-1] == '/')
434 --namelen;
435 if (!namelen || namelen >= PATH_MAX)
436 return -1;
438 memcpy(alt_name, file_name, namelen);
439 alt_name[namelen] = 0;
440 return do_lstat(follow, alt_name, buf);
443 int mingw_lstat(const char *file_name, struct stat *buf)
445 return do_stat_internal(0, file_name, buf);
447 int mingw_stat(const char *file_name, struct stat *buf)
449 return do_stat_internal(1, file_name, buf);
452 #undef fstat
453 int mingw_fstat(int fd, struct stat *buf)
455 HANDLE fh = (HANDLE)_get_osfhandle(fd);
456 BY_HANDLE_FILE_INFORMATION fdata;
458 if (fh == INVALID_HANDLE_VALUE) {
459 errno = EBADF;
460 return -1;
462 /* direct non-file handles to MS's fstat() */
463 if (GetFileType(fh) != FILE_TYPE_DISK)
464 return _fstati64(fd, buf);
466 if (GetFileInformationByHandle(fh, &fdata)) {
467 buf->st_ino = 0;
468 buf->st_gid = 0;
469 buf->st_uid = 0;
470 buf->st_nlink = 1;
471 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
472 buf->st_size = fdata.nFileSizeLow |
473 (((off_t)fdata.nFileSizeHigh)<<32);
474 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
475 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
476 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
477 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
478 return 0;
480 errno = EBADF;
481 return -1;
484 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
486 long long winTime = t * 10000000LL + 116444736000000000LL;
487 ft->dwLowDateTime = winTime;
488 ft->dwHighDateTime = winTime >> 32;
491 int mingw_utime (const char *file_name, const struct utimbuf *times)
493 FILETIME mft, aft;
494 int fh, rc;
496 /* must have write permission */
497 DWORD attrs = GetFileAttributes(file_name);
498 if (attrs != INVALID_FILE_ATTRIBUTES &&
499 (attrs & FILE_ATTRIBUTE_READONLY)) {
500 /* ignore errors here; open() will report them */
501 SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
504 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
505 rc = -1;
506 goto revert_attrs;
509 if (times) {
510 time_t_to_filetime(times->modtime, &mft);
511 time_t_to_filetime(times->actime, &aft);
512 } else {
513 GetSystemTimeAsFileTime(&mft);
514 aft = mft;
516 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
517 errno = EINVAL;
518 rc = -1;
519 } else
520 rc = 0;
521 close(fh);
523 revert_attrs:
524 if (attrs != INVALID_FILE_ATTRIBUTES &&
525 (attrs & FILE_ATTRIBUTE_READONLY)) {
526 /* ignore errors again */
527 SetFileAttributes(file_name, attrs);
529 return rc;
532 unsigned int sleep (unsigned int seconds)
534 Sleep(seconds*1000);
535 return 0;
538 int mkstemp(char *template)
540 char *filename = mktemp(template);
541 if (filename == NULL)
542 return -1;
543 return open(filename, O_RDWR | O_CREAT, 0600);
546 int gettimeofday(struct timeval *tv, void *tz)
548 FILETIME ft;
549 long long hnsec;
551 GetSystemTimeAsFileTime(&ft);
552 hnsec = filetime_to_hnsec(&ft);
553 tv->tv_sec = hnsec / 10000000;
554 tv->tv_usec = (hnsec % 10000000) / 10;
555 return 0;
558 int pipe(int filedes[2])
560 HANDLE h[2];
562 /* this creates non-inheritable handles */
563 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
564 errno = err_win_to_posix(GetLastError());
565 return -1;
567 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
568 if (filedes[0] < 0) {
569 CloseHandle(h[0]);
570 CloseHandle(h[1]);
571 return -1;
573 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
574 if (filedes[0] < 0) {
575 close(filedes[0]);
576 CloseHandle(h[1]);
577 return -1;
579 return 0;
582 struct tm *gmtime_r(const time_t *timep, struct tm *result)
584 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
585 memcpy(result, gmtime(timep), sizeof(struct tm));
586 return result;
589 struct tm *localtime_r(const time_t *timep, struct tm *result)
591 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
592 memcpy(result, localtime(timep), sizeof(struct tm));
593 return result;
596 #undef getcwd
597 char *mingw_getcwd(char *pointer, int len)
599 int i;
600 char *ret = getcwd(pointer, len);
601 if (!ret)
602 return ret;
603 for (i = 0; pointer[i]; i++)
604 if (pointer[i] == '\\')
605 pointer[i] = '/';
606 return ret;
609 #undef getenv
610 char *mingw_getenv(const char *name)
612 char *result = getenv(name);
613 if (!result && !strcmp(name, "TMPDIR")) {
614 /* on Windows it is TMP and TEMP */
615 result = getenv("TMP");
616 if (!result)
617 result = getenv("TEMP");
619 return result;
623 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
624 * (Parsing C++ Command-Line Arguments)
626 static const char *quote_arg(const char *arg)
628 /* count chars to quote */
629 int len = 0, n = 0;
630 int force_quotes = 0;
631 char *q, *d;
632 const char *p = arg;
633 if (!*p) force_quotes = 1;
634 while (*p) {
635 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
636 force_quotes = 1;
637 else if (*p == '"')
638 n++;
639 else if (*p == '\\') {
640 int count = 0;
641 while (*p == '\\') {
642 count++;
643 p++;
644 len++;
646 if (*p == '"')
647 n += count*2 + 1;
648 continue;
650 len++;
651 p++;
653 if (!force_quotes && n == 0)
654 return arg;
656 /* insert \ where necessary */
657 d = q = xmalloc(len+n+3);
658 *d++ = '"';
659 while (*arg) {
660 if (*arg == '"')
661 *d++ = '\\';
662 else if (*arg == '\\') {
663 int count = 0;
664 while (*arg == '\\') {
665 count++;
666 *d++ = *arg++;
668 if (*arg == '"') {
669 while (count-- > 0)
670 *d++ = '\\';
671 *d++ = '\\';
674 *d++ = *arg++;
676 *d++ = '"';
677 *d++ = 0;
678 return q;
681 static const char *parse_interpreter(const char *cmd)
683 static char buf[100];
684 char *p, *opt;
685 int n, fd;
687 /* don't even try a .exe */
688 n = strlen(cmd);
689 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
690 return NULL;
692 fd = open(cmd, O_RDONLY);
693 if (fd < 0)
694 return NULL;
695 n = read(fd, buf, sizeof(buf)-1);
696 close(fd);
697 if (n < 4) /* at least '#!/x' and not error */
698 return NULL;
700 if (buf[0] != '#' || buf[1] != '!')
701 return NULL;
702 buf[n] = '\0';
703 p = buf + strcspn(buf, "\r\n");
704 if (!*p)
705 return NULL;
707 *p = '\0';
708 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
709 return NULL;
710 /* strip options */
711 if ((opt = strchr(p+1, ' ')))
712 *opt = '\0';
713 return p+1;
717 * Splits the PATH into parts.
719 static char **get_path_split(void)
721 char *p, **path, *envpath = getenv("PATH");
722 int i, n = 0;
724 if (!envpath || !*envpath)
725 return NULL;
727 envpath = xstrdup(envpath);
728 p = envpath;
729 while (p) {
730 char *dir = p;
731 p = strchr(p, ';');
732 if (p) *p++ = '\0';
733 if (*dir) { /* not earlier, catches series of ; */
734 ++n;
737 if (!n)
738 return NULL;
740 path = xmalloc((n+1)*sizeof(char *));
741 p = envpath;
742 i = 0;
743 do {
744 if (*p)
745 path[i++] = xstrdup(p);
746 p = p+strlen(p)+1;
747 } while (i < n);
748 path[i] = NULL;
750 free(envpath);
752 return path;
755 static void free_path_split(char **path)
757 char **p = path;
759 if (!path)
760 return;
762 while (*p)
763 free(*p++);
764 free(path);
768 * exe_only means that we only want to detect .exe files, but not scripts
769 * (which do not have an extension)
771 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
773 char path[MAX_PATH];
774 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
776 if (!isexe && access(path, F_OK) == 0)
777 return xstrdup(path);
778 path[strlen(path)-4] = '\0';
779 if ((!exe_only || isexe) && access(path, F_OK) == 0)
780 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
781 return xstrdup(path);
782 return NULL;
786 * Determines the absolute path of cmd using the split path in path.
787 * If cmd contains a slash or backslash, no lookup is performed.
789 static char *path_lookup(const char *cmd, char **path, int exe_only)
791 char *prog = NULL;
792 int len = strlen(cmd);
793 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
795 if (strchr(cmd, '/') || strchr(cmd, '\\'))
796 prog = xstrdup(cmd);
798 while (!prog && *path)
799 prog = lookup_prog(*path++, cmd, isexe, exe_only);
801 return prog;
804 static int env_compare(const void *a, const void *b)
806 char *const *ea = a;
807 char *const *eb = b;
808 return strcasecmp(*ea, *eb);
811 struct pinfo_t {
812 struct pinfo_t *next;
813 pid_t pid;
814 HANDLE proc;
815 } pinfo_t;
816 struct pinfo_t *pinfo = NULL;
817 CRITICAL_SECTION pinfo_cs;
819 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
820 const char *dir,
821 int prepend_cmd, int fhin, int fhout, int fherr)
823 STARTUPINFO si;
824 PROCESS_INFORMATION pi;
825 struct strbuf envblk, args;
826 unsigned flags;
827 BOOL ret;
829 /* Determine whether or not we are associated to a console */
830 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
831 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
832 FILE_ATTRIBUTE_NORMAL, NULL);
833 if (cons == INVALID_HANDLE_VALUE) {
834 /* There is no console associated with this process.
835 * Since the child is a console process, Windows
836 * would normally create a console window. But
837 * since we'll be redirecting std streams, we do
838 * not need the console.
839 * It is necessary to use DETACHED_PROCESS
840 * instead of CREATE_NO_WINDOW to make ssh
841 * recognize that it has no console.
843 flags = DETACHED_PROCESS;
844 } else {
845 /* There is already a console. If we specified
846 * DETACHED_PROCESS here, too, Windows would
847 * disassociate the child from the console.
848 * The same is true for CREATE_NO_WINDOW.
849 * Go figure!
851 flags = 0;
852 CloseHandle(cons);
854 memset(&si, 0, sizeof(si));
855 si.cb = sizeof(si);
856 si.dwFlags = STARTF_USESTDHANDLES;
857 si.hStdInput = (HANDLE) _get_osfhandle(fhin);
858 si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
859 si.hStdError = (HANDLE) _get_osfhandle(fherr);
861 /* concatenate argv, quoting args as we go */
862 strbuf_init(&args, 0);
863 if (prepend_cmd) {
864 char *quoted = (char *)quote_arg(cmd);
865 strbuf_addstr(&args, quoted);
866 if (quoted != cmd)
867 free(quoted);
869 for (; *argv; argv++) {
870 char *quoted = (char *)quote_arg(*argv);
871 if (*args.buf)
872 strbuf_addch(&args, ' ');
873 strbuf_addstr(&args, quoted);
874 if (quoted != *argv)
875 free(quoted);
878 if (env) {
879 int count = 0;
880 char **e, **sorted_env;
882 for (e = env; *e; e++)
883 count++;
885 /* environment must be sorted */
886 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
887 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
888 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
890 strbuf_init(&envblk, 0);
891 for (e = sorted_env; *e; e++) {
892 strbuf_addstr(&envblk, *e);
893 strbuf_addch(&envblk, '\0');
895 free(sorted_env);
898 memset(&pi, 0, sizeof(pi));
899 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
900 env ? envblk.buf : NULL, dir, &si, &pi);
902 if (env)
903 strbuf_release(&envblk);
904 strbuf_release(&args);
906 if (!ret) {
907 errno = ENOENT;
908 return -1;
910 CloseHandle(pi.hThread);
913 * The process ID is the human-readable identifier of the process
914 * that we want to present in log and error messages. The handle
915 * is not useful for this purpose. But we cannot close it, either,
916 * because it is not possible to turn a process ID into a process
917 * handle after the process terminated.
918 * Keep the handle in a list for waitpid.
920 EnterCriticalSection(&pinfo_cs);
922 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
923 info->pid = pi.dwProcessId;
924 info->proc = pi.hProcess;
925 info->next = pinfo;
926 pinfo = info;
928 LeaveCriticalSection(&pinfo_cs);
930 return (pid_t)pi.dwProcessId;
933 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
934 int prepend_cmd)
936 return mingw_spawnve_fd(cmd, argv, env, NULL, prepend_cmd, 0, 1, 2);
939 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
940 const char *dir,
941 int fhin, int fhout, int fherr)
943 pid_t pid;
944 char **path = get_path_split();
945 char *prog = path_lookup(cmd, path, 0);
947 if (!prog) {
948 errno = ENOENT;
949 pid = -1;
951 else {
952 const char *interpr = parse_interpreter(prog);
954 if (interpr) {
955 const char *argv0 = argv[0];
956 char *iprog = path_lookup(interpr, path, 1);
957 argv[0] = prog;
958 if (!iprog) {
959 errno = ENOENT;
960 pid = -1;
962 else {
963 pid = mingw_spawnve_fd(iprog, argv, env, dir, 1,
964 fhin, fhout, fherr);
965 free(iprog);
967 argv[0] = argv0;
969 else
970 pid = mingw_spawnve_fd(prog, argv, env, dir, 0,
971 fhin, fhout, fherr);
972 free(prog);
974 free_path_split(path);
975 return pid;
978 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
980 const char *interpr = parse_interpreter(cmd);
981 char **path;
982 char *prog;
983 int pid = 0;
985 if (!interpr)
986 return 0;
987 path = get_path_split();
988 prog = path_lookup(interpr, path, 1);
989 if (prog) {
990 int argc = 0;
991 const char **argv2;
992 while (argv[argc]) argc++;
993 argv2 = xmalloc(sizeof(*argv) * (argc+1));
994 argv2[0] = (char *)cmd; /* full path to the script file */
995 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
996 pid = mingw_spawnve(prog, argv2, env, 1);
997 if (pid >= 0) {
998 int status;
999 if (waitpid(pid, &status, 0) < 0)
1000 status = 255;
1001 exit(status);
1003 pid = 1; /* indicate that we tried but failed */
1004 free(prog);
1005 free(argv2);
1007 free_path_split(path);
1008 return pid;
1011 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
1013 /* check if git_command is a shell script */
1014 if (!try_shell_exec(cmd, argv, (char **)env)) {
1015 int pid, status;
1017 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
1018 if (pid < 0)
1019 return;
1020 if (waitpid(pid, &status, 0) < 0)
1021 status = 255;
1022 exit(status);
1026 void mingw_execvp(const char *cmd, char *const *argv)
1028 char **path = get_path_split();
1029 char *prog = path_lookup(cmd, path, 0);
1031 if (prog) {
1032 mingw_execve(prog, argv, environ);
1033 free(prog);
1034 } else
1035 errno = ENOENT;
1037 free_path_split(path);
1040 void mingw_execv(const char *cmd, char *const *argv)
1042 mingw_execve(cmd, argv, environ);
1045 int mingw_kill(pid_t pid, int sig)
1047 if (pid > 0 && sig == SIGTERM) {
1048 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1050 if (TerminateProcess(h, -1)) {
1051 CloseHandle(h);
1052 return 0;
1055 errno = err_win_to_posix(GetLastError());
1056 CloseHandle(h);
1057 return -1;
1060 errno = EINVAL;
1061 return -1;
1064 static char **copy_environ(void)
1066 char **env;
1067 int i = 0;
1068 while (environ[i])
1069 i++;
1070 env = xmalloc((i+1)*sizeof(*env));
1071 for (i = 0; environ[i]; i++)
1072 env[i] = xstrdup(environ[i]);
1073 env[i] = NULL;
1074 return env;
1077 void free_environ(char **env)
1079 int i;
1080 for (i = 0; env[i]; i++)
1081 free(env[i]);
1082 free(env);
1085 static int lookup_env(char **env, const char *name, size_t nmln)
1087 int i;
1089 for (i = 0; env[i]; i++) {
1090 if (0 == strncmp(env[i], name, nmln)
1091 && '=' == env[i][nmln])
1092 /* matches */
1093 return i;
1095 return -1;
1099 * If name contains '=', then sets the variable, otherwise it unsets it
1101 static char **env_setenv(char **env, const char *name)
1103 char *eq = strchrnul(name, '=');
1104 int i = lookup_env(env, name, eq-name);
1106 if (i < 0) {
1107 if (*eq) {
1108 for (i = 0; env[i]; i++)
1110 env = xrealloc(env, (i+2)*sizeof(*env));
1111 env[i] = xstrdup(name);
1112 env[i+1] = NULL;
1115 else {
1116 free(env[i]);
1117 if (*eq)
1118 env[i] = xstrdup(name);
1119 else
1120 for (; env[i]; i++)
1121 env[i] = env[i+1];
1123 return env;
1127 * Copies global environ and adjusts variables as specified by vars.
1129 char **make_augmented_environ(const char *const *vars)
1131 char **env = copy_environ();
1133 while (*vars)
1134 env = env_setenv(env, *vars++);
1135 return env;
1139 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1140 * that service contains a numerical port, or that it it is null. It
1141 * does a simple search using gethostbyname, and returns one IPv4 host
1142 * if one was found.
1144 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1145 const struct addrinfo *hints,
1146 struct addrinfo **res)
1148 struct hostent *h = NULL;
1149 struct addrinfo *ai;
1150 struct sockaddr_in *sin;
1152 if (node) {
1153 h = gethostbyname(node);
1154 if (!h)
1155 return WSAGetLastError();
1158 ai = xmalloc(sizeof(struct addrinfo));
1159 *res = ai;
1160 ai->ai_flags = 0;
1161 ai->ai_family = AF_INET;
1162 ai->ai_socktype = hints ? hints->ai_socktype : 0;
1163 switch (ai->ai_socktype) {
1164 case SOCK_STREAM:
1165 ai->ai_protocol = IPPROTO_TCP;
1166 break;
1167 case SOCK_DGRAM:
1168 ai->ai_protocol = IPPROTO_UDP;
1169 break;
1170 default:
1171 ai->ai_protocol = 0;
1172 break;
1174 ai->ai_addrlen = sizeof(struct sockaddr_in);
1175 if (hints && (hints->ai_flags & AI_CANONNAME))
1176 ai->ai_canonname = h ? strdup(h->h_name) : NULL;
1177 else
1178 ai->ai_canonname = NULL;
1180 sin = xmalloc(ai->ai_addrlen);
1181 memset(sin, 0, ai->ai_addrlen);
1182 sin->sin_family = AF_INET;
1183 /* Note: getaddrinfo is supposed to allow service to be a string,
1184 * which should be looked up using getservbyname. This is
1185 * currently not implemented */
1186 if (service)
1187 sin->sin_port = htons(atoi(service));
1188 if (h)
1189 sin->sin_addr = *(struct in_addr *)h->h_addr;
1190 else if (hints && (hints->ai_flags & AI_PASSIVE))
1191 sin->sin_addr.s_addr = INADDR_ANY;
1192 else
1193 sin->sin_addr.s_addr = INADDR_LOOPBACK;
1194 ai->ai_addr = (struct sockaddr *)sin;
1195 ai->ai_next = 0;
1196 return 0;
1199 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1201 free(res->ai_canonname);
1202 free(res->ai_addr);
1203 free(res);
1206 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1207 char *host, DWORD hostlen,
1208 char *serv, DWORD servlen, int flags)
1210 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1211 if (sa->sa_family != AF_INET)
1212 return EAI_FAMILY;
1213 if (!host && !serv)
1214 return EAI_NONAME;
1216 if (host && hostlen > 0) {
1217 struct hostent *ent = NULL;
1218 if (!(flags & NI_NUMERICHOST))
1219 ent = gethostbyaddr((const char *)&sin->sin_addr,
1220 sizeof(sin->sin_addr), AF_INET);
1222 if (ent)
1223 snprintf(host, hostlen, "%s", ent->h_name);
1224 else if (flags & NI_NAMEREQD)
1225 return EAI_NONAME;
1226 else
1227 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1230 if (serv && servlen > 0) {
1231 struct servent *ent = NULL;
1232 if (!(flags & NI_NUMERICSERV))
1233 ent = getservbyport(sin->sin_port,
1234 flags & NI_DGRAM ? "udp" : "tcp");
1236 if (ent)
1237 snprintf(serv, servlen, "%s", ent->s_name);
1238 else
1239 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1242 return 0;
1245 static HMODULE ipv6_dll = NULL;
1246 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1247 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1248 const struct addrinfo *hints,
1249 struct addrinfo **res);
1250 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1251 char *host, DWORD hostlen,
1252 char *serv, DWORD servlen, int flags);
1254 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1255 * don't need to try to load that one dynamically.
1258 static void socket_cleanup(void)
1260 WSACleanup();
1261 if (ipv6_dll)
1262 FreeLibrary(ipv6_dll);
1263 ipv6_dll = NULL;
1264 ipv6_freeaddrinfo = freeaddrinfo_stub;
1265 ipv6_getaddrinfo = getaddrinfo_stub;
1266 ipv6_getnameinfo = getnameinfo_stub;
1269 static void ensure_socket_initialization(void)
1271 WSADATA wsa;
1272 static int initialized = 0;
1273 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1274 const char **name;
1276 if (initialized)
1277 return;
1279 if (WSAStartup(MAKEWORD(2,2), &wsa))
1280 die("unable to initialize winsock subsystem, error %d",
1281 WSAGetLastError());
1283 for (name = libraries; *name; name++) {
1284 ipv6_dll = LoadLibrary(*name);
1285 if (!ipv6_dll)
1286 continue;
1288 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1289 GetProcAddress(ipv6_dll, "freeaddrinfo");
1290 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1291 const struct addrinfo *,
1292 struct addrinfo **))
1293 GetProcAddress(ipv6_dll, "getaddrinfo");
1294 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1295 socklen_t, char *, DWORD,
1296 char *, DWORD, int))
1297 GetProcAddress(ipv6_dll, "getnameinfo");
1298 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1299 FreeLibrary(ipv6_dll);
1300 ipv6_dll = NULL;
1301 } else
1302 break;
1304 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1305 ipv6_freeaddrinfo = freeaddrinfo_stub;
1306 ipv6_getaddrinfo = getaddrinfo_stub;
1307 ipv6_getnameinfo = getnameinfo_stub;
1310 atexit(socket_cleanup);
1311 initialized = 1;
1314 #undef gethostbyname
1315 struct hostent *mingw_gethostbyname(const char *host)
1317 ensure_socket_initialization();
1318 return gethostbyname(host);
1321 void mingw_freeaddrinfo(struct addrinfo *res)
1323 ipv6_freeaddrinfo(res);
1326 int mingw_getaddrinfo(const char *node, const char *service,
1327 const struct addrinfo *hints, struct addrinfo **res)
1329 ensure_socket_initialization();
1330 return ipv6_getaddrinfo(node, service, hints, res);
1333 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1334 char *host, DWORD hostlen, char *serv, DWORD servlen,
1335 int flags)
1337 ensure_socket_initialization();
1338 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1341 int mingw_socket(int domain, int type, int protocol)
1343 int sockfd;
1344 SOCKET s;
1346 ensure_socket_initialization();
1347 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1348 if (s == INVALID_SOCKET) {
1350 * WSAGetLastError() values are regular BSD error codes
1351 * biased by WSABASEERR.
1352 * However, strerror() does not know about networking
1353 * specific errors, which are values beginning at 38 or so.
1354 * Therefore, we choose to leave the biased error code
1355 * in errno so that _if_ someone looks up the code somewhere,
1356 * then it is at least the number that are usually listed.
1358 errno = WSAGetLastError();
1359 return -1;
1361 /* convert into a file descriptor */
1362 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1363 closesocket(s);
1364 return error("unable to make a socket file descriptor: %s",
1365 strerror(errno));
1367 return sockfd;
1370 #undef connect
1371 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1373 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1374 return connect(s, sa, sz);
1377 #undef bind
1378 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1380 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1381 return bind(s, sa, sz);
1384 #undef setsockopt
1385 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1387 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1388 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1391 #undef listen
1392 int mingw_listen(int sockfd, int backlog)
1394 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1395 return listen(s, backlog);
1398 #undef accept
1399 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1401 int sockfd2;
1403 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1404 SOCKET s2 = accept(s1, sa, sz);
1406 /* convert into a file descriptor */
1407 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1408 int err = errno;
1409 closesocket(s2);
1410 return error("unable to make a socket file descriptor: %s",
1411 strerror(err));
1413 return sockfd2;
1416 #undef rename
1417 int mingw_rename(const char *pold, const char *pnew)
1419 DWORD attrs, gle;
1420 int tries = 0;
1423 * Try native rename() first to get errno right.
1424 * It is based on MoveFile(), which cannot overwrite existing files.
1426 if (!rename(pold, pnew))
1427 return 0;
1428 if (errno != EEXIST)
1429 return -1;
1430 repeat:
1431 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1432 return 0;
1433 /* TODO: translate more errors */
1434 gle = GetLastError();
1435 if (gle == ERROR_ACCESS_DENIED &&
1436 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1437 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1438 errno = EISDIR;
1439 return -1;
1441 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1442 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1443 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1444 return 0;
1445 gle = GetLastError();
1446 /* revert file attributes on failure */
1447 SetFileAttributes(pnew, attrs);
1450 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1452 * We assume that some other process had the source or
1453 * destination file open at the wrong moment and retry.
1454 * In order to give the other process a higher chance to
1455 * complete its operation, we give up our time slice now.
1456 * If we have to retry again, we do sleep a bit.
1458 Sleep(delay[tries]);
1459 tries++;
1460 goto repeat;
1462 if (gle == ERROR_ACCESS_DENIED &&
1463 ask_user_yes_no("Rename from '%s' to '%s' failed. "
1464 "Should I try again?", pold, pnew))
1465 goto repeat;
1467 errno = EACCES;
1468 return -1;
1472 * Note that this doesn't return the actual pagesize, but
1473 * the allocation granularity. If future Windows specific git code
1474 * needs the real getpagesize function, we need to find another solution.
1476 int mingw_getpagesize(void)
1478 SYSTEM_INFO si;
1479 GetSystemInfo(&si);
1480 return si.dwAllocationGranularity;
1483 struct passwd *getpwuid(int uid)
1485 static char user_name[100];
1486 static struct passwd p;
1488 DWORD len = sizeof(user_name);
1489 if (!GetUserName(user_name, &len))
1490 return NULL;
1491 p.pw_name = user_name;
1492 p.pw_gecos = "unknown";
1493 p.pw_dir = NULL;
1494 return &p;
1497 static HANDLE timer_event;
1498 static HANDLE timer_thread;
1499 static int timer_interval;
1500 static int one_shot;
1501 static sig_handler_t timer_fn = SIG_DFL;
1503 /* The timer works like this:
1504 * The thread, ticktack(), is a trivial routine that most of the time
1505 * only waits to receive the signal to terminate. The main thread tells
1506 * the thread to terminate by setting the timer_event to the signalled
1507 * state.
1508 * But ticktack() interrupts the wait state after the timer's interval
1509 * length to call the signal handler.
1512 static unsigned __stdcall ticktack(void *dummy)
1514 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1515 if (timer_fn == SIG_DFL)
1516 die("Alarm");
1517 if (timer_fn != SIG_IGN)
1518 timer_fn(SIGALRM);
1519 if (one_shot)
1520 break;
1522 return 0;
1525 static int start_timer_thread(void)
1527 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1528 if (timer_event) {
1529 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1530 if (!timer_thread )
1531 return errno = ENOMEM,
1532 error("cannot start timer thread");
1533 } else
1534 return errno = ENOMEM,
1535 error("cannot allocate resources for timer");
1536 return 0;
1539 static void stop_timer_thread(void)
1541 if (timer_event)
1542 SetEvent(timer_event); /* tell thread to terminate */
1543 if (timer_thread) {
1544 int rc = WaitForSingleObject(timer_thread, 1000);
1545 if (rc == WAIT_TIMEOUT)
1546 error("timer thread did not terminate timely");
1547 else if (rc != WAIT_OBJECT_0)
1548 error("waiting for timer thread failed: %lu",
1549 GetLastError());
1550 CloseHandle(timer_thread);
1552 if (timer_event)
1553 CloseHandle(timer_event);
1554 timer_event = NULL;
1555 timer_thread = NULL;
1558 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1560 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1563 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1565 static const struct timeval zero;
1566 static int atexit_done;
1568 if (out != NULL)
1569 return errno = EINVAL,
1570 error("setitimer param 3 != NULL not implemented");
1571 if (!is_timeval_eq(&in->it_interval, &zero) &&
1572 !is_timeval_eq(&in->it_interval, &in->it_value))
1573 return errno = EINVAL,
1574 error("setitimer: it_interval must be zero or eq it_value");
1576 if (timer_thread)
1577 stop_timer_thread();
1579 if (is_timeval_eq(&in->it_value, &zero) &&
1580 is_timeval_eq(&in->it_interval, &zero))
1581 return 0;
1583 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1584 one_shot = is_timeval_eq(&in->it_interval, &zero);
1585 if (!atexit_done) {
1586 atexit(stop_timer_thread);
1587 atexit_done = 1;
1589 return start_timer_thread();
1592 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1594 if (sig != SIGALRM)
1595 return errno = EINVAL,
1596 error("sigaction only implemented for SIGALRM");
1597 if (out != NULL)
1598 return errno = EINVAL,
1599 error("sigaction: param 3 != NULL not implemented");
1601 timer_fn = in->sa_handler;
1602 return 0;
1605 #undef signal
1606 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1608 sig_handler_t old = timer_fn;
1609 if (sig != SIGALRM)
1610 return signal(sig, handler);
1611 timer_fn = handler;
1612 return old;
1615 static const char *make_backslash_path(const char *path)
1617 static char buf[PATH_MAX + 1];
1618 char *c;
1620 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1621 die("Too long path: %.*s", 60, path);
1623 for (c = buf; *c; c++) {
1624 if (*c == '/')
1625 *c = '\\';
1627 return buf;
1630 void mingw_open_html(const char *unixpath)
1632 const char *htmlpath = make_backslash_path(unixpath);
1633 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1634 const char *, const char *, const char *, INT);
1635 T ShellExecute;
1636 HMODULE shell32;
1637 int r;
1639 shell32 = LoadLibrary("shell32.dll");
1640 if (!shell32)
1641 die("cannot load shell32.dll");
1642 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1643 if (!ShellExecute)
1644 die("cannot run browser");
1646 printf("Launching default browser to display HTML ...\n");
1647 r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1648 FreeLibrary(shell32);
1649 /* see the MSDN documentation referring to the result codes here */
1650 if (r <= 32) {
1651 die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1655 int link(const char *oldpath, const char *newpath)
1657 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1658 static T create_hard_link = NULL;
1659 if (!create_hard_link) {
1660 create_hard_link = (T) GetProcAddress(
1661 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1662 if (!create_hard_link)
1663 create_hard_link = (T)-1;
1665 if (create_hard_link == (T)-1) {
1666 errno = ENOSYS;
1667 return -1;
1669 if (!create_hard_link(newpath, oldpath, NULL)) {
1670 errno = err_win_to_posix(GetLastError());
1671 return -1;
1673 return 0;
1676 char *getpass(const char *prompt)
1678 struct strbuf buf = STRBUF_INIT;
1680 fputs(prompt, stderr);
1681 for (;;) {
1682 char c = _getch();
1683 if (c == '\r' || c == '\n')
1684 break;
1685 strbuf_addch(&buf, c);
1687 fputs("\n", stderr);
1688 return strbuf_detach(&buf, NULL);
1691 pid_t waitpid(pid_t pid, int *status, unsigned options)
1693 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
1694 FALSE, pid);
1695 if (!h) {
1696 errno = ECHILD;
1697 return -1;
1700 if (pid > 0 && options & WNOHANG) {
1701 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
1702 CloseHandle(h);
1703 return 0;
1705 options &= ~WNOHANG;
1708 if (options == 0) {
1709 struct pinfo_t **ppinfo;
1710 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
1711 CloseHandle(h);
1712 return 0;
1715 if (status)
1716 GetExitCodeProcess(h, (LPDWORD)status);
1718 EnterCriticalSection(&pinfo_cs);
1720 ppinfo = &pinfo;
1721 while (*ppinfo) {
1722 struct pinfo_t *info = *ppinfo;
1723 if (info->pid == pid) {
1724 CloseHandle(info->proc);
1725 *ppinfo = info->next;
1726 free(info);
1727 break;
1729 ppinfo = &info->next;
1732 LeaveCriticalSection(&pinfo_cs);
1734 CloseHandle(h);
1735 return pid;
1737 CloseHandle(h);
1739 errno = EINVAL;
1740 return -1;