1 #include "../git-compat-util.h"
5 unsigned int _CRT_fmode = _O_BINARY;
8 int mingw_open (const char *filename, int oflags, ...)
12 va_start(args, oflags);
13 mode = va_arg(args, int);
16 if (!strcmp(filename, "/dev/null"))
18 int fd = open(filename, oflags, mode);
19 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
20 DWORD attrs = GetFileAttributes(filename);
21 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
27 static inline time_t filetime_to_time_t(const FILETIME *ft)
29 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
30 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
31 winTime /= 10000000; /* Nano to seconds resolution */
32 return (time_t)winTime;
35 /* We keep the do_lstat code in a separate function to avoid recursion.
36 * When a path ends with a slash, the stat will fail with ENOENT. In
37 * this case, we strip the trailing slashes and stat again.
39 static int do_lstat(const char *file_name, struct stat *buf)
41 WIN32_FILE_ATTRIBUTE_DATA fdata;
43 if (!(errno = get_file_attr(file_name, &fdata))) {
48 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
49 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
50 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
51 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
52 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
53 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
59 /* We provide our own lstat/fstat functions, since the provided
60 * lstat/fstat functions are so slow. These stat functions are
61 * tailored for Git's usage (read: fast), and are not meant to be
62 * complete. Note that Git stat()s are redirected to mingw_lstat()
63 * too, since Windows doesn't really handle symlinks that well.
65 int mingw_lstat(const char *file_name, struct stat *buf)
68 static char alt_name[PATH_MAX];
70 if (!do_lstat(file_name, buf))
73 /* if file_name ended in a '/', Windows returned ENOENT;
74 * try again without trailing slashes
79 namelen = strlen(file_name);
80 if (namelen && file_name[namelen-1] != '/')
82 while (namelen && file_name[namelen-1] == '/')
84 if (!namelen || namelen >= PATH_MAX)
87 memcpy(alt_name, file_name, namelen);
88 alt_name[namelen] = 0;
89 return do_lstat(alt_name, buf);
93 int mingw_fstat(int fd, struct stat *buf)
95 HANDLE fh = (HANDLE)_get_osfhandle(fd);
96 BY_HANDLE_FILE_INFORMATION fdata;
98 if (fh == INVALID_HANDLE_VALUE) {
102 /* direct non-file handles to MS's fstat() */
103 if (GetFileType(fh) != FILE_TYPE_DISK)
104 return fstat(fd, buf);
106 if (GetFileInformationByHandle(fh, &fdata)) {
111 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
112 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
113 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
114 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
115 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
116 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
123 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
125 long long winTime = t * 10000000LL + 116444736000000000LL;
126 ft->dwLowDateTime = winTime;
127 ft->dwHighDateTime = winTime >> 32;
130 int mingw_utime (const char *file_name, const struct utimbuf *times)
135 /* must have write permission */
136 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
139 time_t_to_filetime(times->modtime, &mft);
140 time_t_to_filetime(times->actime, &aft);
141 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
150 unsigned int sleep (unsigned int seconds)
156 int mkstemp(char *template)
158 char *filename = mktemp(template);
159 if (filename == NULL)
161 return open(filename, O_RDWR | O_CREAT, 0600);
164 int gettimeofday(struct timeval *tv, void *tz)
169 tm.tm_year = st.wYear-1900;
170 tm.tm_mon = st.wMonth-1;
171 tm.tm_mday = st.wDay;
172 tm.tm_hour = st.wHour;
173 tm.tm_min = st.wMinute;
174 tm.tm_sec = st.wSecond;
175 tv->tv_sec = tm_to_time_t(&tm);
178 tv->tv_usec = st.wMilliseconds*1000;
182 int pipe(int filedes[2])
187 if (_pipe(filedes, 8192, 0) < 0)
190 parent = GetCurrentProcess();
192 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
193 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
198 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
199 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
205 fd = _open_osfhandle((int)h[0], O_NOINHERIT);
215 fd = _open_osfhandle((int)h[1], O_NOINHERIT);
227 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
236 return errno = EINVAL, error("poll timeout not supported");
239 /* When there is only one fd to wait for, then we pretend that
240 * input is available and let the actual wait happen when the
241 * caller invokes read().
244 if (!(ufds[0].events & POLLIN))
245 return errno = EINVAL, error("POLLIN not set");
246 ufds[0].revents = POLLIN;
252 for (i = 0; i < nfds; i++) {
254 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
255 if (h == INVALID_HANDLE_VALUE)
256 return -1; /* errno was set */
258 if (!(ufds[i].events & POLLIN))
259 return errno = EINVAL, error("POLLIN not set");
261 /* this emulation works only for pipes */
262 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
263 int err = GetLastError();
264 if (err == ERROR_BROKEN_PIPE) {
265 ufds[i].revents = POLLHUP;
269 return error("PeekNamedPipe failed,"
270 " GetLastError: %u", err);
273 ufds[i].revents = POLLIN;
279 /* The only times that we spin here is when the process
280 * that is connected through the pipes is waiting for
281 * its own input data to become available. But since
282 * the process (pack-objects) is itself CPU intensive,
283 * it will happily pick up the time slice that we are
284 * relinguishing here.
292 struct tm *gmtime_r(const time_t *timep, struct tm *result)
294 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
295 memcpy(result, gmtime(timep), sizeof(struct tm));
299 struct tm *localtime_r(const time_t *timep, struct tm *result)
301 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
302 memcpy(result, localtime(timep), sizeof(struct tm));
307 char *mingw_getcwd(char *pointer, int len)
310 char *ret = getcwd(pointer, len);
313 for (i = 0; pointer[i]; i++)
314 if (pointer[i] == '\\')
320 char *mingw_getenv(const char *name)
322 char *result = getenv(name);
323 if (!result && !strcmp(name, "TMPDIR")) {
324 /* on Windows it is TMP and TEMP */
325 result = getenv("TMP");
327 result = getenv("TEMP");
333 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
334 * (Parsing C++ Command-Line Arguments)
336 static const char *quote_arg(const char *arg)
338 /* count chars to quote */
340 int force_quotes = 0;
343 if (!*p) force_quotes = 1;
345 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
349 else if (*p == '\\') {
363 if (!force_quotes && n == 0)
366 /* insert \ where necessary */
367 d = q = xmalloc(len+n+3);
372 else if (*arg == '\\') {
374 while (*arg == '\\') {
391 static const char *parse_interpreter(const char *cmd)
393 static char buf[100];
397 /* don't even try a .exe */
399 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
402 fd = open(cmd, O_RDONLY);
405 n = read(fd, buf, sizeof(buf)-1);
407 if (n < 4) /* at least '#!/x' and not error */
410 if (buf[0] != '#' || buf[1] != '!')
413 p = strchr(buf, '\n');
418 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
421 if ((opt = strchr(p+1, ' ')))
427 * Splits the PATH into parts.
429 static char **get_path_split(void)
431 char *p, **path, *envpath = getenv("PATH");
434 if (!envpath || !*envpath)
437 envpath = xstrdup(envpath);
443 if (*dir) { /* not earlier, catches series of ; */
450 path = xmalloc((n+1)*sizeof(char*));
455 path[i++] = xstrdup(p);
465 static void free_path_split(char **path)
477 * exe_only means that we only want to detect .exe files, but not scripts
478 * (which do not have an extension)
480 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
483 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
485 if (!isexe && access(path, F_OK) == 0)
486 return xstrdup(path);
487 path[strlen(path)-4] = '\0';
488 if ((!exe_only || isexe) && access(path, F_OK) == 0)
489 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
490 return xstrdup(path);
495 * Determines the absolute path of cmd using the the split path in path.
496 * If cmd contains a slash or backslash, no lookup is performed.
498 static char *path_lookup(const char *cmd, char **path, int exe_only)
501 int len = strlen(cmd);
502 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
504 if (strchr(cmd, '/') || strchr(cmd, '\\'))
507 while (!prog && *path)
508 prog = lookup_prog(*path++, cmd, isexe, exe_only);
513 static int env_compare(const void *a, const void *b)
517 return strcasecmp(*ea, *eb);
520 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
524 PROCESS_INFORMATION pi;
525 struct strbuf envblk, args;
529 /* Determine whether or not we are associated to a console */
530 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
531 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
532 FILE_ATTRIBUTE_NORMAL, NULL);
533 if (cons == INVALID_HANDLE_VALUE) {
534 /* There is no console associated with this process.
535 * Since the child is a console process, Windows
536 * would normally create a console window. But
537 * since we'll be redirecting std streams, we do
538 * not need the console.
540 flags = CREATE_NO_WINDOW;
542 /* There is already a console. If we specified
543 * CREATE_NO_WINDOW here, too, Windows would
544 * disassociate the child from the console.
550 memset(&si, 0, sizeof(si));
552 si.dwFlags = STARTF_USESTDHANDLES;
553 si.hStdInput = (HANDLE) _get_osfhandle(0);
554 si.hStdOutput = (HANDLE) _get_osfhandle(1);
555 si.hStdError = (HANDLE) _get_osfhandle(2);
557 /* concatenate argv, quoting args as we go */
558 strbuf_init(&args, 0);
560 char *quoted = (char *)quote_arg(cmd);
561 strbuf_addstr(&args, quoted);
565 for (; *argv; argv++) {
566 char *quoted = (char *)quote_arg(*argv);
568 strbuf_addch(&args, ' ');
569 strbuf_addstr(&args, quoted);
576 char **e, **sorted_env;
578 for (e = env; *e; e++)
581 /* environment must be sorted */
582 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
583 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
584 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
586 strbuf_init(&envblk, 0);
587 for (e = sorted_env; *e; e++) {
588 strbuf_addstr(&envblk, *e);
589 strbuf_addch(&envblk, '\0');
594 memset(&pi, 0, sizeof(pi));
595 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
596 env ? envblk.buf : NULL, NULL, &si, &pi);
599 strbuf_release(&envblk);
600 strbuf_release(&args);
606 CloseHandle(pi.hThread);
607 return (pid_t)pi.hProcess;
610 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
613 char **path = get_path_split();
614 char *prog = path_lookup(cmd, path, 0);
621 const char *interpr = parse_interpreter(prog);
624 const char *argv0 = argv[0];
625 char *iprog = path_lookup(interpr, path, 1);
632 pid = mingw_spawnve(iprog, argv, env, 1);
638 pid = mingw_spawnve(prog, argv, env, 0);
641 free_path_split(path);
645 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
647 const char *interpr = parse_interpreter(cmd);
654 path = get_path_split();
655 prog = path_lookup(interpr, path, 1);
659 while (argv[argc]) argc++;
660 argv2 = xmalloc(sizeof(*argv) * (argc+1));
661 argv2[0] = (char *)cmd; /* full path to the script file */
662 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
663 pid = mingw_spawnve(prog, argv2, env, 1);
666 if (waitpid(pid, &status, 0) < 0)
670 pid = 1; /* indicate that we tried but failed */
674 free_path_split(path);
678 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
680 /* check if git_command is a shell script */
681 if (!try_shell_exec(cmd, argv, (char **)env)) {
684 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
687 if (waitpid(pid, &status, 0) < 0)
693 void mingw_execvp(const char *cmd, char *const *argv)
695 char **path = get_path_split();
696 char *prog = path_lookup(cmd, path, 0);
699 mingw_execve(prog, argv, environ);
704 free_path_split(path);
707 char **copy_environ()
713 env = xmalloc((i+1)*sizeof(*env));
714 for (i = 0; environ[i]; i++)
715 env[i] = xstrdup(environ[i]);
720 void free_environ(char **env)
723 for (i = 0; env[i]; i++)
728 static int lookup_env(char **env, const char *name, size_t nmln)
732 for (i = 0; env[i]; i++) {
733 if (0 == strncmp(env[i], name, nmln)
734 && '=' == env[i][nmln])
742 * If name contains '=', then sets the variable, otherwise it unsets it
744 char **env_setenv(char **env, const char *name)
746 char *eq = strchrnul(name, '=');
747 int i = lookup_env(env, name, eq-name);
751 for (i = 0; env[i]; i++)
753 env = xrealloc(env, (i+2)*sizeof(*env));
754 env[i] = xstrdup(name);
761 env[i] = xstrdup(name);
769 /* this is the first function to call into WS_32; initialize it */
771 struct hostent *mingw_gethostbyname(const char *host)
775 if (WSAStartup(MAKEWORD(2,2), &wsa))
776 die("unable to initialize winsock subsystem, error %d",
778 atexit((void(*)(void)) WSACleanup);
779 return gethostbyname(host);
782 int mingw_socket(int domain, int type, int protocol)
785 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
786 if (s == INVALID_SOCKET) {
788 * WSAGetLastError() values are regular BSD error codes
789 * biased by WSABASEERR.
790 * However, strerror() does not know about networking
791 * specific errors, which are values beginning at 38 or so.
792 * Therefore, we choose to leave the biased error code
793 * in errno so that _if_ someone looks up the code somewhere,
794 * then it is at least the number that are usually listed.
796 errno = WSAGetLastError();
799 /* convert into a file descriptor */
800 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
802 return error("unable to make a socket file descriptor: %s",
809 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
811 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
812 return connect(s, sa, sz);
816 int mingw_rename(const char *pold, const char *pnew)
819 * Try native rename() first to get errno right.
820 * It is based on MoveFile(), which cannot overwrite existing files.
822 if (!rename(pold, pnew))
826 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
828 /* TODO: translate more errors */
829 if (GetLastError() == ERROR_ACCESS_DENIED) {
830 DWORD attrs = GetFileAttributes(pnew);
831 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
840 struct passwd *getpwuid(int uid)
842 static char user_name[100];
843 static struct passwd p;
845 DWORD len = sizeof(user_name);
846 if (!GetUserName(user_name, &len))
848 p.pw_name = user_name;
849 p.pw_gecos = "unknown";
854 static HANDLE timer_event;
855 static HANDLE timer_thread;
856 static int timer_interval;
858 static sig_handler_t timer_fn = SIG_DFL;
860 /* The timer works like this:
861 * The thread, ticktack(), is a trivial routine that most of the time
862 * only waits to receive the signal to terminate. The main thread tells
863 * the thread to terminate by setting the timer_event to the signalled
865 * But ticktack() interrupts the wait state after the timer's interval
866 * length to call the signal handler.
869 static __stdcall unsigned ticktack(void *dummy)
871 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
872 if (timer_fn == SIG_DFL)
874 if (timer_fn != SIG_IGN)
882 static int start_timer_thread(void)
884 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
886 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
888 return errno = ENOMEM,
889 error("cannot start timer thread");
891 return errno = ENOMEM,
892 error("cannot allocate resources for timer");
896 static void stop_timer_thread(void)
899 SetEvent(timer_event); /* tell thread to terminate */
901 int rc = WaitForSingleObject(timer_thread, 1000);
902 if (rc == WAIT_TIMEOUT)
903 error("timer thread did not terminate timely");
904 else if (rc != WAIT_OBJECT_0)
905 error("waiting for timer thread failed: %lu",
907 CloseHandle(timer_thread);
910 CloseHandle(timer_event);
915 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
917 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
920 int setitimer(int type, struct itimerval *in, struct itimerval *out)
922 static const struct timeval zero;
923 static int atexit_done;
926 return errno = EINVAL,
927 error("setitimer param 3 != NULL not implemented");
928 if (!is_timeval_eq(&in->it_interval, &zero) &&
929 !is_timeval_eq(&in->it_interval, &in->it_value))
930 return errno = EINVAL,
931 error("setitimer: it_interval must be zero or eq it_value");
936 if (is_timeval_eq(&in->it_value, &zero) &&
937 is_timeval_eq(&in->it_interval, &zero))
940 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
941 one_shot = is_timeval_eq(&in->it_interval, &zero);
943 atexit(stop_timer_thread);
946 return start_timer_thread();
949 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
952 return errno = EINVAL,
953 error("sigaction only implemented for SIGALRM");
955 return errno = EINVAL,
956 error("sigaction: param 3 != NULL not implemented");
958 timer_fn = in->sa_handler;
963 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
966 return signal(sig, handler);
967 sig_handler_t old = timer_fn;
972 static const char *make_backslash_path(const char *path)
974 static char buf[PATH_MAX + 1];
977 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
978 die("Too long path: %.*s", 60, path);
980 for (c = buf; *c; c++) {
987 void mingw_open_html(const char *unixpath)
989 const char *htmlpath = make_backslash_path(unixpath);
990 printf("Launching default browser to display HTML ...\n");
991 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);