mingw: move unlink wrapper to mingw.c
[git/dscho.git] / compat / mingw.c
blob4b2f154b0fb2cb101351a1bd93769732565464e6
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 unlink
159 int mingw_unlink(const char *pathname)
161 /* read-only files cannot be removed */
162 chmod(pathname, 0666);
163 return unlink(pathname);
166 #undef open
167 int mingw_open (const char *filename, int oflags, ...)
169 va_list args;
170 unsigned mode;
171 int fd;
173 va_start(args, oflags);
174 mode = va_arg(args, int);
175 va_end(args);
177 if (!strcmp(filename, "/dev/null"))
178 filename = "nul";
180 fd = open(filename, oflags, mode);
182 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
183 DWORD attrs = GetFileAttributes(filename);
184 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
185 errno = EISDIR;
187 if ((oflags & O_CREAT) && fd >= 0 &&
188 hide_dotfiles == HIDE_DOTFILES_TRUE) {
190 * In Windows a file or dir starting with a dot is not
191 * automatically hidden. So lets mark it as hidden when
192 * such a file is created.
194 const char *start = basename((char*)filename);
195 if (*start == '.' && make_hidden(filename))
196 warning("Could not mark '%s' as hidden.", filename);
198 return fd;
201 #undef write
202 ssize_t mingw_write(int fd, const void *buf, size_t count)
205 * While write() calls to a file on a local disk are translated
206 * into WriteFile() calls with a maximum size of 64KB on Windows
207 * XP and 256KB on Vista, no such cap is placed on writes to
208 * files over the network on Windows XP. Unfortunately, there
209 * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
210 * bigger writes fail on Windows XP.
211 * So we cap to a nice 31MB here to avoid write failures over
212 * the net without changing the number of WriteFile() calls in
213 * the local case.
215 return write(fd, buf, min(count, 31 * 1024 * 1024));
218 #undef fopen
219 FILE *mingw_fopen (const char *filename, const char *otype)
221 int hide = 0;
222 FILE *file;
223 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
224 basename((char*)filename)[0] == '.')
225 hide = access(filename, F_OK);
226 if (!strcmp(filename, "/dev/null"))
227 filename = "nul";
228 file = fopen(filename, otype);
229 if (file && hide && make_hidden(filename))
230 warning("Could not mark '%s' as hidden.", filename);
231 return file;
234 #undef freopen
235 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
237 int hide = 0;
238 FILE *file;
239 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
240 basename((char*)filename)[0] == '.')
241 hide = access(filename, F_OK);
242 if (filename && !strcmp(filename, "/dev/null"))
243 filename = "nul";
244 file = freopen(filename, otype, stream);
245 if (file && hide && make_hidden(filename))
246 warning("Could not mark '%s' as hidden.", filename);
247 return file;
251 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
252 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
254 static inline long long filetime_to_hnsec(const FILETIME *ft)
256 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
257 /* Windows to Unix Epoch conversion */
258 return winTime - 116444736000000000LL;
261 static inline time_t filetime_to_time_t(const FILETIME *ft)
263 return (time_t)(filetime_to_hnsec(ft) / 10000000);
266 /* We keep the do_lstat code in a separate function to avoid recursion.
267 * When a path ends with a slash, the stat will fail with ENOENT. In
268 * this case, we strip the trailing slashes and stat again.
270 static int do_lstat(const char *file_name, struct stat *buf)
272 WIN32_FILE_ATTRIBUTE_DATA fdata;
274 if (!(errno = get_file_attr(file_name, &fdata))) {
275 buf->st_ino = 0;
276 buf->st_gid = 0;
277 buf->st_uid = 0;
278 buf->st_nlink = 1;
279 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
280 buf->st_size = fdata.nFileSizeLow |
281 (((off_t)fdata.nFileSizeHigh)<<32);
282 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
283 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
284 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
285 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
286 return 0;
288 return -1;
291 /* We provide our own lstat/fstat functions, since the provided
292 * lstat/fstat functions are so slow. These stat functions are
293 * tailored for Git's usage (read: fast), and are not meant to be
294 * complete. Note that Git stat()s are redirected to mingw_lstat()
295 * too, since Windows doesn't really handle symlinks that well.
297 int mingw_lstat(const char *file_name, struct stat *buf)
299 int namelen;
300 static char alt_name[PATH_MAX];
302 if (!do_lstat(file_name, buf))
303 return 0;
305 /* if file_name ended in a '/', Windows returned ENOENT;
306 * try again without trailing slashes
308 if (errno != ENOENT)
309 return -1;
311 namelen = strlen(file_name);
312 if (namelen && file_name[namelen-1] != '/')
313 return -1;
314 while (namelen && file_name[namelen-1] == '/')
315 --namelen;
316 if (!namelen || namelen >= PATH_MAX)
317 return -1;
319 memcpy(alt_name, file_name, namelen);
320 alt_name[namelen] = 0;
321 return do_lstat(alt_name, buf);
324 #undef fstat
325 int mingw_fstat(int fd, struct stat *buf)
327 HANDLE fh = (HANDLE)_get_osfhandle(fd);
328 BY_HANDLE_FILE_INFORMATION fdata;
330 if (fh == INVALID_HANDLE_VALUE) {
331 errno = EBADF;
332 return -1;
334 /* direct non-file handles to MS's fstat() */
335 if (GetFileType(fh) != FILE_TYPE_DISK)
336 return _fstati64(fd, buf);
338 if (GetFileInformationByHandle(fh, &fdata)) {
339 buf->st_ino = 0;
340 buf->st_gid = 0;
341 buf->st_uid = 0;
342 buf->st_nlink = 1;
343 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
344 buf->st_size = fdata.nFileSizeLow |
345 (((off_t)fdata.nFileSizeHigh)<<32);
346 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
347 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
348 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
349 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
350 return 0;
352 errno = EBADF;
353 return -1;
356 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
358 long long winTime = t * 10000000LL + 116444736000000000LL;
359 ft->dwLowDateTime = winTime;
360 ft->dwHighDateTime = winTime >> 32;
363 int mingw_utime (const char *file_name, const struct utimbuf *times)
365 FILETIME mft, aft;
366 int fh, rc;
368 /* must have write permission */
369 DWORD attrs = GetFileAttributes(file_name);
370 if (attrs != INVALID_FILE_ATTRIBUTES &&
371 (attrs & FILE_ATTRIBUTE_READONLY)) {
372 /* ignore errors here; open() will report them */
373 SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
376 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
377 rc = -1;
378 goto revert_attrs;
381 time_t_to_filetime(times->modtime, &mft);
382 time_t_to_filetime(times->actime, &aft);
383 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
384 errno = EINVAL;
385 rc = -1;
386 } else
387 rc = 0;
388 close(fh);
390 revert_attrs:
391 if (attrs != INVALID_FILE_ATTRIBUTES &&
392 (attrs & FILE_ATTRIBUTE_READONLY)) {
393 /* ignore errors again */
394 SetFileAttributes(file_name, attrs);
396 return rc;
399 unsigned int sleep (unsigned int seconds)
401 Sleep(seconds*1000);
402 return 0;
405 int mkstemp(char *template)
407 char *filename = mktemp(template);
408 if (filename == NULL)
409 return -1;
410 return open(filename, O_RDWR | O_CREAT, 0600);
413 int gettimeofday(struct timeval *tv, void *tz)
415 FILETIME ft;
416 long long hnsec;
418 GetSystemTimeAsFileTime(&ft);
419 hnsec = filetime_to_hnsec(&ft);
420 tv->tv_sec = hnsec / 10000000;
421 tv->tv_usec = (hnsec % 10000000) / 10;
422 return 0;
425 int pipe(int filedes[2])
427 HANDLE h[2];
429 /* this creates non-inheritable handles */
430 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
431 errno = err_win_to_posix(GetLastError());
432 return -1;
434 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
435 if (filedes[0] < 0) {
436 CloseHandle(h[0]);
437 CloseHandle(h[1]);
438 return -1;
440 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
441 if (filedes[0] < 0) {
442 close(filedes[0]);
443 CloseHandle(h[1]);
444 return -1;
446 return 0;
449 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
451 int i, pending;
453 if (timeout >= 0) {
454 if (nfds == 0) {
455 Sleep(timeout);
456 return 0;
458 return errno = EINVAL, error("poll timeout not supported");
461 /* When there is only one fd to wait for, then we pretend that
462 * input is available and let the actual wait happen when the
463 * caller invokes read().
465 if (nfds == 1) {
466 if (!(ufds[0].events & POLLIN))
467 return errno = EINVAL, error("POLLIN not set");
468 ufds[0].revents = POLLIN;
469 return 0;
472 repeat:
473 pending = 0;
474 for (i = 0; i < nfds; i++) {
475 DWORD avail = 0;
476 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
477 if (h == INVALID_HANDLE_VALUE)
478 return -1; /* errno was set */
480 if (!(ufds[i].events & POLLIN))
481 return errno = EINVAL, error("POLLIN not set");
483 /* this emulation works only for pipes */
484 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
485 int err = GetLastError();
486 if (err == ERROR_BROKEN_PIPE) {
487 ufds[i].revents = POLLHUP;
488 pending++;
489 } else {
490 errno = EINVAL;
491 return error("PeekNamedPipe failed,"
492 " GetLastError: %u", err);
494 } else if (avail) {
495 ufds[i].revents = POLLIN;
496 pending++;
497 } else
498 ufds[i].revents = 0;
500 if (!pending) {
501 /* The only times that we spin here is when the process
502 * that is connected through the pipes is waiting for
503 * its own input data to become available. But since
504 * the process (pack-objects) is itself CPU intensive,
505 * it will happily pick up the time slice that we are
506 * relinquishing here.
508 Sleep(0);
509 goto repeat;
511 return 0;
514 struct tm *gmtime_r(const time_t *timep, struct tm *result)
516 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
517 memcpy(result, gmtime(timep), sizeof(struct tm));
518 return result;
521 struct tm *localtime_r(const time_t *timep, struct tm *result)
523 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
524 memcpy(result, localtime(timep), sizeof(struct tm));
525 return result;
528 #undef getcwd
529 char *mingw_getcwd(char *pointer, int len)
531 int i;
532 char *ret = getcwd(pointer, len);
533 if (!ret)
534 return ret;
535 for (i = 0; pointer[i]; i++)
536 if (pointer[i] == '\\')
537 pointer[i] = '/';
538 return ret;
541 #undef getenv
542 char *mingw_getenv(const char *name)
544 char *result = getenv(name);
545 if (!result && !strcmp(name, "TMPDIR")) {
546 /* on Windows it is TMP and TEMP */
547 result = getenv("TMP");
548 if (!result)
549 result = getenv("TEMP");
551 return result;
555 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
556 * (Parsing C++ Command-Line Arguments)
558 static const char *quote_arg(const char *arg)
560 /* count chars to quote */
561 int len = 0, n = 0;
562 int force_quotes = 0;
563 char *q, *d;
564 const char *p = arg;
565 if (!*p) force_quotes = 1;
566 while (*p) {
567 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
568 force_quotes = 1;
569 else if (*p == '"')
570 n++;
571 else if (*p == '\\') {
572 int count = 0;
573 while (*p == '\\') {
574 count++;
575 p++;
576 len++;
578 if (*p == '"')
579 n += count*2 + 1;
580 continue;
582 len++;
583 p++;
585 if (!force_quotes && n == 0)
586 return arg;
588 /* insert \ where necessary */
589 d = q = xmalloc(len+n+3);
590 *d++ = '"';
591 while (*arg) {
592 if (*arg == '"')
593 *d++ = '\\';
594 else if (*arg == '\\') {
595 int count = 0;
596 while (*arg == '\\') {
597 count++;
598 *d++ = *arg++;
600 if (*arg == '"') {
601 while (count-- > 0)
602 *d++ = '\\';
603 *d++ = '\\';
606 *d++ = *arg++;
608 *d++ = '"';
609 *d++ = 0;
610 return q;
613 static const char *parse_interpreter(const char *cmd)
615 static char buf[100];
616 char *p, *opt;
617 int n, fd;
619 /* don't even try a .exe */
620 n = strlen(cmd);
621 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
622 return NULL;
624 fd = open(cmd, O_RDONLY);
625 if (fd < 0)
626 return NULL;
627 n = read(fd, buf, sizeof(buf)-1);
628 close(fd);
629 if (n < 4) /* at least '#!/x' and not error */
630 return NULL;
632 if (buf[0] != '#' || buf[1] != '!')
633 return NULL;
634 buf[n] = '\0';
635 p = buf + strcspn(buf, "\r\n");
636 if (!*p)
637 return NULL;
639 *p = '\0';
640 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
641 return NULL;
642 /* strip options */
643 if ((opt = strchr(p+1, ' ')))
644 *opt = '\0';
645 return p+1;
649 * Splits the PATH into parts.
651 static char **get_path_split(void)
653 char *p, **path, *envpath = getenv("PATH");
654 int i, n = 0;
656 if (!envpath || !*envpath)
657 return NULL;
659 envpath = xstrdup(envpath);
660 p = envpath;
661 while (p) {
662 char *dir = p;
663 p = strchr(p, ';');
664 if (p) *p++ = '\0';
665 if (*dir) { /* not earlier, catches series of ; */
666 ++n;
669 if (!n)
670 return NULL;
672 path = xmalloc((n+1)*sizeof(char *));
673 p = envpath;
674 i = 0;
675 do {
676 if (*p)
677 path[i++] = xstrdup(p);
678 p = p+strlen(p)+1;
679 } while (i < n);
680 path[i] = NULL;
682 free(envpath);
684 return path;
687 static void free_path_split(char **path)
689 char **p = path;
691 if (!path)
692 return;
694 while (*p)
695 free(*p++);
696 free(path);
700 * exe_only means that we only want to detect .exe files, but not scripts
701 * (which do not have an extension)
703 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
705 char path[MAX_PATH];
706 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
708 if (!isexe && access(path, F_OK) == 0)
709 return xstrdup(path);
710 path[strlen(path)-4] = '\0';
711 if ((!exe_only || isexe) && access(path, F_OK) == 0)
712 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
713 return xstrdup(path);
714 return NULL;
718 * Determines the absolute path of cmd using the the split path in path.
719 * If cmd contains a slash or backslash, no lookup is performed.
721 static char *path_lookup(const char *cmd, char **path, int exe_only)
723 char *prog = NULL;
724 int len = strlen(cmd);
725 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
727 if (strchr(cmd, '/') || strchr(cmd, '\\'))
728 prog = xstrdup(cmd);
730 while (!prog && *path)
731 prog = lookup_prog(*path++, cmd, isexe, exe_only);
733 return prog;
736 static int env_compare(const void *a, const void *b)
738 char *const *ea = a;
739 char *const *eb = b;
740 return strcasecmp(*ea, *eb);
743 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
744 const char *dir,
745 int prepend_cmd, int fhin, int fhout, int fherr)
747 STARTUPINFO si;
748 PROCESS_INFORMATION pi;
749 struct strbuf envblk, args;
750 unsigned flags;
751 BOOL ret;
753 /* Determine whether or not we are associated to a console */
754 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
755 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
756 FILE_ATTRIBUTE_NORMAL, NULL);
757 if (cons == INVALID_HANDLE_VALUE) {
758 /* There is no console associated with this process.
759 * Since the child is a console process, Windows
760 * would normally create a console window. But
761 * since we'll be redirecting std streams, we do
762 * not need the console.
763 * It is necessary to use DETACHED_PROCESS
764 * instead of CREATE_NO_WINDOW to make ssh
765 * recognize that it has no console.
767 flags = DETACHED_PROCESS;
768 } else {
769 /* There is already a console. If we specified
770 * DETACHED_PROCESS here, too, Windows would
771 * disassociate the child from the console.
772 * The same is true for CREATE_NO_WINDOW.
773 * Go figure!
775 flags = 0;
776 CloseHandle(cons);
778 memset(&si, 0, sizeof(si));
779 si.cb = sizeof(si);
780 si.dwFlags = STARTF_USESTDHANDLES;
781 si.hStdInput = (HANDLE) _get_osfhandle(fhin);
782 si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
783 si.hStdError = (HANDLE) _get_osfhandle(fherr);
785 /* concatenate argv, quoting args as we go */
786 strbuf_init(&args, 0);
787 if (prepend_cmd) {
788 char *quoted = (char *)quote_arg(cmd);
789 strbuf_addstr(&args, quoted);
790 if (quoted != cmd)
791 free(quoted);
793 for (; *argv; argv++) {
794 char *quoted = (char *)quote_arg(*argv);
795 if (*args.buf)
796 strbuf_addch(&args, ' ');
797 strbuf_addstr(&args, quoted);
798 if (quoted != *argv)
799 free(quoted);
802 if (env) {
803 int count = 0;
804 char **e, **sorted_env;
806 for (e = env; *e; e++)
807 count++;
809 /* environment must be sorted */
810 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
811 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
812 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
814 strbuf_init(&envblk, 0);
815 for (e = sorted_env; *e; e++) {
816 strbuf_addstr(&envblk, *e);
817 strbuf_addch(&envblk, '\0');
819 free(sorted_env);
822 memset(&pi, 0, sizeof(pi));
823 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
824 env ? envblk.buf : NULL, dir, &si, &pi);
826 if (env)
827 strbuf_release(&envblk);
828 strbuf_release(&args);
830 if (!ret) {
831 errno = ENOENT;
832 return -1;
834 CloseHandle(pi.hThread);
835 return (pid_t)pi.hProcess;
838 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
839 int prepend_cmd)
841 return mingw_spawnve_fd(cmd, argv, env, NULL, prepend_cmd, 0, 1, 2);
844 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
845 const char *dir,
846 int fhin, int fhout, int fherr)
848 pid_t pid;
849 char **path = get_path_split();
850 char *prog = path_lookup(cmd, path, 0);
852 if (!prog) {
853 errno = ENOENT;
854 pid = -1;
856 else {
857 const char *interpr = parse_interpreter(prog);
859 if (interpr) {
860 const char *argv0 = argv[0];
861 char *iprog = path_lookup(interpr, path, 1);
862 argv[0] = prog;
863 if (!iprog) {
864 errno = ENOENT;
865 pid = -1;
867 else {
868 pid = mingw_spawnve_fd(iprog, argv, env, dir, 1,
869 fhin, fhout, fherr);
870 free(iprog);
872 argv[0] = argv0;
874 else
875 pid = mingw_spawnve_fd(prog, argv, env, dir, 0,
876 fhin, fhout, fherr);
877 free(prog);
879 free_path_split(path);
880 return pid;
883 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
885 const char *interpr = parse_interpreter(cmd);
886 char **path;
887 char *prog;
888 int pid = 0;
890 if (!interpr)
891 return 0;
892 path = get_path_split();
893 prog = path_lookup(interpr, path, 1);
894 if (prog) {
895 int argc = 0;
896 const char **argv2;
897 while (argv[argc]) argc++;
898 argv2 = xmalloc(sizeof(*argv) * (argc+1));
899 argv2[0] = (char *)cmd; /* full path to the script file */
900 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
901 pid = mingw_spawnve(prog, argv2, env, 1);
902 if (pid >= 0) {
903 int status;
904 if (waitpid(pid, &status, 0) < 0)
905 status = 255;
906 exit(status);
908 pid = 1; /* indicate that we tried but failed */
909 free(prog);
910 free(argv2);
912 free_path_split(path);
913 return pid;
916 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
918 /* check if git_command is a shell script */
919 if (!try_shell_exec(cmd, argv, (char **)env)) {
920 int pid, status;
922 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
923 if (pid < 0)
924 return;
925 if (waitpid(pid, &status, 0) < 0)
926 status = 255;
927 exit(status);
931 void mingw_execvp(const char *cmd, char *const *argv)
933 char **path = get_path_split();
934 char *prog = path_lookup(cmd, path, 0);
936 if (prog) {
937 mingw_execve(prog, argv, environ);
938 free(prog);
939 } else
940 errno = ENOENT;
942 free_path_split(path);
945 static char **copy_environ(void)
947 char **env;
948 int i = 0;
949 while (environ[i])
950 i++;
951 env = xmalloc((i+1)*sizeof(*env));
952 for (i = 0; environ[i]; i++)
953 env[i] = xstrdup(environ[i]);
954 env[i] = NULL;
955 return env;
958 void free_environ(char **env)
960 int i;
961 for (i = 0; env[i]; i++)
962 free(env[i]);
963 free(env);
966 static int lookup_env(char **env, const char *name, size_t nmln)
968 int i;
970 for (i = 0; env[i]; i++) {
971 if (0 == strncmp(env[i], name, nmln)
972 && '=' == env[i][nmln])
973 /* matches */
974 return i;
976 return -1;
980 * If name contains '=', then sets the variable, otherwise it unsets it
982 static char **env_setenv(char **env, const char *name)
984 char *eq = strchrnul(name, '=');
985 int i = lookup_env(env, name, eq-name);
987 if (i < 0) {
988 if (*eq) {
989 for (i = 0; env[i]; i++)
991 env = xrealloc(env, (i+2)*sizeof(*env));
992 env[i] = xstrdup(name);
993 env[i+1] = NULL;
996 else {
997 free(env[i]);
998 if (*eq)
999 env[i] = xstrdup(name);
1000 else
1001 for (; env[i]; i++)
1002 env[i] = env[i+1];
1004 return env;
1008 * Copies global environ and adjusts variables as specified by vars.
1010 char **make_augmented_environ(const char *const *vars)
1012 char **env = copy_environ();
1014 while (*vars)
1015 env = env_setenv(env, *vars++);
1016 return env;
1020 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1021 * that service contains a numerical port, or that it it is null. It
1022 * does a simple search using gethostbyname, and returns one IPv4 host
1023 * if one was found.
1025 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1026 const struct addrinfo *hints,
1027 struct addrinfo **res)
1029 struct hostent *h = gethostbyname(node);
1030 struct addrinfo *ai;
1031 struct sockaddr_in *sin;
1033 if (!h)
1034 return WSAGetLastError();
1036 ai = xmalloc(sizeof(struct addrinfo));
1037 *res = ai;
1038 ai->ai_flags = 0;
1039 ai->ai_family = AF_INET;
1040 ai->ai_socktype = hints->ai_socktype;
1041 switch (hints->ai_socktype) {
1042 case SOCK_STREAM:
1043 ai->ai_protocol = IPPROTO_TCP;
1044 break;
1045 case SOCK_DGRAM:
1046 ai->ai_protocol = IPPROTO_UDP;
1047 break;
1048 default:
1049 ai->ai_protocol = 0;
1050 break;
1052 ai->ai_addrlen = sizeof(struct sockaddr_in);
1053 ai->ai_canonname = strdup(h->h_name);
1055 sin = xmalloc(ai->ai_addrlen);
1056 memset(sin, 0, ai->ai_addrlen);
1057 sin->sin_family = AF_INET;
1058 if (service)
1059 sin->sin_port = htons(atoi(service));
1060 sin->sin_addr = *(struct in_addr *)h->h_addr;
1061 ai->ai_addr = (struct sockaddr *)sin;
1062 ai->ai_next = 0;
1063 return 0;
1066 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1068 free(res->ai_canonname);
1069 free(res->ai_addr);
1070 free(res);
1073 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1074 char *host, DWORD hostlen,
1075 char *serv, DWORD servlen, int flags)
1077 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1078 if (sa->sa_family != AF_INET)
1079 return EAI_FAMILY;
1080 if (!host && !serv)
1081 return EAI_NONAME;
1083 if (host && hostlen > 0) {
1084 struct hostent *ent = NULL;
1085 if (!(flags & NI_NUMERICHOST))
1086 ent = gethostbyaddr((const char *)&sin->sin_addr,
1087 sizeof(sin->sin_addr), AF_INET);
1089 if (ent)
1090 snprintf(host, hostlen, "%s", ent->h_name);
1091 else if (flags & NI_NAMEREQD)
1092 return EAI_NONAME;
1093 else
1094 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1097 if (serv && servlen > 0) {
1098 struct servent *ent = NULL;
1099 if (!(flags & NI_NUMERICSERV))
1100 ent = getservbyport(sin->sin_port,
1101 flags & NI_DGRAM ? "udp" : "tcp");
1103 if (ent)
1104 snprintf(serv, servlen, "%s", ent->s_name);
1105 else
1106 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1109 return 0;
1112 static HMODULE ipv6_dll = NULL;
1113 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1114 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1115 const struct addrinfo *hints,
1116 struct addrinfo **res);
1117 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1118 char *host, DWORD hostlen,
1119 char *serv, DWORD servlen, int flags);
1121 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1122 * don't need to try to load that one dynamically.
1125 static void socket_cleanup(void)
1127 WSACleanup();
1128 if (ipv6_dll)
1129 FreeLibrary(ipv6_dll);
1130 ipv6_dll = NULL;
1131 ipv6_freeaddrinfo = freeaddrinfo_stub;
1132 ipv6_getaddrinfo = getaddrinfo_stub;
1133 ipv6_getnameinfo = getnameinfo_stub;
1136 static void ensure_socket_initialization(void)
1138 WSADATA wsa;
1139 static int initialized = 0;
1140 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1141 const char **name;
1143 if (initialized)
1144 return;
1146 if (WSAStartup(MAKEWORD(2,2), &wsa))
1147 die("unable to initialize winsock subsystem, error %d",
1148 WSAGetLastError());
1150 for (name = libraries; *name; name++) {
1151 ipv6_dll = LoadLibrary(*name);
1152 if (!ipv6_dll)
1153 continue;
1155 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1156 GetProcAddress(ipv6_dll, "freeaddrinfo");
1157 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1158 const struct addrinfo *,
1159 struct addrinfo **))
1160 GetProcAddress(ipv6_dll, "getaddrinfo");
1161 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1162 socklen_t, char *, DWORD,
1163 char *, DWORD, int))
1164 GetProcAddress(ipv6_dll, "getnameinfo");
1165 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1166 FreeLibrary(ipv6_dll);
1167 ipv6_dll = NULL;
1168 } else
1169 break;
1171 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1172 ipv6_freeaddrinfo = freeaddrinfo_stub;
1173 ipv6_getaddrinfo = getaddrinfo_stub;
1174 ipv6_getnameinfo = getnameinfo_stub;
1177 atexit(socket_cleanup);
1178 initialized = 1;
1181 #undef gethostbyname
1182 struct hostent *mingw_gethostbyname(const char *host)
1184 ensure_socket_initialization();
1185 return gethostbyname(host);
1188 void mingw_freeaddrinfo(struct addrinfo *res)
1190 ipv6_freeaddrinfo(res);
1193 int mingw_getaddrinfo(const char *node, const char *service,
1194 const struct addrinfo *hints, struct addrinfo **res)
1196 ensure_socket_initialization();
1197 return ipv6_getaddrinfo(node, service, hints, res);
1200 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1201 char *host, DWORD hostlen, char *serv, DWORD servlen,
1202 int flags)
1204 ensure_socket_initialization();
1205 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1208 int mingw_socket(int domain, int type, int protocol)
1210 int sockfd;
1211 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
1212 if (s == INVALID_SOCKET) {
1214 * WSAGetLastError() values are regular BSD error codes
1215 * biased by WSABASEERR.
1216 * However, strerror() does not know about networking
1217 * specific errors, which are values beginning at 38 or so.
1218 * Therefore, we choose to leave the biased error code
1219 * in errno so that _if_ someone looks up the code somewhere,
1220 * then it is at least the number that are usually listed.
1222 errno = WSAGetLastError();
1223 return -1;
1225 /* convert into a file descriptor */
1226 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1227 closesocket(s);
1228 return error("unable to make a socket file descriptor: %s",
1229 strerror(errno));
1231 return sockfd;
1234 #undef connect
1235 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1237 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1238 return connect(s, sa, sz);
1241 #undef rename
1242 int mingw_rename(const char *pold, const char *pnew)
1244 DWORD attrs, gle;
1245 int tries = 0;
1246 static const int delay[] = { 0, 1, 10, 20, 40 };
1249 * Try native rename() first to get errno right.
1250 * It is based on MoveFile(), which cannot overwrite existing files.
1252 if (!rename(pold, pnew))
1253 return 0;
1254 if (errno != EEXIST)
1255 return -1;
1256 repeat:
1257 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1258 return 0;
1259 /* TODO: translate more errors */
1260 gle = GetLastError();
1261 if (gle == ERROR_ACCESS_DENIED &&
1262 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1263 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1264 errno = EISDIR;
1265 return -1;
1267 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1268 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1269 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1270 return 0;
1271 gle = GetLastError();
1272 /* revert file attributes on failure */
1273 SetFileAttributes(pnew, attrs);
1276 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1278 * We assume that some other process had the source or
1279 * destination file open at the wrong moment and retry.
1280 * In order to give the other process a higher chance to
1281 * complete its operation, we give up our time slice now.
1282 * If we have to retry again, we do sleep a bit.
1284 Sleep(delay[tries]);
1285 tries++;
1286 goto repeat;
1288 errno = EACCES;
1289 return -1;
1293 * Note that this doesn't return the actual pagesize, but
1294 * the allocation granularity. If future Windows specific git code
1295 * needs the real getpagesize function, we need to find another solution.
1297 int mingw_getpagesize(void)
1299 SYSTEM_INFO si;
1300 GetSystemInfo(&si);
1301 return si.dwAllocationGranularity;
1304 struct passwd *getpwuid(int uid)
1306 static char user_name[100];
1307 static struct passwd p;
1309 DWORD len = sizeof(user_name);
1310 if (!GetUserName(user_name, &len))
1311 return NULL;
1312 p.pw_name = user_name;
1313 p.pw_gecos = "unknown";
1314 p.pw_dir = NULL;
1315 return &p;
1318 static HANDLE timer_event;
1319 static HANDLE timer_thread;
1320 static int timer_interval;
1321 static int one_shot;
1322 static sig_handler_t timer_fn = SIG_DFL;
1324 /* The timer works like this:
1325 * The thread, ticktack(), is a trivial routine that most of the time
1326 * only waits to receive the signal to terminate. The main thread tells
1327 * the thread to terminate by setting the timer_event to the signalled
1328 * state.
1329 * But ticktack() interrupts the wait state after the timer's interval
1330 * length to call the signal handler.
1333 static unsigned __stdcall ticktack(void *dummy)
1335 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1336 if (timer_fn == SIG_DFL)
1337 die("Alarm");
1338 if (timer_fn != SIG_IGN)
1339 timer_fn(SIGALRM);
1340 if (one_shot)
1341 break;
1343 return 0;
1346 static int start_timer_thread(void)
1348 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1349 if (timer_event) {
1350 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1351 if (!timer_thread )
1352 return errno = ENOMEM,
1353 error("cannot start timer thread");
1354 } else
1355 return errno = ENOMEM,
1356 error("cannot allocate resources for timer");
1357 return 0;
1360 static void stop_timer_thread(void)
1362 if (timer_event)
1363 SetEvent(timer_event); /* tell thread to terminate */
1364 if (timer_thread) {
1365 int rc = WaitForSingleObject(timer_thread, 1000);
1366 if (rc == WAIT_TIMEOUT)
1367 error("timer thread did not terminate timely");
1368 else if (rc != WAIT_OBJECT_0)
1369 error("waiting for timer thread failed: %lu",
1370 GetLastError());
1371 CloseHandle(timer_thread);
1373 if (timer_event)
1374 CloseHandle(timer_event);
1375 timer_event = NULL;
1376 timer_thread = NULL;
1379 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1381 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1384 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1386 static const struct timeval zero;
1387 static int atexit_done;
1389 if (out != NULL)
1390 return errno = EINVAL,
1391 error("setitimer param 3 != NULL not implemented");
1392 if (!is_timeval_eq(&in->it_interval, &zero) &&
1393 !is_timeval_eq(&in->it_interval, &in->it_value))
1394 return errno = EINVAL,
1395 error("setitimer: it_interval must be zero or eq it_value");
1397 if (timer_thread)
1398 stop_timer_thread();
1400 if (is_timeval_eq(&in->it_value, &zero) &&
1401 is_timeval_eq(&in->it_interval, &zero))
1402 return 0;
1404 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1405 one_shot = is_timeval_eq(&in->it_interval, &zero);
1406 if (!atexit_done) {
1407 atexit(stop_timer_thread);
1408 atexit_done = 1;
1410 return start_timer_thread();
1413 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1415 if (sig != SIGALRM)
1416 return errno = EINVAL,
1417 error("sigaction only implemented for SIGALRM");
1418 if (out != NULL)
1419 return errno = EINVAL,
1420 error("sigaction: param 3 != NULL not implemented");
1422 timer_fn = in->sa_handler;
1423 return 0;
1426 #undef signal
1427 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1429 sig_handler_t old = timer_fn;
1430 if (sig != SIGALRM)
1431 return signal(sig, handler);
1432 timer_fn = handler;
1433 return old;
1436 static const char *make_backslash_path(const char *path)
1438 static char buf[PATH_MAX + 1];
1439 char *c;
1441 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1442 die("Too long path: %.*s", 60, path);
1444 for (c = buf; *c; c++) {
1445 if (*c == '/')
1446 *c = '\\';
1448 return buf;
1451 void mingw_open_html(const char *unixpath)
1453 const char *htmlpath = make_backslash_path(unixpath);
1454 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1455 const char *, const char *, const char *, INT);
1456 T ShellExecute;
1457 HMODULE shell32;
1459 shell32 = LoadLibrary("shell32.dll");
1460 if (!shell32)
1461 die("cannot load shell32.dll");
1462 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1463 if (!ShellExecute)
1464 die("cannot run browser");
1466 printf("Launching default browser to display HTML ...\n");
1467 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);
1469 FreeLibrary(shell32);
1472 int link(const char *oldpath, const char *newpath)
1474 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1475 static T create_hard_link = NULL;
1476 if (!create_hard_link) {
1477 create_hard_link = (T) GetProcAddress(
1478 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1479 if (!create_hard_link)
1480 create_hard_link = (T)-1;
1482 if (create_hard_link == (T)-1) {
1483 errno = ENOSYS;
1484 return -1;
1486 if (!create_hard_link(newpath, oldpath, NULL)) {
1487 errno = err_win_to_posix(GetLastError());
1488 return -1;
1490 return 0;
1493 char *getpass(const char *prompt)
1495 struct strbuf buf = STRBUF_INIT;
1497 fputs(prompt, stderr);
1498 for (;;) {
1499 char c = _getch();
1500 if (c == '\r' || c == '\n')
1501 break;
1502 strbuf_addch(&buf, c);
1504 fputs("\n", stderr);
1505 return strbuf_detach(&buf, NULL);
1508 #ifndef NO_MINGW_REPLACE_READDIR
1509 /* MinGW readdir implementation to avoid extra lstats for Git */
1510 struct mingw_DIR
1512 struct _finddata_t dd_dta; /* disk transfer area for this dir */
1513 struct mingw_dirent dd_dir; /* Our own implementation, including d_type */
1514 long dd_handle; /* _findnext handle */
1515 int dd_stat; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1516 char dd_name[1]; /* given path for dir with search pattern (struct is extended) */
1519 struct dirent *mingw_readdir(DIR *dir)
1521 WIN32_FIND_DATAA buf;
1522 HANDLE handle;
1523 struct mingw_DIR *mdir = (struct mingw_DIR*)dir;
1525 if (!dir->dd_handle) {
1526 errno = EBADF; /* No set_errno for mingw */
1527 return NULL;
1530 if (dir->dd_handle == (long)INVALID_HANDLE_VALUE && dir->dd_stat == 0)
1532 DWORD lasterr;
1533 handle = FindFirstFileA(dir->dd_name, &buf);
1534 lasterr = GetLastError();
1535 dir->dd_handle = (long)handle;
1536 if (handle == INVALID_HANDLE_VALUE && (lasterr != ERROR_NO_MORE_FILES)) {
1537 errno = err_win_to_posix(lasterr);
1538 return NULL;
1540 } else if (dir->dd_handle == (long)INVALID_HANDLE_VALUE) {
1541 return NULL;
1542 } else if (!FindNextFileA((HANDLE)dir->dd_handle, &buf)) {
1543 DWORD lasterr = GetLastError();
1544 FindClose((HANDLE)dir->dd_handle);
1545 dir->dd_handle = (long)INVALID_HANDLE_VALUE;
1546 /* POSIX says you shouldn't set errno when readdir can't
1547 find any more files; so, if another error we leave it set. */
1548 if (lasterr != ERROR_NO_MORE_FILES)
1549 errno = err_win_to_posix(lasterr);
1550 return NULL;
1553 /* We get here if `buf' contains valid data. */
1554 strcpy(dir->dd_dir.d_name, buf.cFileName);
1555 ++dir->dd_stat;
1557 /* Set file type, based on WIN32_FIND_DATA */
1558 mdir->dd_dir.d_type = 0;
1559 if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1560 mdir->dd_dir.d_type |= DT_DIR;
1561 else
1562 mdir->dd_dir.d_type |= DT_REG;
1564 return (struct dirent*)&dir->dd_dir;
1566 #endif // !NO_MINGW_REPLACE_READDIR