core.hidedotfiles: hide '.git' dir by default
[git/dscho.git] / compat / mingw.c
blob34baee3115efdc274a1ff6fbb27217ccb08d12be
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include "../strbuf.h"
5 #include "../cache.h"
7 unsigned int _CRT_fmode = _O_BINARY;
9 int err_win_to_posix(DWORD winerr)
11 int error = ENOSYS;
12 switch(winerr) {
13 case ERROR_ACCESS_DENIED: error = EACCES; break;
14 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
15 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
16 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
17 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
18 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
19 case ERROR_BAD_COMMAND: error = EIO; break;
20 case ERROR_BAD_DEVICE: error = ENODEV; break;
21 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
22 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
23 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
24 case ERROR_BAD_LENGTH: error = EINVAL; break;
25 case ERROR_BAD_PATHNAME: error = ENOENT; break;
26 case ERROR_BAD_PIPE: error = EPIPE; break;
27 case ERROR_BAD_UNIT: error = ENODEV; break;
28 case ERROR_BAD_USERNAME: error = EINVAL; break;
29 case ERROR_BROKEN_PIPE: error = EPIPE; break;
30 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
31 case ERROR_BUSY: error = EBUSY; break;
32 case ERROR_BUSY_DRIVE: error = EBUSY; break;
33 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
34 case ERROR_CANNOT_MAKE: error = EACCES; break;
35 case ERROR_CANTOPEN: error = EIO; break;
36 case ERROR_CANTREAD: error = EIO; break;
37 case ERROR_CANTWRITE: error = EIO; break;
38 case ERROR_CRC: error = EIO; break;
39 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
40 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
41 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
42 case ERROR_DIRECTORY: error = EINVAL; break;
43 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
44 case ERROR_DISK_CHANGE: error = EIO; break;
45 case ERROR_DISK_FULL: error = ENOSPC; break;
46 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
47 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
48 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
49 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
50 case ERROR_FILE_EXISTS: error = EEXIST; break;
51 case ERROR_FILE_INVALID: error = ENODEV; break;
52 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
53 case ERROR_GEN_FAILURE: error = EIO; break;
54 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
55 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
56 case ERROR_INVALID_ACCESS: error = EACCES; break;
57 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
58 case ERROR_INVALID_BLOCK: error = EFAULT; break;
59 case ERROR_INVALID_DATA: error = EINVAL; break;
60 case ERROR_INVALID_DRIVE: error = ENODEV; break;
61 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
62 case ERROR_INVALID_FLAGS: error = EINVAL; break;
63 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
64 case ERROR_INVALID_HANDLE: error = EBADF; break;
65 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
66 case ERROR_INVALID_NAME: error = EINVAL; break;
67 case ERROR_INVALID_OWNER: error = EINVAL; break;
68 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
69 case ERROR_INVALID_PASSWORD: error = EPERM; break;
70 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
71 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
72 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
73 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
74 case ERROR_IO_DEVICE: error = EIO; break;
75 case ERROR_IO_INCOMPLETE: error = EINTR; break;
76 case ERROR_LOCKED: error = EBUSY; break;
77 case ERROR_LOCK_VIOLATION: error = EACCES; break;
78 case ERROR_LOGON_FAILURE: error = EACCES; break;
79 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
80 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
81 case ERROR_MORE_DATA: error = EPIPE; break;
82 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
83 case ERROR_NOACCESS: error = EFAULT; break;
84 case ERROR_NONE_MAPPED: error = EINVAL; break;
85 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
86 case ERROR_NOT_READY: error = EAGAIN; break;
87 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
88 case ERROR_NO_DATA: error = EPIPE; break;
89 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
90 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
91 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
92 case ERROR_OPEN_FAILED: error = EIO; break;
93 case ERROR_OPEN_FILES: error = EBUSY; break;
94 case ERROR_OPERATION_ABORTED: error = EINTR; break;
95 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
96 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
97 case ERROR_PATH_BUSY: error = EBUSY; break;
98 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
99 case ERROR_PIPE_BUSY: error = EBUSY; break;
100 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
101 case ERROR_PIPE_LISTENING: error = EPIPE; break;
102 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
103 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
104 case ERROR_READ_FAULT: error = EIO; break;
105 case ERROR_SEEK: error = EIO; break;
106 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
107 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
108 case ERROR_SHARING_VIOLATION: error = EACCES; break;
109 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
110 case ERROR_SWAPERROR: error = ENOENT; break;
111 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
112 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
113 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
114 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
115 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
116 case ERROR_WRITE_FAULT: error = EIO; break;
117 case ERROR_WRITE_PROTECT: error = EROFS; break;
119 return error;
122 static int make_hidden(const char *path)
124 DWORD attribs = GetFileAttributes(path);
125 if (SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN | attribs))
126 return 0;
127 errno = err_win_to_posix(GetLastError());
128 return -1;
131 void mingw_mark_as_git_dir(const char *dir)
133 if (hide_dotfiles != HIDE_DOTFILES_FALSE && make_hidden(dir))
134 warning("Failed to make '%s' hidden", dir);
137 #undef mkdir
138 int mingw_mkdir(const char *path, int mode)
140 int ret = mkdir(path);
141 if (!ret && hide_dotfiles == HIDE_DOTFILES_TRUE) {
143 * In Windows a file or dir starting with a dot is not
144 * automatically hidden. So lets mark it as hidden when
145 * such a directory is created.
147 const char *start = basename((char*)path);
148 if (*start == '.')
149 return make_hidden(path);
151 return ret;
154 #undef open
155 int mingw_open (const char *filename, int oflags, ...)
157 va_list args;
158 unsigned mode;
159 int fd;
161 va_start(args, oflags);
162 mode = va_arg(args, int);
163 va_end(args);
165 if (!strcmp(filename, "/dev/null"))
166 filename = "nul";
168 fd = open(filename, oflags, mode);
170 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
171 DWORD attrs = GetFileAttributes(filename);
172 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
173 errno = EISDIR;
175 if ((oflags & O_CREAT) && fd >= 0 &&
176 hide_dotfiles == HIDE_DOTFILES_TRUE) {
178 * In Windows a file or dir starting with a dot is not
179 * automatically hidden. So lets mark it as hidden when
180 * such a file is created.
182 const char *start = basename((char*)filename);
183 if (*start == '.' && make_hidden(filename))
184 warning("Could not mark '%s' as hidden.", filename);
186 return fd;
189 #undef fopen
190 FILE *mingw_fopen (const char *filename, const char *otype)
192 int hide = 0;
193 FILE *file;
194 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
195 basename((char*)filename)[0] == '.')
196 hide = access(filename, F_OK);
197 if (!strcmp(filename, "/dev/null"))
198 filename = "nul";
199 file = fopen(filename, otype);
200 if (file && hide && make_hidden(filename))
201 warning("Could not mark '%s' as hidden.", filename);
202 return file;
205 #undef freopen
206 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
208 int hide = 0;
209 FILE *file;
210 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
211 basename((char*)filename)[0] == '.')
212 hide = access(filename, F_OK);
213 if (filename && !strcmp(filename, "/dev/null"))
214 filename = "nul";
215 file = freopen(filename, otype, stream);
216 if (file && hide && make_hidden(filename))
217 warning("Could not mark '%s' as hidden.", filename);
218 return file;
222 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
223 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
225 static inline long long filetime_to_hnsec(const FILETIME *ft)
227 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
228 /* Windows to Unix Epoch conversion */
229 return winTime - 116444736000000000LL;
232 static inline time_t filetime_to_time_t(const FILETIME *ft)
234 return (time_t)(filetime_to_hnsec(ft) / 10000000);
237 /* We keep the do_lstat code in a separate function to avoid recursion.
238 * When a path ends with a slash, the stat will fail with ENOENT. In
239 * this case, we strip the trailing slashes and stat again.
241 static int do_lstat(const char *file_name, struct stat *buf)
243 WIN32_FILE_ATTRIBUTE_DATA fdata;
245 if (!(errno = get_file_attr(file_name, &fdata))) {
246 buf->st_ino = 0;
247 buf->st_gid = 0;
248 buf->st_uid = 0;
249 buf->st_nlink = 1;
250 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
251 buf->st_size = fdata.nFileSizeLow |
252 (((off_t)fdata.nFileSizeHigh)<<32);
253 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
254 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
255 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
256 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
257 return 0;
259 return -1;
262 /* We provide our own lstat/fstat functions, since the provided
263 * lstat/fstat functions are so slow. These stat functions are
264 * tailored for Git's usage (read: fast), and are not meant to be
265 * complete. Note that Git stat()s are redirected to mingw_lstat()
266 * too, since Windows doesn't really handle symlinks that well.
268 int mingw_lstat(const char *file_name, struct stat *buf)
270 int namelen;
271 static char alt_name[PATH_MAX];
273 if (!do_lstat(file_name, buf))
274 return 0;
276 /* if file_name ended in a '/', Windows returned ENOENT;
277 * try again without trailing slashes
279 if (errno != ENOENT)
280 return -1;
282 namelen = strlen(file_name);
283 if (namelen && file_name[namelen-1] != '/')
284 return -1;
285 while (namelen && file_name[namelen-1] == '/')
286 --namelen;
287 if (!namelen || namelen >= PATH_MAX)
288 return -1;
290 memcpy(alt_name, file_name, namelen);
291 alt_name[namelen] = 0;
292 return do_lstat(alt_name, buf);
295 #undef fstat
296 int mingw_fstat(int fd, struct stat *buf)
298 HANDLE fh = (HANDLE)_get_osfhandle(fd);
299 BY_HANDLE_FILE_INFORMATION fdata;
301 if (fh == INVALID_HANDLE_VALUE) {
302 errno = EBADF;
303 return -1;
305 /* direct non-file handles to MS's fstat() */
306 if (GetFileType(fh) != FILE_TYPE_DISK)
307 return _fstati64(fd, buf);
309 if (GetFileInformationByHandle(fh, &fdata)) {
310 buf->st_ino = 0;
311 buf->st_gid = 0;
312 buf->st_uid = 0;
313 buf->st_nlink = 1;
314 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
315 buf->st_size = fdata.nFileSizeLow |
316 (((off_t)fdata.nFileSizeHigh)<<32);
317 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
318 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
319 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
320 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
321 return 0;
323 errno = EBADF;
324 return -1;
327 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
329 long long winTime = t * 10000000LL + 116444736000000000LL;
330 ft->dwLowDateTime = winTime;
331 ft->dwHighDateTime = winTime >> 32;
334 int mingw_utime (const char *file_name, const struct utimbuf *times)
336 FILETIME mft, aft;
337 int fh, rc;
339 /* must have write permission */
340 DWORD attrs = GetFileAttributes(file_name);
341 if (attrs != INVALID_FILE_ATTRIBUTES &&
342 (attrs & FILE_ATTRIBUTE_READONLY)) {
343 /* ignore errors here; open() will report them */
344 SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
347 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
348 rc = -1;
349 goto revert_attrs;
352 time_t_to_filetime(times->modtime, &mft);
353 time_t_to_filetime(times->actime, &aft);
354 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
355 errno = EINVAL;
356 rc = -1;
357 } else
358 rc = 0;
359 close(fh);
361 revert_attrs:
362 if (attrs != INVALID_FILE_ATTRIBUTES &&
363 (attrs & FILE_ATTRIBUTE_READONLY)) {
364 /* ignore errors again */
365 SetFileAttributes(file_name, attrs);
367 return rc;
370 unsigned int sleep (unsigned int seconds)
372 Sleep(seconds*1000);
373 return 0;
376 int mkstemp(char *template)
378 char *filename = mktemp(template);
379 if (filename == NULL)
380 return -1;
381 return open(filename, O_RDWR | O_CREAT, 0600);
384 int gettimeofday(struct timeval *tv, void *tz)
386 FILETIME ft;
387 long long hnsec;
389 GetSystemTimeAsFileTime(&ft);
390 hnsec = filetime_to_hnsec(&ft);
391 tv->tv_sec = hnsec / 10000000;
392 tv->tv_usec = (hnsec % 10000000) / 10;
393 return 0;
396 int pipe(int filedes[2])
398 HANDLE h[2];
400 /* this creates non-inheritable handles */
401 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
402 errno = err_win_to_posix(GetLastError());
403 return -1;
405 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
406 if (filedes[0] < 0) {
407 CloseHandle(h[0]);
408 CloseHandle(h[1]);
409 return -1;
411 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
412 if (filedes[0] < 0) {
413 close(filedes[0]);
414 CloseHandle(h[1]);
415 return -1;
417 return 0;
420 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
422 int i, pending;
424 if (timeout >= 0) {
425 if (nfds == 0) {
426 Sleep(timeout);
427 return 0;
429 return errno = EINVAL, error("poll timeout not supported");
432 /* When there is only one fd to wait for, then we pretend that
433 * input is available and let the actual wait happen when the
434 * caller invokes read().
436 if (nfds == 1) {
437 if (!(ufds[0].events & POLLIN))
438 return errno = EINVAL, error("POLLIN not set");
439 ufds[0].revents = POLLIN;
440 return 0;
443 repeat:
444 pending = 0;
445 for (i = 0; i < nfds; i++) {
446 DWORD avail = 0;
447 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
448 if (h == INVALID_HANDLE_VALUE)
449 return -1; /* errno was set */
451 if (!(ufds[i].events & POLLIN))
452 return errno = EINVAL, error("POLLIN not set");
454 /* this emulation works only for pipes */
455 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
456 int err = GetLastError();
457 if (err == ERROR_BROKEN_PIPE) {
458 ufds[i].revents = POLLHUP;
459 pending++;
460 } else {
461 errno = EINVAL;
462 return error("PeekNamedPipe failed,"
463 " GetLastError: %u", err);
465 } else if (avail) {
466 ufds[i].revents = POLLIN;
467 pending++;
468 } else
469 ufds[i].revents = 0;
471 if (!pending) {
472 /* The only times that we spin here is when the process
473 * that is connected through the pipes is waiting for
474 * its own input data to become available. But since
475 * the process (pack-objects) is itself CPU intensive,
476 * it will happily pick up the time slice that we are
477 * relinquishing here.
479 Sleep(0);
480 goto repeat;
482 return 0;
485 struct tm *gmtime_r(const time_t *timep, struct tm *result)
487 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
488 memcpy(result, gmtime(timep), sizeof(struct tm));
489 return result;
492 struct tm *localtime_r(const time_t *timep, struct tm *result)
494 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
495 memcpy(result, localtime(timep), sizeof(struct tm));
496 return result;
499 #undef getcwd
500 char *mingw_getcwd(char *pointer, int len)
502 int i;
503 char *ret = getcwd(pointer, len);
504 if (!ret)
505 return ret;
506 for (i = 0; pointer[i]; i++)
507 if (pointer[i] == '\\')
508 pointer[i] = '/';
509 return ret;
512 #undef getenv
513 char *mingw_getenv(const char *name)
515 char *result = getenv(name);
516 if (!result && !strcmp(name, "TMPDIR")) {
517 /* on Windows it is TMP and TEMP */
518 result = getenv("TMP");
519 if (!result)
520 result = getenv("TEMP");
522 return result;
526 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
527 * (Parsing C++ Command-Line Arguments)
529 static const char *quote_arg(const char *arg)
531 /* count chars to quote */
532 int len = 0, n = 0;
533 int force_quotes = 0;
534 char *q, *d;
535 const char *p = arg;
536 if (!*p) force_quotes = 1;
537 while (*p) {
538 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
539 force_quotes = 1;
540 else if (*p == '"')
541 n++;
542 else if (*p == '\\') {
543 int count = 0;
544 while (*p == '\\') {
545 count++;
546 p++;
547 len++;
549 if (*p == '"')
550 n += count*2 + 1;
551 continue;
553 len++;
554 p++;
556 if (!force_quotes && n == 0)
557 return arg;
559 /* insert \ where necessary */
560 d = q = xmalloc(len+n+3);
561 *d++ = '"';
562 while (*arg) {
563 if (*arg == '"')
564 *d++ = '\\';
565 else if (*arg == '\\') {
566 int count = 0;
567 while (*arg == '\\') {
568 count++;
569 *d++ = *arg++;
571 if (*arg == '"') {
572 while (count-- > 0)
573 *d++ = '\\';
574 *d++ = '\\';
577 *d++ = *arg++;
579 *d++ = '"';
580 *d++ = 0;
581 return q;
584 static const char *parse_interpreter(const char *cmd)
586 static char buf[100];
587 char *p, *opt;
588 int n, fd;
590 /* don't even try a .exe */
591 n = strlen(cmd);
592 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
593 return NULL;
595 fd = open(cmd, O_RDONLY);
596 if (fd < 0)
597 return NULL;
598 n = read(fd, buf, sizeof(buf)-1);
599 close(fd);
600 if (n < 4) /* at least '#!/x' and not error */
601 return NULL;
603 if (buf[0] != '#' || buf[1] != '!')
604 return NULL;
605 buf[n] = '\0';
606 p = buf + strcspn(buf, "\r\n");
607 if (!*p)
608 return NULL;
610 *p = '\0';
611 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
612 return NULL;
613 /* strip options */
614 if ((opt = strchr(p+1, ' ')))
615 *opt = '\0';
616 return p+1;
620 * Splits the PATH into parts.
622 static char **get_path_split(void)
624 char *p, **path, *envpath = getenv("PATH");
625 int i, n = 0;
627 if (!envpath || !*envpath)
628 return NULL;
630 envpath = xstrdup(envpath);
631 p = envpath;
632 while (p) {
633 char *dir = p;
634 p = strchr(p, ';');
635 if (p) *p++ = '\0';
636 if (*dir) { /* not earlier, catches series of ; */
637 ++n;
640 if (!n)
641 return NULL;
643 path = xmalloc((n+1)*sizeof(char *));
644 p = envpath;
645 i = 0;
646 do {
647 if (*p)
648 path[i++] = xstrdup(p);
649 p = p+strlen(p)+1;
650 } while (i < n);
651 path[i] = NULL;
653 free(envpath);
655 return path;
658 static void free_path_split(char **path)
660 char **p = path;
662 if (!path)
663 return;
665 while (*p)
666 free(*p++);
667 free(path);
671 * exe_only means that we only want to detect .exe files, but not scripts
672 * (which do not have an extension)
674 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
676 char path[MAX_PATH];
677 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
679 if (!isexe && access(path, F_OK) == 0)
680 return xstrdup(path);
681 path[strlen(path)-4] = '\0';
682 if ((!exe_only || isexe) && access(path, F_OK) == 0)
683 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
684 return xstrdup(path);
685 return NULL;
689 * Determines the absolute path of cmd using the the split path in path.
690 * If cmd contains a slash or backslash, no lookup is performed.
692 static char *path_lookup(const char *cmd, char **path, int exe_only)
694 char *prog = NULL;
695 int len = strlen(cmd);
696 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
698 if (strchr(cmd, '/') || strchr(cmd, '\\'))
699 prog = xstrdup(cmd);
701 while (!prog && *path)
702 prog = lookup_prog(*path++, cmd, isexe, exe_only);
704 return prog;
707 static int env_compare(const void *a, const void *b)
709 char *const *ea = a;
710 char *const *eb = b;
711 return strcasecmp(*ea, *eb);
714 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
715 int prepend_cmd, int fhin, int fhout, int fherr)
717 STARTUPINFO si;
718 PROCESS_INFORMATION pi;
719 struct strbuf envblk, args;
720 unsigned flags;
721 BOOL ret;
723 /* Determine whether or not we are associated to a console */
724 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
725 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
726 FILE_ATTRIBUTE_NORMAL, NULL);
727 if (cons == INVALID_HANDLE_VALUE) {
728 /* There is no console associated with this process.
729 * Since the child is a console process, Windows
730 * would normally create a console window. But
731 * since we'll be redirecting std streams, we do
732 * not need the console.
733 * It is necessary to use DETACHED_PROCESS
734 * instead of CREATE_NO_WINDOW to make ssh
735 * recognize that it has no console.
737 flags = DETACHED_PROCESS;
738 } else {
739 /* There is already a console. If we specified
740 * DETACHED_PROCESS here, too, Windows would
741 * disassociate the child from the console.
742 * The same is true for CREATE_NO_WINDOW.
743 * Go figure!
745 flags = 0;
746 CloseHandle(cons);
748 memset(&si, 0, sizeof(si));
749 si.cb = sizeof(si);
750 si.dwFlags = STARTF_USESTDHANDLES;
751 si.hStdInput = (HANDLE) _get_osfhandle(fhin);
752 si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
753 si.hStdError = (HANDLE) _get_osfhandle(fherr);
755 /* concatenate argv, quoting args as we go */
756 strbuf_init(&args, 0);
757 if (prepend_cmd) {
758 char *quoted = (char *)quote_arg(cmd);
759 strbuf_addstr(&args, quoted);
760 if (quoted != cmd)
761 free(quoted);
763 for (; *argv; argv++) {
764 char *quoted = (char *)quote_arg(*argv);
765 if (*args.buf)
766 strbuf_addch(&args, ' ');
767 strbuf_addstr(&args, quoted);
768 if (quoted != *argv)
769 free(quoted);
772 if (env) {
773 int count = 0;
774 char **e, **sorted_env;
776 for (e = env; *e; e++)
777 count++;
779 /* environment must be sorted */
780 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
781 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
782 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
784 strbuf_init(&envblk, 0);
785 for (e = sorted_env; *e; e++) {
786 strbuf_addstr(&envblk, *e);
787 strbuf_addch(&envblk, '\0');
789 free(sorted_env);
792 memset(&pi, 0, sizeof(pi));
793 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
794 env ? envblk.buf : NULL, NULL, &si, &pi);
796 if (env)
797 strbuf_release(&envblk);
798 strbuf_release(&args);
800 if (!ret) {
801 errno = ENOENT;
802 return -1;
804 CloseHandle(pi.hThread);
805 return (pid_t)pi.hProcess;
808 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
809 int prepend_cmd)
811 return mingw_spawnve_fd(cmd, argv, env, prepend_cmd, 0, 1, 2);
814 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
815 int fhin, int fhout, int fherr)
817 pid_t pid;
818 char **path = get_path_split();
819 char *prog = path_lookup(cmd, path, 0);
821 if (!prog) {
822 errno = ENOENT;
823 pid = -1;
825 else {
826 const char *interpr = parse_interpreter(prog);
828 if (interpr) {
829 const char *argv0 = argv[0];
830 char *iprog = path_lookup(interpr, path, 1);
831 argv[0] = prog;
832 if (!iprog) {
833 errno = ENOENT;
834 pid = -1;
836 else {
837 pid = mingw_spawnve_fd(iprog, argv, env, 1,
838 fhin, fhout, fherr);
839 free(iprog);
841 argv[0] = argv0;
843 else
844 pid = mingw_spawnve_fd(prog, argv, env, 0,
845 fhin, fhout, fherr);
846 free(prog);
848 free_path_split(path);
849 return pid;
852 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
854 const char *interpr = parse_interpreter(cmd);
855 char **path;
856 char *prog;
857 int pid = 0;
859 if (!interpr)
860 return 0;
861 path = get_path_split();
862 prog = path_lookup(interpr, path, 1);
863 if (prog) {
864 int argc = 0;
865 const char **argv2;
866 while (argv[argc]) argc++;
867 argv2 = xmalloc(sizeof(*argv) * (argc+1));
868 argv2[0] = (char *)cmd; /* full path to the script file */
869 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
870 pid = mingw_spawnve(prog, argv2, env, 1);
871 if (pid >= 0) {
872 int status;
873 if (waitpid(pid, &status, 0) < 0)
874 status = 255;
875 exit(status);
877 pid = 1; /* indicate that we tried but failed */
878 free(prog);
879 free(argv2);
881 free_path_split(path);
882 return pid;
885 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
887 /* check if git_command is a shell script */
888 if (!try_shell_exec(cmd, argv, (char **)env)) {
889 int pid, status;
891 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
892 if (pid < 0)
893 return;
894 if (waitpid(pid, &status, 0) < 0)
895 status = 255;
896 exit(status);
900 void mingw_execvp(const char *cmd, char *const *argv)
902 char **path = get_path_split();
903 char *prog = path_lookup(cmd, path, 0);
905 if (prog) {
906 mingw_execve(prog, argv, environ);
907 free(prog);
908 } else
909 errno = ENOENT;
911 free_path_split(path);
914 static char **copy_environ(void)
916 char **env;
917 int i = 0;
918 while (environ[i])
919 i++;
920 env = xmalloc((i+1)*sizeof(*env));
921 for (i = 0; environ[i]; i++)
922 env[i] = xstrdup(environ[i]);
923 env[i] = NULL;
924 return env;
927 void free_environ(char **env)
929 int i;
930 for (i = 0; env[i]; i++)
931 free(env[i]);
932 free(env);
935 static int lookup_env(char **env, const char *name, size_t nmln)
937 int i;
939 for (i = 0; env[i]; i++) {
940 if (0 == strncmp(env[i], name, nmln)
941 && '=' == env[i][nmln])
942 /* matches */
943 return i;
945 return -1;
949 * If name contains '=', then sets the variable, otherwise it unsets it
951 static char **env_setenv(char **env, const char *name)
953 char *eq = strchrnul(name, '=');
954 int i = lookup_env(env, name, eq-name);
956 if (i < 0) {
957 if (*eq) {
958 for (i = 0; env[i]; i++)
960 env = xrealloc(env, (i+2)*sizeof(*env));
961 env[i] = xstrdup(name);
962 env[i+1] = NULL;
965 else {
966 free(env[i]);
967 if (*eq)
968 env[i] = xstrdup(name);
969 else
970 for (; env[i]; i++)
971 env[i] = env[i+1];
973 return env;
977 * Copies global environ and adjusts variables as specified by vars.
979 char **make_augmented_environ(const char *const *vars)
981 char **env = copy_environ();
983 while (*vars)
984 env = env_setenv(env, *vars++);
985 return env;
989 * Note, this isn't a complete replacement for getaddrinfo. It assumes
990 * that service contains a numerical port, or that it it is null. It
991 * does a simple search using gethostbyname, and returns one IPv4 host
992 * if one was found.
994 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
995 const struct addrinfo *hints,
996 struct addrinfo **res)
998 struct hostent *h = gethostbyname(node);
999 struct addrinfo *ai;
1000 struct sockaddr_in *sin;
1002 if (!h)
1003 return WSAGetLastError();
1005 ai = xmalloc(sizeof(struct addrinfo));
1006 *res = ai;
1007 ai->ai_flags = 0;
1008 ai->ai_family = AF_INET;
1009 ai->ai_socktype = hints->ai_socktype;
1010 switch (hints->ai_socktype) {
1011 case SOCK_STREAM:
1012 ai->ai_protocol = IPPROTO_TCP;
1013 break;
1014 case SOCK_DGRAM:
1015 ai->ai_protocol = IPPROTO_UDP;
1016 break;
1017 default:
1018 ai->ai_protocol = 0;
1019 break;
1021 ai->ai_addrlen = sizeof(struct sockaddr_in);
1022 ai->ai_canonname = strdup(h->h_name);
1024 sin = xmalloc(ai->ai_addrlen);
1025 memset(sin, 0, ai->ai_addrlen);
1026 sin->sin_family = AF_INET;
1027 if (service)
1028 sin->sin_port = htons(atoi(service));
1029 sin->sin_addr = *(struct in_addr *)h->h_addr;
1030 ai->ai_addr = (struct sockaddr *)sin;
1031 ai->ai_next = 0;
1032 return 0;
1035 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1037 free(res->ai_canonname);
1038 free(res->ai_addr);
1039 free(res);
1042 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1043 char *host, DWORD hostlen,
1044 char *serv, DWORD servlen, int flags)
1046 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1047 if (sa->sa_family != AF_INET)
1048 return EAI_FAMILY;
1049 if (!host && !serv)
1050 return EAI_NONAME;
1052 if (host && hostlen > 0) {
1053 struct hostent *ent = NULL;
1054 if (!(flags & NI_NUMERICHOST))
1055 ent = gethostbyaddr((const char *)&sin->sin_addr,
1056 sizeof(sin->sin_addr), AF_INET);
1058 if (ent)
1059 snprintf(host, hostlen, "%s", ent->h_name);
1060 else if (flags & NI_NAMEREQD)
1061 return EAI_NONAME;
1062 else
1063 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1066 if (serv && servlen > 0) {
1067 struct servent *ent = NULL;
1068 if (!(flags & NI_NUMERICSERV))
1069 ent = getservbyport(sin->sin_port,
1070 flags & NI_DGRAM ? "udp" : "tcp");
1072 if (ent)
1073 snprintf(serv, servlen, "%s", ent->s_name);
1074 else
1075 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1078 return 0;
1081 static HMODULE ipv6_dll = NULL;
1082 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1083 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1084 const struct addrinfo *hints,
1085 struct addrinfo **res);
1086 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1087 char *host, DWORD hostlen,
1088 char *serv, DWORD servlen, int flags);
1090 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1091 * don't need to try to load that one dynamically.
1094 static void socket_cleanup(void)
1096 WSACleanup();
1097 if (ipv6_dll)
1098 FreeLibrary(ipv6_dll);
1099 ipv6_dll = NULL;
1100 ipv6_freeaddrinfo = freeaddrinfo_stub;
1101 ipv6_getaddrinfo = getaddrinfo_stub;
1102 ipv6_getnameinfo = getnameinfo_stub;
1105 static void ensure_socket_initialization(void)
1107 WSADATA wsa;
1108 static int initialized = 0;
1109 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1110 const char **name;
1112 if (initialized)
1113 return;
1115 if (WSAStartup(MAKEWORD(2,2), &wsa))
1116 die("unable to initialize winsock subsystem, error %d",
1117 WSAGetLastError());
1119 for (name = libraries; *name; name++) {
1120 ipv6_dll = LoadLibrary(*name);
1121 if (!ipv6_dll)
1122 continue;
1124 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1125 GetProcAddress(ipv6_dll, "freeaddrinfo");
1126 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1127 const struct addrinfo *,
1128 struct addrinfo **))
1129 GetProcAddress(ipv6_dll, "getaddrinfo");
1130 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1131 socklen_t, char *, DWORD,
1132 char *, DWORD, int))
1133 GetProcAddress(ipv6_dll, "getnameinfo");
1134 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1135 FreeLibrary(ipv6_dll);
1136 ipv6_dll = NULL;
1137 } else
1138 break;
1140 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1141 ipv6_freeaddrinfo = freeaddrinfo_stub;
1142 ipv6_getaddrinfo = getaddrinfo_stub;
1143 ipv6_getnameinfo = getnameinfo_stub;
1146 atexit(socket_cleanup);
1147 initialized = 1;
1150 #undef gethostbyname
1151 struct hostent *mingw_gethostbyname(const char *host)
1153 ensure_socket_initialization();
1154 return gethostbyname(host);
1157 void mingw_freeaddrinfo(struct addrinfo *res)
1159 ipv6_freeaddrinfo(res);
1162 int mingw_getaddrinfo(const char *node, const char *service,
1163 const struct addrinfo *hints, struct addrinfo **res)
1165 ensure_socket_initialization();
1166 return ipv6_getaddrinfo(node, service, hints, res);
1169 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1170 char *host, DWORD hostlen, char *serv, DWORD servlen,
1171 int flags)
1173 ensure_socket_initialization();
1174 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1177 int mingw_socket(int domain, int type, int protocol)
1179 int sockfd;
1180 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
1181 if (s == INVALID_SOCKET) {
1183 * WSAGetLastError() values are regular BSD error codes
1184 * biased by WSABASEERR.
1185 * However, strerror() does not know about networking
1186 * specific errors, which are values beginning at 38 or so.
1187 * Therefore, we choose to leave the biased error code
1188 * in errno so that _if_ someone looks up the code somewhere,
1189 * then it is at least the number that are usually listed.
1191 errno = WSAGetLastError();
1192 return -1;
1194 /* convert into a file descriptor */
1195 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1196 closesocket(s);
1197 return error("unable to make a socket file descriptor: %s",
1198 strerror(errno));
1200 return sockfd;
1203 #undef connect
1204 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1206 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1207 return connect(s, sa, sz);
1210 #undef rename
1211 int mingw_rename(const char *pold, const char *pnew)
1213 DWORD attrs, gle;
1214 int tries = 0;
1215 static const int delay[] = { 0, 1, 10, 20, 40 };
1218 * Try native rename() first to get errno right.
1219 * It is based on MoveFile(), which cannot overwrite existing files.
1221 if (!rename(pold, pnew))
1222 return 0;
1223 if (errno != EEXIST)
1224 return -1;
1225 repeat:
1226 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1227 return 0;
1228 /* TODO: translate more errors */
1229 gle = GetLastError();
1230 if (gle == ERROR_ACCESS_DENIED &&
1231 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1232 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1233 errno = EISDIR;
1234 return -1;
1236 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1237 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1238 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1239 return 0;
1240 gle = GetLastError();
1241 /* revert file attributes on failure */
1242 SetFileAttributes(pnew, attrs);
1245 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1247 * We assume that some other process had the source or
1248 * destination file open at the wrong moment and retry.
1249 * In order to give the other process a higher chance to
1250 * complete its operation, we give up our time slice now.
1251 * If we have to retry again, we do sleep a bit.
1253 Sleep(delay[tries]);
1254 tries++;
1255 goto repeat;
1257 errno = EACCES;
1258 return -1;
1262 * Note that this doesn't return the actual pagesize, but
1263 * the allocation granularity. If future Windows specific git code
1264 * needs the real getpagesize function, we need to find another solution.
1266 int mingw_getpagesize(void)
1268 SYSTEM_INFO si;
1269 GetSystemInfo(&si);
1270 return si.dwAllocationGranularity;
1273 struct passwd *getpwuid(int uid)
1275 static char user_name[100];
1276 static struct passwd p;
1278 DWORD len = sizeof(user_name);
1279 if (!GetUserName(user_name, &len))
1280 return NULL;
1281 p.pw_name = user_name;
1282 p.pw_gecos = "unknown";
1283 p.pw_dir = NULL;
1284 return &p;
1287 static HANDLE timer_event;
1288 static HANDLE timer_thread;
1289 static int timer_interval;
1290 static int one_shot;
1291 static sig_handler_t timer_fn = SIG_DFL;
1293 /* The timer works like this:
1294 * The thread, ticktack(), is a trivial routine that most of the time
1295 * only waits to receive the signal to terminate. The main thread tells
1296 * the thread to terminate by setting the timer_event to the signalled
1297 * state.
1298 * But ticktack() interrupts the wait state after the timer's interval
1299 * length to call the signal handler.
1302 static unsigned __stdcall ticktack(void *dummy)
1304 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1305 if (timer_fn == SIG_DFL)
1306 die("Alarm");
1307 if (timer_fn != SIG_IGN)
1308 timer_fn(SIGALRM);
1309 if (one_shot)
1310 break;
1312 return 0;
1315 static int start_timer_thread(void)
1317 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1318 if (timer_event) {
1319 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1320 if (!timer_thread )
1321 return errno = ENOMEM,
1322 error("cannot start timer thread");
1323 } else
1324 return errno = ENOMEM,
1325 error("cannot allocate resources for timer");
1326 return 0;
1329 static void stop_timer_thread(void)
1331 if (timer_event)
1332 SetEvent(timer_event); /* tell thread to terminate */
1333 if (timer_thread) {
1334 int rc = WaitForSingleObject(timer_thread, 1000);
1335 if (rc == WAIT_TIMEOUT)
1336 error("timer thread did not terminate timely");
1337 else if (rc != WAIT_OBJECT_0)
1338 error("waiting for timer thread failed: %lu",
1339 GetLastError());
1340 CloseHandle(timer_thread);
1342 if (timer_event)
1343 CloseHandle(timer_event);
1344 timer_event = NULL;
1345 timer_thread = NULL;
1348 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1350 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1353 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1355 static const struct timeval zero;
1356 static int atexit_done;
1358 if (out != NULL)
1359 return errno = EINVAL,
1360 error("setitimer param 3 != NULL not implemented");
1361 if (!is_timeval_eq(&in->it_interval, &zero) &&
1362 !is_timeval_eq(&in->it_interval, &in->it_value))
1363 return errno = EINVAL,
1364 error("setitimer: it_interval must be zero or eq it_value");
1366 if (timer_thread)
1367 stop_timer_thread();
1369 if (is_timeval_eq(&in->it_value, &zero) &&
1370 is_timeval_eq(&in->it_interval, &zero))
1371 return 0;
1373 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1374 one_shot = is_timeval_eq(&in->it_interval, &zero);
1375 if (!atexit_done) {
1376 atexit(stop_timer_thread);
1377 atexit_done = 1;
1379 return start_timer_thread();
1382 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1384 if (sig != SIGALRM)
1385 return errno = EINVAL,
1386 error("sigaction only implemented for SIGALRM");
1387 if (out != NULL)
1388 return errno = EINVAL,
1389 error("sigaction: param 3 != NULL not implemented");
1391 timer_fn = in->sa_handler;
1392 return 0;
1395 #undef signal
1396 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1398 sig_handler_t old = timer_fn;
1399 if (sig != SIGALRM)
1400 return signal(sig, handler);
1401 timer_fn = handler;
1402 return old;
1405 static const char *make_backslash_path(const char *path)
1407 static char buf[PATH_MAX + 1];
1408 char *c;
1410 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1411 die("Too long path: %.*s", 60, path);
1413 for (c = buf; *c; c++) {
1414 if (*c == '/')
1415 *c = '\\';
1417 return buf;
1420 void mingw_open_html(const char *unixpath)
1422 const char *htmlpath = make_backslash_path(unixpath);
1423 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1424 const char *, const char *, const char *, INT);
1425 T ShellExecute;
1426 HMODULE shell32;
1428 shell32 = LoadLibrary("shell32.dll");
1429 if (!shell32)
1430 die("cannot load shell32.dll");
1431 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1432 if (!ShellExecute)
1433 die("cannot run browser");
1435 printf("Launching default browser to display HTML ...\n");
1436 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);
1438 FreeLibrary(shell32);
1441 int link(const char *oldpath, const char *newpath)
1443 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1444 static T create_hard_link = NULL;
1445 if (!create_hard_link) {
1446 create_hard_link = (T) GetProcAddress(
1447 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1448 if (!create_hard_link)
1449 create_hard_link = (T)-1;
1451 if (create_hard_link == (T)-1) {
1452 errno = ENOSYS;
1453 return -1;
1455 if (!create_hard_link(newpath, oldpath, NULL)) {
1456 errno = err_win_to_posix(GetLastError());
1457 return -1;
1459 return 0;
1462 char *getpass(const char *prompt)
1464 struct strbuf buf = STRBUF_INIT;
1466 fputs(prompt, stderr);
1467 for (;;) {
1468 char c = _getch();
1469 if (c == '\r' || c == '\n')
1470 break;
1471 strbuf_addch(&buf, c);
1473 fputs("\n", stderr);
1474 return strbuf_detach(&buf, NULL);
1477 #ifndef NO_MINGW_REPLACE_READDIR
1478 /* MinGW readdir implementation to avoid extra lstats for Git */
1479 struct mingw_DIR
1481 struct _finddata_t dd_dta; /* disk transfer area for this dir */
1482 struct mingw_dirent dd_dir; /* Our own implementation, including d_type */
1483 long dd_handle; /* _findnext handle */
1484 int dd_stat; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1485 char dd_name[1]; /* given path for dir with search pattern (struct is extended) */
1488 struct dirent *mingw_readdir(DIR *dir)
1490 WIN32_FIND_DATAA buf;
1491 HANDLE handle;
1492 struct mingw_DIR *mdir = (struct mingw_DIR*)dir;
1494 if (!dir->dd_handle) {
1495 errno = EBADF; /* No set_errno for mingw */
1496 return NULL;
1499 if (dir->dd_handle == (long)INVALID_HANDLE_VALUE && dir->dd_stat == 0)
1501 DWORD lasterr;
1502 handle = FindFirstFileA(dir->dd_name, &buf);
1503 lasterr = GetLastError();
1504 dir->dd_handle = (long)handle;
1505 if (handle == INVALID_HANDLE_VALUE && (lasterr != ERROR_NO_MORE_FILES)) {
1506 errno = err_win_to_posix(lasterr);
1507 return NULL;
1509 } else if (dir->dd_handle == (long)INVALID_HANDLE_VALUE) {
1510 return NULL;
1511 } else if (!FindNextFileA((HANDLE)dir->dd_handle, &buf)) {
1512 DWORD lasterr = GetLastError();
1513 FindClose((HANDLE)dir->dd_handle);
1514 dir->dd_handle = (long)INVALID_HANDLE_VALUE;
1515 /* POSIX says you shouldn't set errno when readdir can't
1516 find any more files; so, if another error we leave it set. */
1517 if (lasterr != ERROR_NO_MORE_FILES)
1518 errno = err_win_to_posix(lasterr);
1519 return NULL;
1522 /* We get here if `buf' contains valid data. */
1523 strcpy(dir->dd_dir.d_name, buf.cFileName);
1524 ++dir->dd_stat;
1526 /* Set file type, based on WIN32_FIND_DATA */
1527 mdir->dd_dir.d_type = 0;
1528 if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1529 mdir->dd_dir.d_type |= DT_DIR;
1530 else
1531 mdir->dd_dir.d_type |= DT_REG;
1533 return (struct dirent*)&dir->dd_dir;
1535 #endif // !NO_MINGW_REPLACE_READDIR