Windows: Implement a custom spawnve().
[git/debian.git] / compat / mingw.c
blob1ef2a4caf2be92acebd847a9707c78e41d26eb50
1 #include "../git-compat-util.h"
2 #include "../strbuf.h"
4 unsigned int _CRT_fmode = _O_BINARY;
6 #undef open
7 int mingw_open (const char *filename, int oflags, ...)
9 va_list args;
10 unsigned mode;
11 va_start(args, oflags);
12 mode = va_arg(args, int);
13 va_end(args);
15 if (!strcmp(filename, "/dev/null"))
16 filename = "nul";
17 int fd = open(filename, oflags, mode);
18 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
19 DWORD attrs = GetFileAttributes(filename);
20 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
21 errno = EISDIR;
23 return fd;
26 unsigned int sleep (unsigned int seconds)
28 Sleep(seconds*1000);
29 return 0;
32 int mkstemp(char *template)
34 char *filename = mktemp(template);
35 if (filename == NULL)
36 return -1;
37 return open(filename, O_RDWR | O_CREAT, 0600);
40 int gettimeofday(struct timeval *tv, void *tz)
42 SYSTEMTIME st;
43 struct tm tm;
44 GetSystemTime(&st);
45 tm.tm_year = st.wYear-1900;
46 tm.tm_mon = st.wMonth-1;
47 tm.tm_mday = st.wDay;
48 tm.tm_hour = st.wHour;
49 tm.tm_min = st.wMinute;
50 tm.tm_sec = st.wSecond;
51 tv->tv_sec = tm_to_time_t(&tm);
52 if (tv->tv_sec < 0)
53 return -1;
54 tv->tv_usec = st.wMilliseconds*1000;
55 return 0;
58 int pipe(int filedes[2])
60 int fd;
61 HANDLE h[2], parent;
63 if (_pipe(filedes, 8192, 0) < 0)
64 return -1;
66 parent = GetCurrentProcess();
68 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
69 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
70 close(filedes[0]);
71 close(filedes[1]);
72 return -1;
74 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
75 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
76 close(filedes[0]);
77 close(filedes[1]);
78 CloseHandle(h[0]);
79 return -1;
81 fd = _open_osfhandle((int)h[0], O_NOINHERIT);
82 if (fd < 0) {
83 close(filedes[0]);
84 close(filedes[1]);
85 CloseHandle(h[0]);
86 CloseHandle(h[1]);
87 return -1;
89 close(filedes[0]);
90 filedes[0] = fd;
91 fd = _open_osfhandle((int)h[1], O_NOINHERIT);
92 if (fd < 0) {
93 close(filedes[0]);
94 close(filedes[1]);
95 CloseHandle(h[1]);
96 return -1;
98 close(filedes[1]);
99 filedes[1] = fd;
100 return 0;
103 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
105 int i, pending;
107 if (timeout != -1)
108 return errno = EINVAL, error("poll timeout not supported");
110 /* When there is only one fd to wait for, then we pretend that
111 * input is available and let the actual wait happen when the
112 * caller invokes read().
114 if (nfds == 1) {
115 if (!(ufds[0].events & POLLIN))
116 return errno = EINVAL, error("POLLIN not set");
117 ufds[0].revents = POLLIN;
118 return 0;
121 repeat:
122 pending = 0;
123 for (i = 0; i < nfds; i++) {
124 DWORD avail = 0;
125 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
126 if (h == INVALID_HANDLE_VALUE)
127 return -1; /* errno was set */
129 if (!(ufds[i].events & POLLIN))
130 return errno = EINVAL, error("POLLIN not set");
132 /* this emulation works only for pipes */
133 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
134 int err = GetLastError();
135 if (err == ERROR_BROKEN_PIPE) {
136 ufds[i].revents = POLLHUP;
137 pending++;
138 } else {
139 errno = EINVAL;
140 return error("PeekNamedPipe failed,"
141 " GetLastError: %u", err);
143 } else if (avail) {
144 ufds[i].revents = POLLIN;
145 pending++;
146 } else
147 ufds[i].revents = 0;
149 if (!pending) {
150 /* The only times that we spin here is when the process
151 * that is connected through the pipes is waiting for
152 * its own input data to become available. But since
153 * the process (pack-objects) is itself CPU intensive,
154 * it will happily pick up the time slice that we are
155 * relinguishing here.
157 Sleep(0);
158 goto repeat;
160 return 0;
163 struct tm *gmtime_r(const time_t *timep, struct tm *result)
165 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
166 memcpy(result, gmtime(timep), sizeof(struct tm));
167 return result;
170 struct tm *localtime_r(const time_t *timep, struct tm *result)
172 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
173 memcpy(result, localtime(timep), sizeof(struct tm));
174 return result;
177 #undef getcwd
178 char *mingw_getcwd(char *pointer, int len)
180 int i;
181 char *ret = getcwd(pointer, len);
182 if (!ret)
183 return ret;
184 for (i = 0; pointer[i]; i++)
185 if (pointer[i] == '\\')
186 pointer[i] = '/';
187 return ret;
191 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
192 * (Parsing C++ Command-Line Arguments)
194 static const char *quote_arg(const char *arg)
196 /* count chars to quote */
197 int len = 0, n = 0;
198 int force_quotes = 0;
199 char *q, *d;
200 const char *p = arg;
201 if (!*p) force_quotes = 1;
202 while (*p) {
203 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
204 force_quotes = 1;
205 else if (*p == '"')
206 n++;
207 else if (*p == '\\') {
208 int count = 0;
209 while (*p == '\\') {
210 count++;
211 p++;
212 len++;
214 if (*p == '"')
215 n += count*2 + 1;
216 continue;
218 len++;
219 p++;
221 if (!force_quotes && n == 0)
222 return arg;
224 /* insert \ where necessary */
225 d = q = xmalloc(len+n+3);
226 *d++ = '"';
227 while (*arg) {
228 if (*arg == '"')
229 *d++ = '\\';
230 else if (*arg == '\\') {
231 int count = 0;
232 while (*arg == '\\') {
233 count++;
234 *d++ = *arg++;
236 if (*arg == '"') {
237 while (count-- > 0)
238 *d++ = '\\';
239 *d++ = '\\';
242 *d++ = *arg++;
244 *d++ = '"';
245 *d++ = 0;
246 return q;
249 static const char *parse_interpreter(const char *cmd)
251 static char buf[100];
252 char *p, *opt;
253 int n, fd;
255 /* don't even try a .exe */
256 n = strlen(cmd);
257 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
258 return NULL;
260 fd = open(cmd, O_RDONLY);
261 if (fd < 0)
262 return NULL;
263 n = read(fd, buf, sizeof(buf)-1);
264 close(fd);
265 if (n < 4) /* at least '#!/x' and not error */
266 return NULL;
268 if (buf[0] != '#' || buf[1] != '!')
269 return NULL;
270 buf[n] = '\0';
271 p = strchr(buf, '\n');
272 if (!p)
273 return NULL;
275 *p = '\0';
276 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
277 return NULL;
278 /* strip options */
279 if ((opt = strchr(p+1, ' ')))
280 *opt = '\0';
281 return p+1;
285 * Splits the PATH into parts.
287 static char **get_path_split(void)
289 char *p, **path, *envpath = getenv("PATH");
290 int i, n = 0;
292 if (!envpath || !*envpath)
293 return NULL;
295 envpath = xstrdup(envpath);
296 p = envpath;
297 while (p) {
298 char *dir = p;
299 p = strchr(p, ';');
300 if (p) *p++ = '\0';
301 if (*dir) { /* not earlier, catches series of ; */
302 ++n;
305 if (!n)
306 return NULL;
308 path = xmalloc((n+1)*sizeof(char*));
309 p = envpath;
310 i = 0;
311 do {
312 if (*p)
313 path[i++] = xstrdup(p);
314 p = p+strlen(p)+1;
315 } while (i < n);
316 path[i] = NULL;
318 free(envpath);
320 return path;
323 static void free_path_split(char **path)
325 if (!path)
326 return;
328 char **p = path;
329 while (*p)
330 free(*p++);
331 free(path);
335 * exe_only means that we only want to detect .exe files, but not scripts
336 * (which do not have an extension)
338 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
340 char path[MAX_PATH];
341 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
343 if (!isexe && access(path, F_OK) == 0)
344 return xstrdup(path);
345 path[strlen(path)-4] = '\0';
346 if ((!exe_only || isexe) && access(path, F_OK) == 0)
347 return xstrdup(path);
348 return NULL;
352 * Determines the absolute path of cmd using the the split path in path.
353 * If cmd contains a slash or backslash, no lookup is performed.
355 static char *path_lookup(const char *cmd, char **path, int exe_only)
357 char *prog = NULL;
358 int len = strlen(cmd);
359 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
361 if (strchr(cmd, '/') || strchr(cmd, '\\'))
362 prog = xstrdup(cmd);
364 while (!prog && *path)
365 prog = lookup_prog(*path++, cmd, isexe, exe_only);
367 return prog;
370 static int env_compare(const void *a, const void *b)
372 char *const *ea = a;
373 char *const *eb = b;
374 return strcasecmp(*ea, *eb);
377 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
378 int prepend_cmd)
380 STARTUPINFO si;
381 PROCESS_INFORMATION pi;
382 struct strbuf envblk, args;
383 unsigned flags;
384 BOOL ret;
386 /* Determine whether or not we are associated to a console */
387 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
388 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
389 FILE_ATTRIBUTE_NORMAL, NULL);
390 if (cons == INVALID_HANDLE_VALUE) {
391 /* There is no console associated with this process.
392 * Since the child is a console process, Windows
393 * would normally create a console window. But
394 * since we'll be redirecting std streams, we do
395 * not need the console.
397 flags = CREATE_NO_WINDOW;
398 } else {
399 /* There is already a console. If we specified
400 * CREATE_NO_WINDOW here, too, Windows would
401 * disassociate the child from the console.
402 * Go figure!
404 flags = 0;
405 CloseHandle(cons);
407 memset(&si, 0, sizeof(si));
408 si.cb = sizeof(si);
409 si.dwFlags = STARTF_USESTDHANDLES;
410 si.hStdInput = (HANDLE) _get_osfhandle(0);
411 si.hStdOutput = (HANDLE) _get_osfhandle(1);
412 si.hStdError = (HANDLE) _get_osfhandle(2);
414 /* concatenate argv, quoting args as we go */
415 strbuf_init(&args, 0);
416 if (prepend_cmd) {
417 char *quoted = (char *)quote_arg(cmd);
418 strbuf_addstr(&args, quoted);
419 if (quoted != cmd)
420 free(quoted);
422 for (; *argv; argv++) {
423 char *quoted = (char *)quote_arg(*argv);
424 if (*args.buf)
425 strbuf_addch(&args, ' ');
426 strbuf_addstr(&args, quoted);
427 if (quoted != *argv)
428 free(quoted);
431 if (env) {
432 int count = 0;
433 char **e, **sorted_env;
435 for (e = env; *e; e++)
436 count++;
438 /* environment must be sorted */
439 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
440 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
441 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
443 strbuf_init(&envblk, 0);
444 for (e = sorted_env; *e; e++) {
445 strbuf_addstr(&envblk, *e);
446 strbuf_addch(&envblk, '\0');
448 free(sorted_env);
451 memset(&pi, 0, sizeof(pi));
452 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
453 env ? envblk.buf : NULL, NULL, &si, &pi);
455 if (env)
456 strbuf_release(&envblk);
457 strbuf_release(&args);
459 if (!ret) {
460 errno = ENOENT;
461 return -1;
463 CloseHandle(pi.hThread);
464 return (pid_t)pi.hProcess;
467 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
469 pid_t pid;
470 char **path = get_path_split();
471 char *prog = path_lookup(cmd, path, 0);
473 if (!prog) {
474 errno = ENOENT;
475 pid = -1;
477 else {
478 const char *interpr = parse_interpreter(prog);
480 if (interpr) {
481 const char *argv0 = argv[0];
482 char *iprog = path_lookup(interpr, path, 1);
483 argv[0] = prog;
484 if (!iprog) {
485 errno = ENOENT;
486 pid = -1;
488 else {
489 pid = mingw_spawnve(iprog, argv, env, 1);
490 free(iprog);
492 argv[0] = argv0;
494 else
495 pid = mingw_spawnve(prog, argv, env, 0);
496 free(prog);
498 free_path_split(path);
499 return pid;
502 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
504 const char *interpr = parse_interpreter(cmd);
505 char **path;
506 char *prog;
507 int pid = 0;
509 if (!interpr)
510 return 0;
511 path = get_path_split();
512 prog = path_lookup(interpr, path, 1);
513 if (prog) {
514 int argc = 0;
515 const char **argv2;
516 while (argv[argc]) argc++;
517 argv2 = xmalloc(sizeof(*argv) * (argc+1));
518 argv2[0] = (char *)cmd; /* full path to the script file */
519 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
520 pid = mingw_spawnve(prog, argv2, env, 1);
521 if (pid >= 0) {
522 int status;
523 if (waitpid(pid, &status, 0) < 0)
524 status = 255;
525 exit(status);
527 pid = 1; /* indicate that we tried but failed */
528 free(prog);
529 free(argv2);
531 free_path_split(path);
532 return pid;
535 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
537 /* check if git_command is a shell script */
538 if (!try_shell_exec(cmd, argv, (char **)env)) {
539 int pid, status;
541 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
542 if (pid < 0)
543 return;
544 if (waitpid(pid, &status, 0) < 0)
545 status = 255;
546 exit(status);
550 void mingw_execvp(const char *cmd, char *const *argv)
552 char **path = get_path_split();
553 char *prog = path_lookup(cmd, path, 0);
555 if (prog) {
556 mingw_execve(prog, argv, environ);
557 free(prog);
558 } else
559 errno = ENOENT;
561 free_path_split(path);
564 char **copy_environ()
566 char **env;
567 int i = 0;
568 while (environ[i])
569 i++;
570 env = xmalloc((i+1)*sizeof(*env));
571 for (i = 0; environ[i]; i++)
572 env[i] = xstrdup(environ[i]);
573 env[i] = NULL;
574 return env;
577 void free_environ(char **env)
579 int i;
580 for (i = 0; env[i]; i++)
581 free(env[i]);
582 free(env);
585 static int lookup_env(char **env, const char *name, size_t nmln)
587 int i;
589 for (i = 0; env[i]; i++) {
590 if (0 == strncmp(env[i], name, nmln)
591 && '=' == env[i][nmln])
592 /* matches */
593 return i;
595 return -1;
599 * If name contains '=', then sets the variable, otherwise it unsets it
601 char **env_setenv(char **env, const char *name)
603 char *eq = strchrnul(name, '=');
604 int i = lookup_env(env, name, eq-name);
606 if (i < 0) {
607 if (*eq) {
608 for (i = 0; env[i]; i++)
610 env = xrealloc(env, (i+2)*sizeof(*env));
611 env[i] = xstrdup(name);
612 env[i+1] = NULL;
615 else {
616 free(env[i]);
617 if (*eq)
618 env[i] = xstrdup(name);
619 else
620 for (; env[i]; i++)
621 env[i] = env[i+1];
623 return env;
626 /* this is the first function to call into WS_32; initialize it */
627 #undef gethostbyname
628 struct hostent *mingw_gethostbyname(const char *host)
630 WSADATA wsa;
632 if (WSAStartup(MAKEWORD(2,2), &wsa))
633 die("unable to initialize winsock subsystem, error %d",
634 WSAGetLastError());
635 atexit((void(*)(void)) WSACleanup);
636 return gethostbyname(host);
639 int mingw_socket(int domain, int type, int protocol)
641 int sockfd;
642 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
643 if (s == INVALID_SOCKET) {
645 * WSAGetLastError() values are regular BSD error codes
646 * biased by WSABASEERR.
647 * However, strerror() does not know about networking
648 * specific errors, which are values beginning at 38 or so.
649 * Therefore, we choose to leave the biased error code
650 * in errno so that _if_ someone looks up the code somewhere,
651 * then it is at least the number that are usually listed.
653 errno = WSAGetLastError();
654 return -1;
656 /* convert into a file descriptor */
657 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
658 closesocket(s);
659 return error("unable to make a socket file descriptor: %s",
660 strerror(errno));
662 return sockfd;
665 #undef connect
666 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
668 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
669 return connect(s, sa, sz);
672 #undef rename
673 int mingw_rename(const char *pold, const char *pnew)
676 * Try native rename() first to get errno right.
677 * It is based on MoveFile(), which cannot overwrite existing files.
679 if (!rename(pold, pnew))
680 return 0;
681 if (errno != EEXIST)
682 return -1;
683 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
684 return 0;
685 /* TODO: translate more errors */
686 if (GetLastError() == ERROR_ACCESS_DENIED) {
687 DWORD attrs = GetFileAttributes(pnew);
688 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
689 errno = EISDIR;
690 return -1;
693 errno = EACCES;
694 return -1;
697 struct passwd *getpwuid(int uid)
699 static char user_name[100];
700 static struct passwd p;
702 DWORD len = sizeof(user_name);
703 if (!GetUserName(user_name, &len))
704 return NULL;
705 p.pw_name = user_name;
706 p.pw_gecos = "unknown";
707 p.pw_dir = NULL;
708 return &p;
711 static HANDLE timer_event;
712 static HANDLE timer_thread;
713 static int timer_interval;
714 static int one_shot;
715 static sig_handler_t timer_fn = SIG_DFL;
717 /* The timer works like this:
718 * The thread, ticktack(), is a trivial routine that most of the time
719 * only waits to receive the signal to terminate. The main thread tells
720 * the thread to terminate by setting the timer_event to the signalled
721 * state.
722 * But ticktack() interrupts the wait state after the timer's interval
723 * length to call the signal handler.
726 static __stdcall unsigned ticktack(void *dummy)
728 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
729 if (timer_fn == SIG_DFL)
730 die("Alarm");
731 if (timer_fn != SIG_IGN)
732 timer_fn(SIGALRM);
733 if (one_shot)
734 break;
736 return 0;
739 static int start_timer_thread(void)
741 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
742 if (timer_event) {
743 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
744 if (!timer_thread )
745 return errno = ENOMEM,
746 error("cannot start timer thread");
747 } else
748 return errno = ENOMEM,
749 error("cannot allocate resources for timer");
750 return 0;
753 static void stop_timer_thread(void)
755 if (timer_event)
756 SetEvent(timer_event); /* tell thread to terminate */
757 if (timer_thread) {
758 int rc = WaitForSingleObject(timer_thread, 1000);
759 if (rc == WAIT_TIMEOUT)
760 error("timer thread did not terminate timely");
761 else if (rc != WAIT_OBJECT_0)
762 error("waiting for timer thread failed: %lu",
763 GetLastError());
764 CloseHandle(timer_thread);
766 if (timer_event)
767 CloseHandle(timer_event);
768 timer_event = NULL;
769 timer_thread = NULL;
772 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
774 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
777 int setitimer(int type, struct itimerval *in, struct itimerval *out)
779 static const struct timeval zero;
780 static int atexit_done;
782 if (out != NULL)
783 return errno = EINVAL,
784 error("setitimer param 3 != NULL not implemented");
785 if (!is_timeval_eq(&in->it_interval, &zero) &&
786 !is_timeval_eq(&in->it_interval, &in->it_value))
787 return errno = EINVAL,
788 error("setitimer: it_interval must be zero or eq it_value");
790 if (timer_thread)
791 stop_timer_thread();
793 if (is_timeval_eq(&in->it_value, &zero) &&
794 is_timeval_eq(&in->it_interval, &zero))
795 return 0;
797 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
798 one_shot = is_timeval_eq(&in->it_interval, &zero);
799 if (!atexit_done) {
800 atexit(stop_timer_thread);
801 atexit_done = 1;
803 return start_timer_thread();
806 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
808 if (sig != SIGALRM)
809 return errno = EINVAL,
810 error("sigaction only implemented for SIGALRM");
811 if (out != NULL)
812 return errno = EINVAL,
813 error("sigaction: param 3 != NULL not implemented");
815 timer_fn = in->sa_handler;
816 return 0;
819 #undef signal
820 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
822 if (sig != SIGALRM)
823 return signal(sig, handler);
824 sig_handler_t old = timer_fn;
825 timer_fn = handler;
826 return old;