criss cross rename failure workaround
[git/dscho.git] / compat / mingw.c
blob921ca7c61f58e0271a8251c96a62f5f09fd168ea
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include "../strbuf.h"
5 #include "../cache.h"
7 unsigned int _CRT_fmode = _O_BINARY;
9 int err_win_to_posix(DWORD winerr)
11 int error = ENOSYS;
12 switch(winerr) {
13 case ERROR_ACCESS_DENIED: error = EACCES; break;
14 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
15 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
16 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
17 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
18 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
19 case ERROR_BAD_COMMAND: error = EIO; break;
20 case ERROR_BAD_DEVICE: error = ENODEV; break;
21 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
22 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
23 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
24 case ERROR_BAD_LENGTH: error = EINVAL; break;
25 case ERROR_BAD_PATHNAME: error = ENOENT; break;
26 case ERROR_BAD_PIPE: error = EPIPE; break;
27 case ERROR_BAD_UNIT: error = ENODEV; break;
28 case ERROR_BAD_USERNAME: error = EINVAL; break;
29 case ERROR_BROKEN_PIPE: error = EPIPE; break;
30 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
31 case ERROR_BUSY: error = EBUSY; break;
32 case ERROR_BUSY_DRIVE: error = EBUSY; break;
33 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
34 case ERROR_CANNOT_MAKE: error = EACCES; break;
35 case ERROR_CANTOPEN: error = EIO; break;
36 case ERROR_CANTREAD: error = EIO; break;
37 case ERROR_CANTWRITE: error = EIO; break;
38 case ERROR_CRC: error = EIO; break;
39 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
40 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
41 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
42 case ERROR_DIRECTORY: error = EINVAL; break;
43 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
44 case ERROR_DISK_CHANGE: error = EIO; break;
45 case ERROR_DISK_FULL: error = ENOSPC; break;
46 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
47 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
48 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
49 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
50 case ERROR_FILE_EXISTS: error = EEXIST; break;
51 case ERROR_FILE_INVALID: error = ENODEV; break;
52 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
53 case ERROR_GEN_FAILURE: error = EIO; break;
54 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
55 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
56 case ERROR_INVALID_ACCESS: error = EACCES; break;
57 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
58 case ERROR_INVALID_BLOCK: error = EFAULT; break;
59 case ERROR_INVALID_DATA: error = EINVAL; break;
60 case ERROR_INVALID_DRIVE: error = ENODEV; break;
61 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
62 case ERROR_INVALID_FLAGS: error = EINVAL; break;
63 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
64 case ERROR_INVALID_HANDLE: error = EBADF; break;
65 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
66 case ERROR_INVALID_NAME: error = EINVAL; break;
67 case ERROR_INVALID_OWNER: error = EINVAL; break;
68 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
69 case ERROR_INVALID_PASSWORD: error = EPERM; break;
70 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
71 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
72 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
73 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
74 case ERROR_IO_DEVICE: error = EIO; break;
75 case ERROR_IO_INCOMPLETE: error = EINTR; break;
76 case ERROR_LOCKED: error = EBUSY; break;
77 case ERROR_LOCK_VIOLATION: error = EACCES; break;
78 case ERROR_LOGON_FAILURE: error = EACCES; break;
79 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
80 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
81 case ERROR_MORE_DATA: error = EPIPE; break;
82 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
83 case ERROR_NOACCESS: error = EFAULT; break;
84 case ERROR_NONE_MAPPED: error = EINVAL; break;
85 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
86 case ERROR_NOT_READY: error = EAGAIN; break;
87 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
88 case ERROR_NO_DATA: error = EPIPE; break;
89 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
90 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
91 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
92 case ERROR_OPEN_FAILED: error = EIO; break;
93 case ERROR_OPEN_FILES: error = EBUSY; break;
94 case ERROR_OPERATION_ABORTED: error = EINTR; break;
95 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
96 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
97 case ERROR_PATH_BUSY: error = EBUSY; break;
98 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
99 case ERROR_PIPE_BUSY: error = EBUSY; break;
100 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
101 case ERROR_PIPE_LISTENING: error = EPIPE; break;
102 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
103 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
104 case ERROR_READ_FAULT: error = EIO; break;
105 case ERROR_SEEK: error = EIO; break;
106 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
107 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
108 case ERROR_SHARING_VIOLATION: error = EACCES; break;
109 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
110 case ERROR_SWAPERROR: error = ENOENT; break;
111 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
112 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
113 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
114 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
115 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
116 case ERROR_WRITE_FAULT: error = EIO; break;
117 case ERROR_WRITE_PROTECT: error = EROFS; break;
119 return error;
122 static int make_hidden(const char *path)
124 DWORD attribs = GetFileAttributes(path);
125 if (SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN | attribs))
126 return 0;
127 errno = err_win_to_posix(GetLastError());
128 return -1;
131 void mingw_mark_as_git_dir(const char *dir)
133 if (hide_dotfiles != HIDE_DOTFILES_FALSE && make_hidden(dir))
134 warning("Failed to make '%s' hidden", dir);
135 git_config_set("core.hideDotFiles",
136 hide_dotfiles == HIDE_DOTFILES_FALSE ? "false" :
137 (hide_dotfiles == HIDE_DOTFILES_DOTGITONLY ?
138 "dotGitOnly" : "true"));
141 #undef mkdir
142 int mingw_mkdir(const char *path, int mode)
144 int ret = mkdir(path);
145 if (!ret && hide_dotfiles == HIDE_DOTFILES_TRUE) {
147 * In Windows a file or dir starting with a dot is not
148 * automatically hidden. So lets mark it as hidden when
149 * such a directory is created.
151 const char *start = basename((char*)path);
152 if (*start == '.')
153 return make_hidden(path);
155 return ret;
158 #undef open
159 int mingw_open (const char *filename, int oflags, ...)
161 va_list args;
162 unsigned mode;
163 int fd;
165 va_start(args, oflags);
166 mode = va_arg(args, int);
167 va_end(args);
169 if (!strcmp(filename, "/dev/null"))
170 filename = "nul";
172 fd = open(filename, oflags, mode);
174 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
175 DWORD attrs = GetFileAttributes(filename);
176 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
177 errno = EISDIR;
179 if ((oflags & O_CREAT) && fd >= 0 &&
180 hide_dotfiles == HIDE_DOTFILES_TRUE) {
182 * In Windows a file or dir starting with a dot is not
183 * automatically hidden. So lets mark it as hidden when
184 * such a file is created.
186 const char *start = basename((char*)filename);
187 if (*start == '.' && make_hidden(filename))
188 warning("Could not mark '%s' as hidden.", filename);
190 return fd;
193 #undef fopen
194 FILE *mingw_fopen (const char *filename, const char *otype)
196 int hide = 0;
197 FILE *file;
198 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
199 basename((char*)filename)[0] == '.')
200 hide = access(filename, F_OK);
201 if (!strcmp(filename, "/dev/null"))
202 filename = "nul";
203 file = fopen(filename, otype);
204 if (file && hide && make_hidden(filename))
205 warning("Could not mark '%s' as hidden.", filename);
206 return file;
209 #undef freopen
210 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
212 int hide = 0;
213 FILE *file;
214 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
215 basename((char*)filename)[0] == '.')
216 hide = access(filename, F_OK);
217 if (filename && !strcmp(filename, "/dev/null"))
218 filename = "nul";
219 file = freopen(filename, otype, stream);
220 if (file && hide && make_hidden(filename))
221 warning("Could not mark '%s' as hidden.", filename);
222 return file;
226 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
227 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
229 static inline long long filetime_to_hnsec(const FILETIME *ft)
231 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
232 /* Windows to Unix Epoch conversion */
233 return winTime - 116444736000000000LL;
236 static inline time_t filetime_to_time_t(const FILETIME *ft)
238 return (time_t)(filetime_to_hnsec(ft) / 10000000);
241 /* We keep the do_lstat code in a separate function to avoid recursion.
242 * When a path ends with a slash, the stat will fail with ENOENT. In
243 * this case, we strip the trailing slashes and stat again.
245 static int do_lstat(const char *file_name, struct stat *buf)
247 WIN32_FILE_ATTRIBUTE_DATA fdata;
249 if (!(errno = get_file_attr(file_name, &fdata))) {
250 buf->st_ino = 0;
251 buf->st_gid = 0;
252 buf->st_uid = 0;
253 buf->st_nlink = 1;
254 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
255 buf->st_size = fdata.nFileSizeLow |
256 (((off_t)fdata.nFileSizeHigh)<<32);
257 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
258 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
259 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
260 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
261 return 0;
263 return -1;
266 /* We provide our own lstat/fstat functions, since the provided
267 * lstat/fstat functions are so slow. These stat functions are
268 * tailored for Git's usage (read: fast), and are not meant to be
269 * complete. Note that Git stat()s are redirected to mingw_lstat()
270 * too, since Windows doesn't really handle symlinks that well.
272 int mingw_lstat(const char *file_name, struct stat *buf)
274 int namelen;
275 static char alt_name[PATH_MAX];
277 if (!do_lstat(file_name, buf))
278 return 0;
280 /* if file_name ended in a '/', Windows returned ENOENT;
281 * try again without trailing slashes
283 if (errno != ENOENT)
284 return -1;
286 namelen = strlen(file_name);
287 if (namelen && file_name[namelen-1] != '/')
288 return -1;
289 while (namelen && file_name[namelen-1] == '/')
290 --namelen;
291 if (!namelen || namelen >= PATH_MAX)
292 return -1;
294 memcpy(alt_name, file_name, namelen);
295 alt_name[namelen] = 0;
296 return do_lstat(alt_name, buf);
299 #undef fstat
300 int mingw_fstat(int fd, struct stat *buf)
302 HANDLE fh = (HANDLE)_get_osfhandle(fd);
303 BY_HANDLE_FILE_INFORMATION fdata;
305 if (fh == INVALID_HANDLE_VALUE) {
306 errno = EBADF;
307 return -1;
309 /* direct non-file handles to MS's fstat() */
310 if (GetFileType(fh) != FILE_TYPE_DISK)
311 return _fstati64(fd, buf);
313 if (GetFileInformationByHandle(fh, &fdata)) {
314 buf->st_ino = 0;
315 buf->st_gid = 0;
316 buf->st_uid = 0;
317 buf->st_nlink = 1;
318 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
319 buf->st_size = fdata.nFileSizeLow |
320 (((off_t)fdata.nFileSizeHigh)<<32);
321 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
322 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
323 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
324 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
325 return 0;
327 errno = EBADF;
328 return -1;
331 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
333 long long winTime = t * 10000000LL + 116444736000000000LL;
334 ft->dwLowDateTime = winTime;
335 ft->dwHighDateTime = winTime >> 32;
338 int mingw_utime (const char *file_name, const struct utimbuf *times)
340 FILETIME mft, aft;
341 int fh, rc;
343 /* must have write permission */
344 DWORD attrs = GetFileAttributes(file_name);
345 if (attrs != INVALID_FILE_ATTRIBUTES &&
346 (attrs & FILE_ATTRIBUTE_READONLY)) {
347 /* ignore errors here; open() will report them */
348 SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
351 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
352 rc = -1;
353 goto revert_attrs;
356 time_t_to_filetime(times->modtime, &mft);
357 time_t_to_filetime(times->actime, &aft);
358 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
359 errno = EINVAL;
360 rc = -1;
361 } else
362 rc = 0;
363 close(fh);
365 revert_attrs:
366 if (attrs != INVALID_FILE_ATTRIBUTES &&
367 (attrs & FILE_ATTRIBUTE_READONLY)) {
368 /* ignore errors again */
369 SetFileAttributes(file_name, attrs);
371 return rc;
374 unsigned int sleep (unsigned int seconds)
376 Sleep(seconds*1000);
377 return 0;
380 int mkstemp(char *template)
382 char *filename = mktemp(template);
383 if (filename == NULL)
384 return -1;
385 return open(filename, O_RDWR | O_CREAT, 0600);
388 int gettimeofday(struct timeval *tv, void *tz)
390 FILETIME ft;
391 long long hnsec;
393 GetSystemTimeAsFileTime(&ft);
394 hnsec = filetime_to_hnsec(&ft);
395 tv->tv_sec = hnsec / 10000000;
396 tv->tv_usec = (hnsec % 10000000) / 10;
397 return 0;
400 int pipe(int filedes[2])
402 HANDLE h[2];
404 /* this creates non-inheritable handles */
405 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
406 errno = err_win_to_posix(GetLastError());
407 return -1;
409 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
410 if (filedes[0] < 0) {
411 CloseHandle(h[0]);
412 CloseHandle(h[1]);
413 return -1;
415 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
416 if (filedes[0] < 0) {
417 close(filedes[0]);
418 CloseHandle(h[1]);
419 return -1;
421 return 0;
424 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
426 int i, pending;
428 if (timeout >= 0) {
429 if (nfds == 0) {
430 Sleep(timeout);
431 return 0;
433 return errno = EINVAL, error("poll timeout not supported");
436 /* When there is only one fd to wait for, then we pretend that
437 * input is available and let the actual wait happen when the
438 * caller invokes read().
440 if (nfds == 1) {
441 if (!(ufds[0].events & POLLIN))
442 return errno = EINVAL, error("POLLIN not set");
443 ufds[0].revents = POLLIN;
444 return 0;
447 repeat:
448 pending = 0;
449 for (i = 0; i < nfds; i++) {
450 DWORD avail = 0;
451 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
452 if (h == INVALID_HANDLE_VALUE)
453 return -1; /* errno was set */
455 if (!(ufds[i].events & POLLIN))
456 return errno = EINVAL, error("POLLIN not set");
458 /* this emulation works only for pipes */
459 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
460 int err = GetLastError();
461 if (err == ERROR_BROKEN_PIPE) {
462 ufds[i].revents = POLLHUP;
463 pending++;
464 } else {
465 errno = EINVAL;
466 return error("PeekNamedPipe failed,"
467 " GetLastError: %u", err);
469 } else if (avail) {
470 ufds[i].revents = POLLIN;
471 pending++;
472 } else
473 ufds[i].revents = 0;
475 if (!pending) {
476 /* The only times that we spin here is when the process
477 * that is connected through the pipes is waiting for
478 * its own input data to become available. But since
479 * the process (pack-objects) is itself CPU intensive,
480 * it will happily pick up the time slice that we are
481 * relinquishing here.
483 Sleep(0);
484 goto repeat;
486 return 0;
489 struct tm *gmtime_r(const time_t *timep, struct tm *result)
491 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
492 memcpy(result, gmtime(timep), sizeof(struct tm));
493 return result;
496 struct tm *localtime_r(const time_t *timep, struct tm *result)
498 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
499 memcpy(result, localtime(timep), sizeof(struct tm));
500 return result;
503 #undef getcwd
504 char *mingw_getcwd(char *pointer, int len)
506 int i;
507 char *ret = getcwd(pointer, len);
508 if (!ret)
509 return ret;
510 for (i = 0; pointer[i]; i++)
511 if (pointer[i] == '\\')
512 pointer[i] = '/';
513 return ret;
516 #undef getenv
517 char *mingw_getenv(const char *name)
519 char *result = getenv(name);
520 if (!result && !strcmp(name, "TMPDIR")) {
521 /* on Windows it is TMP and TEMP */
522 result = getenv("TMP");
523 if (!result)
524 result = getenv("TEMP");
526 return result;
530 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
531 * (Parsing C++ Command-Line Arguments)
533 static const char *quote_arg(const char *arg)
535 /* count chars to quote */
536 int len = 0, n = 0;
537 int force_quotes = 0;
538 char *q, *d;
539 const char *p = arg;
540 if (!*p) force_quotes = 1;
541 while (*p) {
542 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
543 force_quotes = 1;
544 else if (*p == '"')
545 n++;
546 else if (*p == '\\') {
547 int count = 0;
548 while (*p == '\\') {
549 count++;
550 p++;
551 len++;
553 if (*p == '"')
554 n += count*2 + 1;
555 continue;
557 len++;
558 p++;
560 if (!force_quotes && n == 0)
561 return arg;
563 /* insert \ where necessary */
564 d = q = xmalloc(len+n+3);
565 *d++ = '"';
566 while (*arg) {
567 if (*arg == '"')
568 *d++ = '\\';
569 else if (*arg == '\\') {
570 int count = 0;
571 while (*arg == '\\') {
572 count++;
573 *d++ = *arg++;
575 if (*arg == '"') {
576 while (count-- > 0)
577 *d++ = '\\';
578 *d++ = '\\';
581 *d++ = *arg++;
583 *d++ = '"';
584 *d++ = 0;
585 return q;
588 static const char *parse_interpreter(const char *cmd)
590 static char buf[100];
591 char *p, *opt;
592 int n, fd;
594 /* don't even try a .exe */
595 n = strlen(cmd);
596 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
597 return NULL;
599 fd = open(cmd, O_RDONLY);
600 if (fd < 0)
601 return NULL;
602 n = read(fd, buf, sizeof(buf)-1);
603 close(fd);
604 if (n < 4) /* at least '#!/x' and not error */
605 return NULL;
607 if (buf[0] != '#' || buf[1] != '!')
608 return NULL;
609 buf[n] = '\0';
610 p = buf + strcspn(buf, "\r\n");
611 if (!*p)
612 return NULL;
614 *p = '\0';
615 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
616 return NULL;
617 /* strip options */
618 if ((opt = strchr(p+1, ' ')))
619 *opt = '\0';
620 return p+1;
624 * Splits the PATH into parts.
626 static char **get_path_split(void)
628 char *p, **path, *envpath = getenv("PATH");
629 int i, n = 0;
631 if (!envpath || !*envpath)
632 return NULL;
634 envpath = xstrdup(envpath);
635 p = envpath;
636 while (p) {
637 char *dir = p;
638 p = strchr(p, ';');
639 if (p) *p++ = '\0';
640 if (*dir) { /* not earlier, catches series of ; */
641 ++n;
644 if (!n)
645 return NULL;
647 path = xmalloc((n+1)*sizeof(char *));
648 p = envpath;
649 i = 0;
650 do {
651 if (*p)
652 path[i++] = xstrdup(p);
653 p = p+strlen(p)+1;
654 } while (i < n);
655 path[i] = NULL;
657 free(envpath);
659 return path;
662 static void free_path_split(char **path)
664 char **p = path;
666 if (!path)
667 return;
669 while (*p)
670 free(*p++);
671 free(path);
675 * exe_only means that we only want to detect .exe files, but not scripts
676 * (which do not have an extension)
678 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
680 char path[MAX_PATH];
681 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
683 if (!isexe && access(path, F_OK) == 0)
684 return xstrdup(path);
685 path[strlen(path)-4] = '\0';
686 if ((!exe_only || isexe) && access(path, F_OK) == 0)
687 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
688 return xstrdup(path);
689 return NULL;
693 * Determines the absolute path of cmd using the the split path in path.
694 * If cmd contains a slash or backslash, no lookup is performed.
696 static char *path_lookup(const char *cmd, char **path, int exe_only)
698 char *prog = NULL;
699 int len = strlen(cmd);
700 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
702 if (strchr(cmd, '/') || strchr(cmd, '\\'))
703 prog = xstrdup(cmd);
705 while (!prog && *path)
706 prog = lookup_prog(*path++, cmd, isexe, exe_only);
708 return prog;
711 static int env_compare(const void *a, const void *b)
713 char *const *ea = a;
714 char *const *eb = b;
715 return strcasecmp(*ea, *eb);
718 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
719 int prepend_cmd, int fhin, int fhout, int fherr)
721 STARTUPINFO si;
722 PROCESS_INFORMATION pi;
723 struct strbuf envblk, args;
724 unsigned flags;
725 BOOL ret;
727 /* Determine whether or not we are associated to a console */
728 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
729 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
730 FILE_ATTRIBUTE_NORMAL, NULL);
731 if (cons == INVALID_HANDLE_VALUE) {
732 /* There is no console associated with this process.
733 * Since the child is a console process, Windows
734 * would normally create a console window. But
735 * since we'll be redirecting std streams, we do
736 * not need the console.
737 * It is necessary to use DETACHED_PROCESS
738 * instead of CREATE_NO_WINDOW to make ssh
739 * recognize that it has no console.
741 flags = DETACHED_PROCESS;
742 } else {
743 /* There is already a console. If we specified
744 * DETACHED_PROCESS here, too, Windows would
745 * disassociate the child from the console.
746 * The same is true for CREATE_NO_WINDOW.
747 * Go figure!
749 flags = 0;
750 CloseHandle(cons);
752 memset(&si, 0, sizeof(si));
753 si.cb = sizeof(si);
754 si.dwFlags = STARTF_USESTDHANDLES;
755 si.hStdInput = (HANDLE) _get_osfhandle(fhin);
756 si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
757 si.hStdError = (HANDLE) _get_osfhandle(fherr);
759 /* concatenate argv, quoting args as we go */
760 strbuf_init(&args, 0);
761 if (prepend_cmd) {
762 char *quoted = (char *)quote_arg(cmd);
763 strbuf_addstr(&args, quoted);
764 if (quoted != cmd)
765 free(quoted);
767 for (; *argv; argv++) {
768 char *quoted = (char *)quote_arg(*argv);
769 if (*args.buf)
770 strbuf_addch(&args, ' ');
771 strbuf_addstr(&args, quoted);
772 if (quoted != *argv)
773 free(quoted);
776 if (env) {
777 int count = 0;
778 char **e, **sorted_env;
780 for (e = env; *e; e++)
781 count++;
783 /* environment must be sorted */
784 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
785 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
786 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
788 strbuf_init(&envblk, 0);
789 for (e = sorted_env; *e; e++) {
790 strbuf_addstr(&envblk, *e);
791 strbuf_addch(&envblk, '\0');
793 free(sorted_env);
796 memset(&pi, 0, sizeof(pi));
797 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
798 env ? envblk.buf : NULL, NULL, &si, &pi);
800 if (env)
801 strbuf_release(&envblk);
802 strbuf_release(&args);
804 if (!ret) {
805 errno = ENOENT;
806 return -1;
808 CloseHandle(pi.hThread);
809 return (pid_t)pi.hProcess;
812 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
813 int prepend_cmd)
815 return mingw_spawnve_fd(cmd, argv, env, prepend_cmd, 0, 1, 2);
818 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
819 int fhin, int fhout, int fherr)
821 pid_t pid;
822 char **path = get_path_split();
823 char *prog = path_lookup(cmd, path, 0);
825 if (!prog) {
826 errno = ENOENT;
827 pid = -1;
829 else {
830 const char *interpr = parse_interpreter(prog);
832 if (interpr) {
833 const char *argv0 = argv[0];
834 char *iprog = path_lookup(interpr, path, 1);
835 argv[0] = prog;
836 if (!iprog) {
837 errno = ENOENT;
838 pid = -1;
840 else {
841 pid = mingw_spawnve_fd(iprog, argv, env, 1,
842 fhin, fhout, fherr);
843 free(iprog);
845 argv[0] = argv0;
847 else
848 pid = mingw_spawnve_fd(prog, argv, env, 0,
849 fhin, fhout, fherr);
850 free(prog);
852 free_path_split(path);
853 return pid;
856 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
858 const char *interpr = parse_interpreter(cmd);
859 char **path;
860 char *prog;
861 int pid = 0;
863 if (!interpr)
864 return 0;
865 path = get_path_split();
866 prog = path_lookup(interpr, path, 1);
867 if (prog) {
868 int argc = 0;
869 const char **argv2;
870 while (argv[argc]) argc++;
871 argv2 = xmalloc(sizeof(*argv) * (argc+1));
872 argv2[0] = (char *)cmd; /* full path to the script file */
873 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
874 pid = mingw_spawnve(prog, argv2, env, 1);
875 if (pid >= 0) {
876 int status;
877 if (waitpid(pid, &status, 0) < 0)
878 status = 255;
879 exit(status);
881 pid = 1; /* indicate that we tried but failed */
882 free(prog);
883 free(argv2);
885 free_path_split(path);
886 return pid;
889 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
891 /* check if git_command is a shell script */
892 if (!try_shell_exec(cmd, argv, (char **)env)) {
893 int pid, status;
895 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
896 if (pid < 0)
897 return;
898 if (waitpid(pid, &status, 0) < 0)
899 status = 255;
900 exit(status);
904 void mingw_execvp(const char *cmd, char *const *argv)
906 char **path = get_path_split();
907 char *prog = path_lookup(cmd, path, 0);
909 if (prog) {
910 mingw_execve(prog, argv, environ);
911 free(prog);
912 } else
913 errno = ENOENT;
915 free_path_split(path);
918 static char **copy_environ(void)
920 char **env;
921 int i = 0;
922 while (environ[i])
923 i++;
924 env = xmalloc((i+1)*sizeof(*env));
925 for (i = 0; environ[i]; i++)
926 env[i] = xstrdup(environ[i]);
927 env[i] = NULL;
928 return env;
931 void free_environ(char **env)
933 int i;
934 for (i = 0; env[i]; i++)
935 free(env[i]);
936 free(env);
939 static int lookup_env(char **env, const char *name, size_t nmln)
941 int i;
943 for (i = 0; env[i]; i++) {
944 if (0 == strncmp(env[i], name, nmln)
945 && '=' == env[i][nmln])
946 /* matches */
947 return i;
949 return -1;
953 * If name contains '=', then sets the variable, otherwise it unsets it
955 static char **env_setenv(char **env, const char *name)
957 char *eq = strchrnul(name, '=');
958 int i = lookup_env(env, name, eq-name);
960 if (i < 0) {
961 if (*eq) {
962 for (i = 0; env[i]; i++)
964 env = xrealloc(env, (i+2)*sizeof(*env));
965 env[i] = xstrdup(name);
966 env[i+1] = NULL;
969 else {
970 free(env[i]);
971 if (*eq)
972 env[i] = xstrdup(name);
973 else
974 for (; env[i]; i++)
975 env[i] = env[i+1];
977 return env;
981 * Copies global environ and adjusts variables as specified by vars.
983 char **make_augmented_environ(const char *const *vars)
985 char **env = copy_environ();
987 while (*vars)
988 env = env_setenv(env, *vars++);
989 return env;
993 * Note, this isn't a complete replacement for getaddrinfo. It assumes
994 * that service contains a numerical port, or that it it is null. It
995 * does a simple search using gethostbyname, and returns one IPv4 host
996 * if one was found.
998 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
999 const struct addrinfo *hints,
1000 struct addrinfo **res)
1002 struct hostent *h = gethostbyname(node);
1003 struct addrinfo *ai;
1004 struct sockaddr_in *sin;
1006 if (!h)
1007 return WSAGetLastError();
1009 ai = xmalloc(sizeof(struct addrinfo));
1010 *res = ai;
1011 ai->ai_flags = 0;
1012 ai->ai_family = AF_INET;
1013 ai->ai_socktype = hints->ai_socktype;
1014 switch (hints->ai_socktype) {
1015 case SOCK_STREAM:
1016 ai->ai_protocol = IPPROTO_TCP;
1017 break;
1018 case SOCK_DGRAM:
1019 ai->ai_protocol = IPPROTO_UDP;
1020 break;
1021 default:
1022 ai->ai_protocol = 0;
1023 break;
1025 ai->ai_addrlen = sizeof(struct sockaddr_in);
1026 ai->ai_canonname = strdup(h->h_name);
1028 sin = xmalloc(ai->ai_addrlen);
1029 memset(sin, 0, ai->ai_addrlen);
1030 sin->sin_family = AF_INET;
1031 if (service)
1032 sin->sin_port = htons(atoi(service));
1033 sin->sin_addr = *(struct in_addr *)h->h_addr;
1034 ai->ai_addr = (struct sockaddr *)sin;
1035 ai->ai_next = 0;
1036 return 0;
1039 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1041 free(res->ai_canonname);
1042 free(res->ai_addr);
1043 free(res);
1046 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1047 char *host, DWORD hostlen,
1048 char *serv, DWORD servlen, int flags)
1050 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1051 if (sa->sa_family != AF_INET)
1052 return EAI_FAMILY;
1053 if (!host && !serv)
1054 return EAI_NONAME;
1056 if (host && hostlen > 0) {
1057 struct hostent *ent = NULL;
1058 if (!(flags & NI_NUMERICHOST))
1059 ent = gethostbyaddr((const char *)&sin->sin_addr,
1060 sizeof(sin->sin_addr), AF_INET);
1062 if (ent)
1063 snprintf(host, hostlen, "%s", ent->h_name);
1064 else if (flags & NI_NAMEREQD)
1065 return EAI_NONAME;
1066 else
1067 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1070 if (serv && servlen > 0) {
1071 struct servent *ent = NULL;
1072 if (!(flags & NI_NUMERICSERV))
1073 ent = getservbyport(sin->sin_port,
1074 flags & NI_DGRAM ? "udp" : "tcp");
1076 if (ent)
1077 snprintf(serv, servlen, "%s", ent->s_name);
1078 else
1079 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1082 return 0;
1085 static HMODULE ipv6_dll = NULL;
1086 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1087 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1088 const struct addrinfo *hints,
1089 struct addrinfo **res);
1090 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1091 char *host, DWORD hostlen,
1092 char *serv, DWORD servlen, int flags);
1094 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1095 * don't need to try to load that one dynamically.
1098 static void socket_cleanup(void)
1100 WSACleanup();
1101 if (ipv6_dll)
1102 FreeLibrary(ipv6_dll);
1103 ipv6_dll = NULL;
1104 ipv6_freeaddrinfo = freeaddrinfo_stub;
1105 ipv6_getaddrinfo = getaddrinfo_stub;
1106 ipv6_getnameinfo = getnameinfo_stub;
1109 static void ensure_socket_initialization(void)
1111 WSADATA wsa;
1112 static int initialized = 0;
1113 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1114 const char **name;
1116 if (initialized)
1117 return;
1119 if (WSAStartup(MAKEWORD(2,2), &wsa))
1120 die("unable to initialize winsock subsystem, error %d",
1121 WSAGetLastError());
1123 for (name = libraries; *name; name++) {
1124 ipv6_dll = LoadLibrary(*name);
1125 if (!ipv6_dll)
1126 continue;
1128 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1129 GetProcAddress(ipv6_dll, "freeaddrinfo");
1130 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1131 const struct addrinfo *,
1132 struct addrinfo **))
1133 GetProcAddress(ipv6_dll, "getaddrinfo");
1134 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1135 socklen_t, char *, DWORD,
1136 char *, DWORD, int))
1137 GetProcAddress(ipv6_dll, "getnameinfo");
1138 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1139 FreeLibrary(ipv6_dll);
1140 ipv6_dll = NULL;
1141 } else
1142 break;
1144 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1145 ipv6_freeaddrinfo = freeaddrinfo_stub;
1146 ipv6_getaddrinfo = getaddrinfo_stub;
1147 ipv6_getnameinfo = getnameinfo_stub;
1150 atexit(socket_cleanup);
1151 initialized = 1;
1154 #undef gethostbyname
1155 struct hostent *mingw_gethostbyname(const char *host)
1157 ensure_socket_initialization();
1158 return gethostbyname(host);
1161 void mingw_freeaddrinfo(struct addrinfo *res)
1163 ipv6_freeaddrinfo(res);
1166 int mingw_getaddrinfo(const char *node, const char *service,
1167 const struct addrinfo *hints, struct addrinfo **res)
1169 ensure_socket_initialization();
1170 return ipv6_getaddrinfo(node, service, hints, res);
1173 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1174 char *host, DWORD hostlen, char *serv, DWORD servlen,
1175 int flags)
1177 ensure_socket_initialization();
1178 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1181 int mingw_socket(int domain, int type, int protocol)
1183 int sockfd;
1184 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
1185 if (s == INVALID_SOCKET) {
1187 * WSAGetLastError() values are regular BSD error codes
1188 * biased by WSABASEERR.
1189 * However, strerror() does not know about networking
1190 * specific errors, which are values beginning at 38 or so.
1191 * Therefore, we choose to leave the biased error code
1192 * in errno so that _if_ someone looks up the code somewhere,
1193 * then it is at least the number that are usually listed.
1195 errno = WSAGetLastError();
1196 return -1;
1198 /* convert into a file descriptor */
1199 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1200 closesocket(s);
1201 return error("unable to make a socket file descriptor: %s",
1202 strerror(errno));
1204 return sockfd;
1207 #undef connect
1208 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1210 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1211 return connect(s, sa, sz);
1214 #undef rename
1215 int mingw_rename(const char *pold, const char *pnew)
1217 DWORD attrs, gle;
1218 int tries = 0;
1219 static const int delay[] = { 0, 1, 10, 20, 40 };
1222 * Try native rename() first to get errno right.
1223 * It is based on MoveFile(), which cannot overwrite existing files.
1225 if (!rename(pold, pnew))
1226 return 0;
1227 if (errno != EEXIST)
1228 return -1;
1229 repeat:
1230 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1231 return 0;
1232 /* TODO: translate more errors */
1233 gle = GetLastError();
1234 if (gle == ERROR_ACCESS_DENIED &&
1235 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1236 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1237 errno = EISDIR;
1238 return -1;
1240 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1241 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1242 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1243 return 0;
1244 gle = GetLastError();
1245 /* revert file attributes on failure */
1246 SetFileAttributes(pnew, attrs);
1249 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1251 * We assume that some other process had the source or
1252 * destination file open at the wrong moment and retry.
1253 * In order to give the other process a higher chance to
1254 * complete its operation, we give up our time slice now.
1255 * If we have to retry again, we do sleep a bit.
1257 Sleep(delay[tries]);
1258 tries++;
1259 goto repeat;
1261 errno = EACCES;
1262 return -1;
1266 * Note that this doesn't return the actual pagesize, but
1267 * the allocation granularity. If future Windows specific git code
1268 * needs the real getpagesize function, we need to find another solution.
1270 int mingw_getpagesize(void)
1272 SYSTEM_INFO si;
1273 GetSystemInfo(&si);
1274 return si.dwAllocationGranularity;
1277 struct passwd *getpwuid(int uid)
1279 static char user_name[100];
1280 static struct passwd p;
1282 DWORD len = sizeof(user_name);
1283 if (!GetUserName(user_name, &len))
1284 return NULL;
1285 p.pw_name = user_name;
1286 p.pw_gecos = "unknown";
1287 p.pw_dir = NULL;
1288 return &p;
1291 static HANDLE timer_event;
1292 static HANDLE timer_thread;
1293 static int timer_interval;
1294 static int one_shot;
1295 static sig_handler_t timer_fn = SIG_DFL;
1297 /* The timer works like this:
1298 * The thread, ticktack(), is a trivial routine that most of the time
1299 * only waits to receive the signal to terminate. The main thread tells
1300 * the thread to terminate by setting the timer_event to the signalled
1301 * state.
1302 * But ticktack() interrupts the wait state after the timer's interval
1303 * length to call the signal handler.
1306 static unsigned __stdcall ticktack(void *dummy)
1308 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1309 if (timer_fn == SIG_DFL)
1310 die("Alarm");
1311 if (timer_fn != SIG_IGN)
1312 timer_fn(SIGALRM);
1313 if (one_shot)
1314 break;
1316 return 0;
1319 static int start_timer_thread(void)
1321 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1322 if (timer_event) {
1323 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1324 if (!timer_thread )
1325 return errno = ENOMEM,
1326 error("cannot start timer thread");
1327 } else
1328 return errno = ENOMEM,
1329 error("cannot allocate resources for timer");
1330 return 0;
1333 static void stop_timer_thread(void)
1335 if (timer_event)
1336 SetEvent(timer_event); /* tell thread to terminate */
1337 if (timer_thread) {
1338 int rc = WaitForSingleObject(timer_thread, 1000);
1339 if (rc == WAIT_TIMEOUT)
1340 error("timer thread did not terminate timely");
1341 else if (rc != WAIT_OBJECT_0)
1342 error("waiting for timer thread failed: %lu",
1343 GetLastError());
1344 CloseHandle(timer_thread);
1346 if (timer_event)
1347 CloseHandle(timer_event);
1348 timer_event = NULL;
1349 timer_thread = NULL;
1352 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1354 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1357 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1359 static const struct timeval zero;
1360 static int atexit_done;
1362 if (out != NULL)
1363 return errno = EINVAL,
1364 error("setitimer param 3 != NULL not implemented");
1365 if (!is_timeval_eq(&in->it_interval, &zero) &&
1366 !is_timeval_eq(&in->it_interval, &in->it_value))
1367 return errno = EINVAL,
1368 error("setitimer: it_interval must be zero or eq it_value");
1370 if (timer_thread)
1371 stop_timer_thread();
1373 if (is_timeval_eq(&in->it_value, &zero) &&
1374 is_timeval_eq(&in->it_interval, &zero))
1375 return 0;
1377 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1378 one_shot = is_timeval_eq(&in->it_interval, &zero);
1379 if (!atexit_done) {
1380 atexit(stop_timer_thread);
1381 atexit_done = 1;
1383 return start_timer_thread();
1386 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1388 if (sig != SIGALRM)
1389 return errno = EINVAL,
1390 error("sigaction only implemented for SIGALRM");
1391 if (out != NULL)
1392 return errno = EINVAL,
1393 error("sigaction: param 3 != NULL not implemented");
1395 timer_fn = in->sa_handler;
1396 return 0;
1399 #undef signal
1400 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1402 sig_handler_t old = timer_fn;
1403 if (sig != SIGALRM)
1404 return signal(sig, handler);
1405 timer_fn = handler;
1406 return old;
1409 static const char *make_backslash_path(const char *path)
1411 static char buf[PATH_MAX + 1];
1412 char *c;
1414 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1415 die("Too long path: %.*s", 60, path);
1417 for (c = buf; *c; c++) {
1418 if (*c == '/')
1419 *c = '\\';
1421 return buf;
1424 void mingw_open_html(const char *unixpath)
1426 const char *htmlpath = make_backslash_path(unixpath);
1427 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1428 const char *, const char *, const char *, INT);
1429 T ShellExecute;
1430 HMODULE shell32;
1432 shell32 = LoadLibrary("shell32.dll");
1433 if (!shell32)
1434 die("cannot load shell32.dll");
1435 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1436 if (!ShellExecute)
1437 die("cannot run browser");
1439 printf("Launching default browser to display HTML ...\n");
1440 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);
1442 FreeLibrary(shell32);
1445 int link(const char *oldpath, const char *newpath)
1447 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1448 static T create_hard_link = NULL;
1449 if (!create_hard_link) {
1450 create_hard_link = (T) GetProcAddress(
1451 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1452 if (!create_hard_link)
1453 create_hard_link = (T)-1;
1455 if (create_hard_link == (T)-1) {
1456 errno = ENOSYS;
1457 return -1;
1459 if (!create_hard_link(newpath, oldpath, NULL)) {
1460 errno = err_win_to_posix(GetLastError());
1461 return -1;
1463 return 0;
1466 char *getpass(const char *prompt)
1468 struct strbuf buf = STRBUF_INIT;
1470 fputs(prompt, stderr);
1471 for (;;) {
1472 char c = _getch();
1473 if (c == '\r' || c == '\n')
1474 break;
1475 strbuf_addch(&buf, c);
1477 fputs("\n", stderr);
1478 return strbuf_detach(&buf, NULL);
1481 #ifndef NO_MINGW_REPLACE_READDIR
1482 /* MinGW readdir implementation to avoid extra lstats for Git */
1483 struct mingw_DIR
1485 struct _finddata_t dd_dta; /* disk transfer area for this dir */
1486 struct mingw_dirent dd_dir; /* Our own implementation, including d_type */
1487 long dd_handle; /* _findnext handle */
1488 int dd_stat; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1489 char dd_name[1]; /* given path for dir with search pattern (struct is extended) */
1492 struct dirent *mingw_readdir(DIR *dir)
1494 WIN32_FIND_DATAA buf;
1495 HANDLE handle;
1496 struct mingw_DIR *mdir = (struct mingw_DIR*)dir;
1498 if (!dir->dd_handle) {
1499 errno = EBADF; /* No set_errno for mingw */
1500 return NULL;
1503 if (dir->dd_handle == (long)INVALID_HANDLE_VALUE && dir->dd_stat == 0)
1505 DWORD lasterr;
1506 handle = FindFirstFileA(dir->dd_name, &buf);
1507 lasterr = GetLastError();
1508 dir->dd_handle = (long)handle;
1509 if (handle == INVALID_HANDLE_VALUE && (lasterr != ERROR_NO_MORE_FILES)) {
1510 errno = err_win_to_posix(lasterr);
1511 return NULL;
1513 } else if (dir->dd_handle == (long)INVALID_HANDLE_VALUE) {
1514 return NULL;
1515 } else if (!FindNextFileA((HANDLE)dir->dd_handle, &buf)) {
1516 DWORD lasterr = GetLastError();
1517 FindClose((HANDLE)dir->dd_handle);
1518 dir->dd_handle = (long)INVALID_HANDLE_VALUE;
1519 /* POSIX says you shouldn't set errno when readdir can't
1520 find any more files; so, if another error we leave it set. */
1521 if (lasterr != ERROR_NO_MORE_FILES)
1522 errno = err_win_to_posix(lasterr);
1523 return NULL;
1526 /* We get here if `buf' contains valid data. */
1527 strcpy(dir->dd_dir.d_name, buf.cFileName);
1528 ++dir->dd_stat;
1530 /* Set file type, based on WIN32_FIND_DATA */
1531 mdir->dd_dir.d_type = 0;
1532 if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1533 mdir->dd_dir.d_type |= DT_DIR;
1534 else
1535 mdir->dd_dir.d_type |= DT_REG;
1537 return (struct dirent*)&dir->dd_dir;
1539 #endif // !NO_MINGW_REPLACE_READDIR