Sync with maint
[alt-git.git] / run-command.c
blob9e36151bf97d36945ca3464e719687718ee6d1c7
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec_cmd.h"
4 #include "sigchain.h"
5 #include "argv-array.h"
6 #include "thread-utils.h"
7 #include "strbuf.h"
9 void child_process_init(struct child_process *child)
11 memset(child, 0, sizeof(*child));
12 argv_array_init(&child->args);
13 argv_array_init(&child->env_array);
16 void child_process_clear(struct child_process *child)
18 argv_array_clear(&child->args);
19 argv_array_clear(&child->env_array);
22 struct child_to_clean {
23 pid_t pid;
24 struct child_process *process;
25 struct child_to_clean *next;
27 static struct child_to_clean *children_to_clean;
28 static int installed_child_cleanup_handler;
30 static void cleanup_children(int sig, int in_signal)
32 struct child_to_clean *children_to_wait_for = NULL;
34 while (children_to_clean) {
35 struct child_to_clean *p = children_to_clean;
36 children_to_clean = p->next;
38 if (p->process && !in_signal) {
39 struct child_process *process = p->process;
40 if (process->clean_on_exit_handler) {
41 trace_printf(
42 "trace: run_command: running exit handler for pid %"
43 PRIuMAX, (uintmax_t)p->pid
45 process->clean_on_exit_handler(process);
49 kill(p->pid, sig);
51 if (p->process && p->process->wait_after_clean) {
52 p->next = children_to_wait_for;
53 children_to_wait_for = p;
54 } else {
55 if (!in_signal)
56 free(p);
60 while (children_to_wait_for) {
61 struct child_to_clean *p = children_to_wait_for;
62 children_to_wait_for = p->next;
64 while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
65 ; /* spin waiting for process exit or error */
67 if (!in_signal)
68 free(p);
72 static void cleanup_children_on_signal(int sig)
74 cleanup_children(sig, 1);
75 sigchain_pop(sig);
76 raise(sig);
79 static void cleanup_children_on_exit(void)
81 cleanup_children(SIGTERM, 0);
84 static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
86 struct child_to_clean *p = xmalloc(sizeof(*p));
87 p->pid = pid;
88 p->process = process;
89 p->next = children_to_clean;
90 children_to_clean = p;
92 if (!installed_child_cleanup_handler) {
93 atexit(cleanup_children_on_exit);
94 sigchain_push_common(cleanup_children_on_signal);
95 installed_child_cleanup_handler = 1;
99 static void clear_child_for_cleanup(pid_t pid)
101 struct child_to_clean **pp;
103 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
104 struct child_to_clean *clean_me = *pp;
106 if (clean_me->pid == pid) {
107 *pp = clean_me->next;
108 free(clean_me);
109 return;
114 static inline void close_pair(int fd[2])
116 close(fd[0]);
117 close(fd[1]);
120 int is_executable(const char *name)
122 struct stat st;
124 if (stat(name, &st) || /* stat, not lstat */
125 !S_ISREG(st.st_mode))
126 return 0;
128 #if defined(GIT_WINDOWS_NATIVE)
130 * On Windows there is no executable bit. The file extension
131 * indicates whether it can be run as an executable, and Git
132 * has special-handling to detect scripts and launch them
133 * through the indicated script interpreter. We test for the
134 * file extension first because virus scanners may make
135 * it quite expensive to open many files.
137 if (ends_with(name, ".exe"))
138 return S_IXUSR;
142 * Now that we know it does not have an executable extension,
143 * peek into the file instead.
145 char buf[3] = { 0 };
146 int n;
147 int fd = open(name, O_RDONLY);
148 st.st_mode &= ~S_IXUSR;
149 if (fd >= 0) {
150 n = read(fd, buf, 2);
151 if (n == 2)
152 /* look for a she-bang */
153 if (!strcmp(buf, "#!"))
154 st.st_mode |= S_IXUSR;
155 close(fd);
158 #endif
159 return st.st_mode & S_IXUSR;
163 * Search $PATH for a command. This emulates the path search that
164 * execvp would perform, without actually executing the command so it
165 * can be used before fork() to prepare to run a command using
166 * execve() or after execvp() to diagnose why it failed.
168 * The caller should ensure that file contains no directory
169 * separators.
171 * Returns the path to the command, as found in $PATH or NULL if the
172 * command could not be found. The caller inherits ownership of the memory
173 * used to store the resultant path.
175 * This should not be used on Windows, where the $PATH search rules
176 * are more complicated (e.g., a search for "foo" should find
177 * "foo.exe").
179 static char *locate_in_PATH(const char *file)
181 const char *p = getenv("PATH");
182 struct strbuf buf = STRBUF_INIT;
184 if (!p || !*p)
185 return NULL;
187 while (1) {
188 const char *end = strchrnul(p, ':');
190 strbuf_reset(&buf);
192 /* POSIX specifies an empty entry as the current directory. */
193 if (end != p) {
194 strbuf_add(&buf, p, end - p);
195 strbuf_addch(&buf, '/');
197 strbuf_addstr(&buf, file);
199 if (is_executable(buf.buf))
200 return strbuf_detach(&buf, NULL);
202 if (!*end)
203 break;
204 p = end + 1;
207 strbuf_release(&buf);
208 return NULL;
211 static int exists_in_PATH(const char *file)
213 char *r = locate_in_PATH(file);
214 free(r);
215 return r != NULL;
218 int sane_execvp(const char *file, char * const argv[])
220 if (!execvp(file, argv))
221 return 0; /* cannot happen ;-) */
224 * When a command can't be found because one of the directories
225 * listed in $PATH is unsearchable, execvp reports EACCES, but
226 * careful usability testing (read: analysis of occasional bug
227 * reports) reveals that "No such file or directory" is more
228 * intuitive.
230 * We avoid commands with "/", because execvp will not do $PATH
231 * lookups in that case.
233 * The reassignment of EACCES to errno looks like a no-op below,
234 * but we need to protect against exists_in_PATH overwriting errno.
236 if (errno == EACCES && !strchr(file, '/'))
237 errno = exists_in_PATH(file) ? EACCES : ENOENT;
238 else if (errno == ENOTDIR && !strchr(file, '/'))
239 errno = ENOENT;
240 return -1;
243 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
245 if (!argv[0])
246 die("BUG: shell command is empty");
248 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
249 #ifndef GIT_WINDOWS_NATIVE
250 argv_array_push(out, SHELL_PATH);
251 #else
252 argv_array_push(out, "sh");
253 #endif
254 argv_array_push(out, "-c");
257 * If we have no extra arguments, we do not even need to
258 * bother with the "$@" magic.
260 if (!argv[1])
261 argv_array_push(out, argv[0]);
262 else
263 argv_array_pushf(out, "%s \"$@\"", argv[0]);
266 argv_array_pushv(out, argv);
267 return out->argv;
270 #ifndef GIT_WINDOWS_NATIVE
271 static int child_notifier = -1;
273 enum child_errcode {
274 CHILD_ERR_CHDIR,
275 CHILD_ERR_DUP2,
276 CHILD_ERR_CLOSE,
277 CHILD_ERR_SIGPROCMASK,
278 CHILD_ERR_ENOENT,
279 CHILD_ERR_SILENT,
280 CHILD_ERR_ERRNO
283 struct child_err {
284 enum child_errcode err;
285 int syserr; /* errno */
288 static void child_die(enum child_errcode err)
290 struct child_err buf;
292 buf.err = err;
293 buf.syserr = errno;
295 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
296 xwrite(child_notifier, &buf, sizeof(buf));
297 _exit(1);
300 static void child_dup2(int fd, int to)
302 if (dup2(fd, to) < 0)
303 child_die(CHILD_ERR_DUP2);
306 static void child_close(int fd)
308 if (close(fd))
309 child_die(CHILD_ERR_CLOSE);
312 static void child_close_pair(int fd[2])
314 child_close(fd[0]);
315 child_close(fd[1]);
319 * parent will make it look like the child spewed a fatal error and died
320 * this is needed to prevent changes to t0061.
322 static void fake_fatal(const char *err, va_list params)
324 vreportf("fatal: ", err, params);
327 static void child_error_fn(const char *err, va_list params)
329 const char msg[] = "error() should not be called in child\n";
330 xwrite(2, msg, sizeof(msg) - 1);
333 static void child_warn_fn(const char *err, va_list params)
335 const char msg[] = "warn() should not be called in child\n";
336 xwrite(2, msg, sizeof(msg) - 1);
339 static void NORETURN child_die_fn(const char *err, va_list params)
341 const char msg[] = "die() should not be called in child\n";
342 xwrite(2, msg, sizeof(msg) - 1);
343 _exit(2);
346 /* this runs in the parent process */
347 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
349 static void (*old_errfn)(const char *err, va_list params);
351 old_errfn = get_error_routine();
352 set_error_routine(fake_fatal);
353 errno = cerr->syserr;
355 switch (cerr->err) {
356 case CHILD_ERR_CHDIR:
357 error_errno("exec '%s': cd to '%s' failed",
358 cmd->argv[0], cmd->dir);
359 break;
360 case CHILD_ERR_DUP2:
361 error_errno("dup2() in child failed");
362 break;
363 case CHILD_ERR_CLOSE:
364 error_errno("close() in child failed");
365 break;
366 case CHILD_ERR_SIGPROCMASK:
367 error_errno("sigprocmask failed restoring signals");
368 break;
369 case CHILD_ERR_ENOENT:
370 error_errno("cannot run %s", cmd->argv[0]);
371 break;
372 case CHILD_ERR_SILENT:
373 break;
374 case CHILD_ERR_ERRNO:
375 error_errno("cannot exec '%s'", cmd->argv[0]);
376 break;
378 set_error_routine(old_errfn);
381 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
383 if (!cmd->argv[0])
384 die("BUG: command is empty");
387 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
388 * attempt to interpret the command with 'sh'.
390 argv_array_push(out, SHELL_PATH);
392 if (cmd->git_cmd) {
393 argv_array_push(out, "git");
394 argv_array_pushv(out, cmd->argv);
395 } else if (cmd->use_shell) {
396 prepare_shell_cmd(out, cmd->argv);
397 } else {
398 argv_array_pushv(out, cmd->argv);
402 * If there are no '/' characters in the command then perform a path
403 * lookup and use the resolved path as the command to exec. If there
404 * are no '/' characters or if the command wasn't found in the path,
405 * have exec attempt to invoke the command directly.
407 if (!strchr(out->argv[1], '/')) {
408 char *program = locate_in_PATH(out->argv[1]);
409 if (program) {
410 free((char *)out->argv[1]);
411 out->argv[1] = program;
416 static char **prep_childenv(const char *const *deltaenv)
418 extern char **environ;
419 char **childenv;
420 struct string_list env = STRING_LIST_INIT_DUP;
421 struct strbuf key = STRBUF_INIT;
422 const char *const *p;
423 int i;
425 /* Construct a sorted string list consisting of the current environ */
426 for (p = (const char *const *) environ; p && *p; p++) {
427 const char *equals = strchr(*p, '=');
429 if (equals) {
430 strbuf_reset(&key);
431 strbuf_add(&key, *p, equals - *p);
432 string_list_append(&env, key.buf)->util = (void *) *p;
433 } else {
434 string_list_append(&env, *p)->util = (void *) *p;
437 string_list_sort(&env);
439 /* Merge in 'deltaenv' with the current environ */
440 for (p = deltaenv; p && *p; p++) {
441 const char *equals = strchr(*p, '=');
443 if (equals) {
444 /* ('key=value'), insert or replace entry */
445 strbuf_reset(&key);
446 strbuf_add(&key, *p, equals - *p);
447 string_list_insert(&env, key.buf)->util = (void *) *p;
448 } else {
449 /* otherwise ('key') remove existing entry */
450 string_list_remove(&env, *p, 0);
454 /* Create an array of 'char *' to be used as the childenv */
455 childenv = xmalloc((env.nr + 1) * sizeof(char *));
456 for (i = 0; i < env.nr; i++)
457 childenv[i] = env.items[i].util;
458 childenv[env.nr] = NULL;
460 string_list_clear(&env, 0);
461 strbuf_release(&key);
462 return childenv;
465 struct atfork_state {
466 #ifndef NO_PTHREADS
467 int cs;
468 #endif
469 sigset_t old;
472 #ifndef NO_PTHREADS
473 static void bug_die(int err, const char *msg)
475 if (err) {
476 errno = err;
477 die_errno("BUG: %s", msg);
480 #endif
482 static void atfork_prepare(struct atfork_state *as)
484 sigset_t all;
486 if (sigfillset(&all))
487 die_errno("sigfillset");
488 #ifdef NO_PTHREADS
489 if (sigprocmask(SIG_SETMASK, &all, &as->old))
490 die_errno("sigprocmask");
491 #else
492 bug_die(pthread_sigmask(SIG_SETMASK, &all, &as->old),
493 "blocking all signals");
494 bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
495 "disabling cancellation");
496 #endif
499 static void atfork_parent(struct atfork_state *as)
501 #ifdef NO_PTHREADS
502 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
503 die_errno("sigprocmask");
504 #else
505 bug_die(pthread_setcancelstate(as->cs, NULL),
506 "re-enabling cancellation");
507 bug_die(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
508 "restoring signal mask");
509 #endif
511 #endif /* GIT_WINDOWS_NATIVE */
513 static inline void set_cloexec(int fd)
515 int flags = fcntl(fd, F_GETFD);
516 if (flags >= 0)
517 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
520 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
522 int status, code = -1;
523 pid_t waiting;
524 int failed_errno = 0;
526 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
527 ; /* nothing */
528 if (in_signal)
529 return 0;
531 if (waiting < 0) {
532 failed_errno = errno;
533 error_errno("waitpid for %s failed", argv0);
534 } else if (waiting != pid) {
535 error("waitpid is confused (%s)", argv0);
536 } else if (WIFSIGNALED(status)) {
537 code = WTERMSIG(status);
538 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
539 error("%s died of signal %d", argv0, code);
541 * This return value is chosen so that code & 0xff
542 * mimics the exit code that a POSIX shell would report for
543 * a program that died from this signal.
545 code += 128;
546 } else if (WIFEXITED(status)) {
547 code = WEXITSTATUS(status);
548 } else {
549 error("waitpid is confused (%s)", argv0);
552 clear_child_for_cleanup(pid);
554 errno = failed_errno;
555 return code;
558 int start_command(struct child_process *cmd)
560 int need_in, need_out, need_err;
561 int fdin[2], fdout[2], fderr[2];
562 int failed_errno;
563 char *str;
565 if (!cmd->argv)
566 cmd->argv = cmd->args.argv;
567 if (!cmd->env)
568 cmd->env = cmd->env_array.argv;
571 * In case of errors we must keep the promise to close FDs
572 * that have been passed in via ->in and ->out.
575 need_in = !cmd->no_stdin && cmd->in < 0;
576 if (need_in) {
577 if (pipe(fdin) < 0) {
578 failed_errno = errno;
579 if (cmd->out > 0)
580 close(cmd->out);
581 str = "standard input";
582 goto fail_pipe;
584 cmd->in = fdin[1];
587 need_out = !cmd->no_stdout
588 && !cmd->stdout_to_stderr
589 && cmd->out < 0;
590 if (need_out) {
591 if (pipe(fdout) < 0) {
592 failed_errno = errno;
593 if (need_in)
594 close_pair(fdin);
595 else if (cmd->in)
596 close(cmd->in);
597 str = "standard output";
598 goto fail_pipe;
600 cmd->out = fdout[0];
603 need_err = !cmd->no_stderr && cmd->err < 0;
604 if (need_err) {
605 if (pipe(fderr) < 0) {
606 failed_errno = errno;
607 if (need_in)
608 close_pair(fdin);
609 else if (cmd->in)
610 close(cmd->in);
611 if (need_out)
612 close_pair(fdout);
613 else if (cmd->out)
614 close(cmd->out);
615 str = "standard error";
616 fail_pipe:
617 error("cannot create %s pipe for %s: %s",
618 str, cmd->argv[0], strerror(failed_errno));
619 child_process_clear(cmd);
620 errno = failed_errno;
621 return -1;
623 cmd->err = fderr[0];
626 trace_argv_printf(cmd->argv, "trace: run_command:");
627 fflush(NULL);
629 #ifndef GIT_WINDOWS_NATIVE
631 int notify_pipe[2];
632 int null_fd = -1;
633 char **childenv;
634 struct argv_array argv = ARGV_ARRAY_INIT;
635 struct child_err cerr;
636 struct atfork_state as;
638 if (pipe(notify_pipe))
639 notify_pipe[0] = notify_pipe[1] = -1;
641 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
642 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
643 if (null_fd < 0)
644 die_errno(_("open /dev/null failed"));
645 set_cloexec(null_fd);
648 prepare_cmd(&argv, cmd);
649 childenv = prep_childenv(cmd->env);
650 atfork_prepare(&as);
653 * NOTE: In order to prevent deadlocking when using threads special
654 * care should be taken with the function calls made in between the
655 * fork() and exec() calls. No calls should be made to functions which
656 * require acquiring a lock (e.g. malloc) as the lock could have been
657 * held by another thread at the time of forking, causing the lock to
658 * never be released in the child process. This means only
659 * Async-Signal-Safe functions are permitted in the child.
661 cmd->pid = fork();
662 failed_errno = errno;
663 if (!cmd->pid) {
664 int sig;
666 * Ensure the default die/error/warn routines do not get
667 * called, they can take stdio locks and malloc.
669 set_die_routine(child_die_fn);
670 set_error_routine(child_error_fn);
671 set_warn_routine(child_warn_fn);
673 close(notify_pipe[0]);
674 set_cloexec(notify_pipe[1]);
675 child_notifier = notify_pipe[1];
677 if (cmd->no_stdin)
678 child_dup2(null_fd, 0);
679 else if (need_in) {
680 child_dup2(fdin[0], 0);
681 child_close_pair(fdin);
682 } else if (cmd->in) {
683 child_dup2(cmd->in, 0);
684 child_close(cmd->in);
687 if (cmd->no_stderr)
688 child_dup2(null_fd, 2);
689 else if (need_err) {
690 child_dup2(fderr[1], 2);
691 child_close_pair(fderr);
692 } else if (cmd->err > 1) {
693 child_dup2(cmd->err, 2);
694 child_close(cmd->err);
697 if (cmd->no_stdout)
698 child_dup2(null_fd, 1);
699 else if (cmd->stdout_to_stderr)
700 child_dup2(2, 1);
701 else if (need_out) {
702 child_dup2(fdout[1], 1);
703 child_close_pair(fdout);
704 } else if (cmd->out > 1) {
705 child_dup2(cmd->out, 1);
706 child_close(cmd->out);
709 if (cmd->dir && chdir(cmd->dir))
710 child_die(CHILD_ERR_CHDIR);
713 * restore default signal handlers here, in case
714 * we catch a signal right before execve below
716 for (sig = 1; sig < NSIG; sig++) {
717 /* ignored signals get reset to SIG_DFL on execve */
718 if (signal(sig, SIG_DFL) == SIG_IGN)
719 signal(sig, SIG_IGN);
722 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
723 child_die(CHILD_ERR_SIGPROCMASK);
726 * Attempt to exec using the command and arguments starting at
727 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
728 * be used in the event exec failed with ENOEXEC at which point
729 * we will try to interpret the command using 'sh'.
731 execve(argv.argv[1], (char *const *) argv.argv + 1,
732 (char *const *) childenv);
733 if (errno == ENOEXEC)
734 execve(argv.argv[0], (char *const *) argv.argv,
735 (char *const *) childenv);
737 if (errno == ENOENT) {
738 if (cmd->silent_exec_failure)
739 child_die(CHILD_ERR_SILENT);
740 child_die(CHILD_ERR_ENOENT);
741 } else {
742 child_die(CHILD_ERR_ERRNO);
745 atfork_parent(&as);
746 if (cmd->pid < 0)
747 error_errno("cannot fork() for %s", cmd->argv[0]);
748 else if (cmd->clean_on_exit)
749 mark_child_for_cleanup(cmd->pid, cmd);
752 * Wait for child's exec. If the exec succeeds (or if fork()
753 * failed), EOF is seen immediately by the parent. Otherwise, the
754 * child process sends a child_err struct.
755 * Note that use of this infrastructure is completely advisory,
756 * therefore, we keep error checks minimal.
758 close(notify_pipe[1]);
759 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
761 * At this point we know that fork() succeeded, but exec()
762 * failed. Errors have been reported to our stderr.
764 wait_or_whine(cmd->pid, cmd->argv[0], 0);
765 child_err_spew(cmd, &cerr);
766 failed_errno = errno;
767 cmd->pid = -1;
769 close(notify_pipe[0]);
771 if (null_fd >= 0)
772 close(null_fd);
773 argv_array_clear(&argv);
774 free(childenv);
776 #else
778 int fhin = 0, fhout = 1, fherr = 2;
779 const char **sargv = cmd->argv;
780 struct argv_array nargv = ARGV_ARRAY_INIT;
782 if (cmd->no_stdin)
783 fhin = open("/dev/null", O_RDWR);
784 else if (need_in)
785 fhin = dup(fdin[0]);
786 else if (cmd->in)
787 fhin = dup(cmd->in);
789 if (cmd->no_stderr)
790 fherr = open("/dev/null", O_RDWR);
791 else if (need_err)
792 fherr = dup(fderr[1]);
793 else if (cmd->err > 2)
794 fherr = dup(cmd->err);
796 if (cmd->no_stdout)
797 fhout = open("/dev/null", O_RDWR);
798 else if (cmd->stdout_to_stderr)
799 fhout = dup(fherr);
800 else if (need_out)
801 fhout = dup(fdout[1]);
802 else if (cmd->out > 1)
803 fhout = dup(cmd->out);
805 if (cmd->git_cmd)
806 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
807 else if (cmd->use_shell)
808 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
810 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
811 cmd->dir, fhin, fhout, fherr);
812 failed_errno = errno;
813 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
814 error_errno("cannot spawn %s", cmd->argv[0]);
815 if (cmd->clean_on_exit && cmd->pid >= 0)
816 mark_child_for_cleanup(cmd->pid, cmd);
818 argv_array_clear(&nargv);
819 cmd->argv = sargv;
820 if (fhin != 0)
821 close(fhin);
822 if (fhout != 1)
823 close(fhout);
824 if (fherr != 2)
825 close(fherr);
827 #endif
829 if (cmd->pid < 0) {
830 if (need_in)
831 close_pair(fdin);
832 else if (cmd->in)
833 close(cmd->in);
834 if (need_out)
835 close_pair(fdout);
836 else if (cmd->out)
837 close(cmd->out);
838 if (need_err)
839 close_pair(fderr);
840 else if (cmd->err)
841 close(cmd->err);
842 child_process_clear(cmd);
843 errno = failed_errno;
844 return -1;
847 if (need_in)
848 close(fdin[0]);
849 else if (cmd->in)
850 close(cmd->in);
852 if (need_out)
853 close(fdout[1]);
854 else if (cmd->out)
855 close(cmd->out);
857 if (need_err)
858 close(fderr[1]);
859 else if (cmd->err)
860 close(cmd->err);
862 return 0;
865 int finish_command(struct child_process *cmd)
867 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
868 child_process_clear(cmd);
869 return ret;
872 int finish_command_in_signal(struct child_process *cmd)
874 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
878 int run_command(struct child_process *cmd)
880 int code;
882 if (cmd->out < 0 || cmd->err < 0)
883 die("BUG: run_command with a pipe can cause deadlock");
885 code = start_command(cmd);
886 if (code)
887 return code;
888 return finish_command(cmd);
891 int run_command_v_opt(const char **argv, int opt)
893 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
896 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
898 struct child_process cmd = CHILD_PROCESS_INIT;
899 cmd.argv = argv;
900 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
901 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
902 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
903 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
904 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
905 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
906 cmd.dir = dir;
907 cmd.env = env;
908 return run_command(&cmd);
911 #ifndef NO_PTHREADS
912 static pthread_t main_thread;
913 static int main_thread_set;
914 static pthread_key_t async_key;
915 static pthread_key_t async_die_counter;
917 static void *run_thread(void *data)
919 struct async *async = data;
920 intptr_t ret;
922 if (async->isolate_sigpipe) {
923 sigset_t mask;
924 sigemptyset(&mask);
925 sigaddset(&mask, SIGPIPE);
926 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
927 ret = error("unable to block SIGPIPE in async thread");
928 return (void *)ret;
932 pthread_setspecific(async_key, async);
933 ret = async->proc(async->proc_in, async->proc_out, async->data);
934 return (void *)ret;
937 static NORETURN void die_async(const char *err, va_list params)
939 vreportf("fatal: ", err, params);
941 if (in_async()) {
942 struct async *async = pthread_getspecific(async_key);
943 if (async->proc_in >= 0)
944 close(async->proc_in);
945 if (async->proc_out >= 0)
946 close(async->proc_out);
947 pthread_exit((void *)128);
950 exit(128);
953 static int async_die_is_recursing(void)
955 void *ret = pthread_getspecific(async_die_counter);
956 pthread_setspecific(async_die_counter, (void *)1);
957 return ret != NULL;
960 int in_async(void)
962 if (!main_thread_set)
963 return 0; /* no asyncs started yet */
964 return !pthread_equal(main_thread, pthread_self());
967 static void NORETURN async_exit(int code)
969 pthread_exit((void *)(intptr_t)code);
972 #else
974 static struct {
975 void (**handlers)(void);
976 size_t nr;
977 size_t alloc;
978 } git_atexit_hdlrs;
980 static int git_atexit_installed;
982 static void git_atexit_dispatch(void)
984 size_t i;
986 for (i=git_atexit_hdlrs.nr ; i ; i--)
987 git_atexit_hdlrs.handlers[i-1]();
990 static void git_atexit_clear(void)
992 free(git_atexit_hdlrs.handlers);
993 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
994 git_atexit_installed = 0;
997 #undef atexit
998 int git_atexit(void (*handler)(void))
1000 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
1001 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
1002 if (!git_atexit_installed) {
1003 if (atexit(&git_atexit_dispatch))
1004 return -1;
1005 git_atexit_installed = 1;
1007 return 0;
1009 #define atexit git_atexit
1011 static int process_is_async;
1012 int in_async(void)
1014 return process_is_async;
1017 static void NORETURN async_exit(int code)
1019 exit(code);
1022 #endif
1024 void check_pipe(int err)
1026 if (err == EPIPE) {
1027 if (in_async())
1028 async_exit(141);
1030 signal(SIGPIPE, SIG_DFL);
1031 raise(SIGPIPE);
1032 /* Should never happen, but just in case... */
1033 exit(141);
1037 int start_async(struct async *async)
1039 int need_in, need_out;
1040 int fdin[2], fdout[2];
1041 int proc_in, proc_out;
1043 need_in = async->in < 0;
1044 if (need_in) {
1045 if (pipe(fdin) < 0) {
1046 if (async->out > 0)
1047 close(async->out);
1048 return error_errno("cannot create pipe");
1050 async->in = fdin[1];
1053 need_out = async->out < 0;
1054 if (need_out) {
1055 if (pipe(fdout) < 0) {
1056 if (need_in)
1057 close_pair(fdin);
1058 else if (async->in)
1059 close(async->in);
1060 return error_errno("cannot create pipe");
1062 async->out = fdout[0];
1065 if (need_in)
1066 proc_in = fdin[0];
1067 else if (async->in)
1068 proc_in = async->in;
1069 else
1070 proc_in = -1;
1072 if (need_out)
1073 proc_out = fdout[1];
1074 else if (async->out)
1075 proc_out = async->out;
1076 else
1077 proc_out = -1;
1079 #ifdef NO_PTHREADS
1080 /* Flush stdio before fork() to avoid cloning buffers */
1081 fflush(NULL);
1083 async->pid = fork();
1084 if (async->pid < 0) {
1085 error_errno("fork (async) failed");
1086 goto error;
1088 if (!async->pid) {
1089 if (need_in)
1090 close(fdin[1]);
1091 if (need_out)
1092 close(fdout[0]);
1093 git_atexit_clear();
1094 process_is_async = 1;
1095 exit(!!async->proc(proc_in, proc_out, async->data));
1098 mark_child_for_cleanup(async->pid, NULL);
1100 if (need_in)
1101 close(fdin[0]);
1102 else if (async->in)
1103 close(async->in);
1105 if (need_out)
1106 close(fdout[1]);
1107 else if (async->out)
1108 close(async->out);
1109 #else
1110 if (!main_thread_set) {
1112 * We assume that the first time that start_async is called
1113 * it is from the main thread.
1115 main_thread_set = 1;
1116 main_thread = pthread_self();
1117 pthread_key_create(&async_key, NULL);
1118 pthread_key_create(&async_die_counter, NULL);
1119 set_die_routine(die_async);
1120 set_die_is_recursing_routine(async_die_is_recursing);
1123 if (proc_in >= 0)
1124 set_cloexec(proc_in);
1125 if (proc_out >= 0)
1126 set_cloexec(proc_out);
1127 async->proc_in = proc_in;
1128 async->proc_out = proc_out;
1130 int err = pthread_create(&async->tid, NULL, run_thread, async);
1131 if (err) {
1132 error_errno("cannot create thread");
1133 goto error;
1136 #endif
1137 return 0;
1139 error:
1140 if (need_in)
1141 close_pair(fdin);
1142 else if (async->in)
1143 close(async->in);
1145 if (need_out)
1146 close_pair(fdout);
1147 else if (async->out)
1148 close(async->out);
1149 return -1;
1152 int finish_async(struct async *async)
1154 #ifdef NO_PTHREADS
1155 return wait_or_whine(async->pid, "child process", 0);
1156 #else
1157 void *ret = (void *)(intptr_t)(-1);
1159 if (pthread_join(async->tid, &ret))
1160 error("pthread_join failed");
1161 return (int)(intptr_t)ret;
1162 #endif
1165 const char *find_hook(const char *name)
1167 static struct strbuf path = STRBUF_INIT;
1169 strbuf_reset(&path);
1170 strbuf_git_path(&path, "hooks/%s", name);
1171 if (access(path.buf, X_OK) < 0) {
1172 #ifdef STRIP_EXTENSION
1173 strbuf_addstr(&path, STRIP_EXTENSION);
1174 if (access(path.buf, X_OK) >= 0)
1175 return path.buf;
1176 #endif
1177 return NULL;
1179 return path.buf;
1182 int run_hook_ve(const char *const *env, const char *name, va_list args)
1184 struct child_process hook = CHILD_PROCESS_INIT;
1185 const char *p;
1187 p = find_hook(name);
1188 if (!p)
1189 return 0;
1191 argv_array_push(&hook.args, p);
1192 while ((p = va_arg(args, const char *)))
1193 argv_array_push(&hook.args, p);
1194 hook.env = env;
1195 hook.no_stdin = 1;
1196 hook.stdout_to_stderr = 1;
1198 return run_command(&hook);
1201 int run_hook_le(const char *const *env, const char *name, ...)
1203 va_list args;
1204 int ret;
1206 va_start(args, name);
1207 ret = run_hook_ve(env, name, args);
1208 va_end(args);
1210 return ret;
1213 struct io_pump {
1214 /* initialized by caller */
1215 int fd;
1216 int type; /* POLLOUT or POLLIN */
1217 union {
1218 struct {
1219 const char *buf;
1220 size_t len;
1221 } out;
1222 struct {
1223 struct strbuf *buf;
1224 size_t hint;
1225 } in;
1226 } u;
1228 /* returned by pump_io */
1229 int error; /* 0 for success, otherwise errno */
1231 /* internal use */
1232 struct pollfd *pfd;
1235 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1237 int pollsize = 0;
1238 int i;
1240 for (i = 0; i < nr; i++) {
1241 struct io_pump *io = &slots[i];
1242 if (io->fd < 0)
1243 continue;
1244 pfd[pollsize].fd = io->fd;
1245 pfd[pollsize].events = io->type;
1246 io->pfd = &pfd[pollsize++];
1249 if (!pollsize)
1250 return 0;
1252 if (poll(pfd, pollsize, -1) < 0) {
1253 if (errno == EINTR)
1254 return 1;
1255 die_errno("poll failed");
1258 for (i = 0; i < nr; i++) {
1259 struct io_pump *io = &slots[i];
1261 if (io->fd < 0)
1262 continue;
1264 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1265 continue;
1267 if (io->type == POLLOUT) {
1268 ssize_t len = xwrite(io->fd,
1269 io->u.out.buf, io->u.out.len);
1270 if (len < 0) {
1271 io->error = errno;
1272 close(io->fd);
1273 io->fd = -1;
1274 } else {
1275 io->u.out.buf += len;
1276 io->u.out.len -= len;
1277 if (!io->u.out.len) {
1278 close(io->fd);
1279 io->fd = -1;
1284 if (io->type == POLLIN) {
1285 ssize_t len = strbuf_read_once(io->u.in.buf,
1286 io->fd, io->u.in.hint);
1287 if (len < 0)
1288 io->error = errno;
1289 if (len <= 0) {
1290 close(io->fd);
1291 io->fd = -1;
1296 return 1;
1299 static int pump_io(struct io_pump *slots, int nr)
1301 struct pollfd *pfd;
1302 int i;
1304 for (i = 0; i < nr; i++)
1305 slots[i].error = 0;
1307 ALLOC_ARRAY(pfd, nr);
1308 while (pump_io_round(slots, nr, pfd))
1309 ; /* nothing */
1310 free(pfd);
1312 /* There may be multiple errno values, so just pick the first. */
1313 for (i = 0; i < nr; i++) {
1314 if (slots[i].error) {
1315 errno = slots[i].error;
1316 return -1;
1319 return 0;
1323 int pipe_command(struct child_process *cmd,
1324 const char *in, size_t in_len,
1325 struct strbuf *out, size_t out_hint,
1326 struct strbuf *err, size_t err_hint)
1328 struct io_pump io[3];
1329 int nr = 0;
1331 if (in)
1332 cmd->in = -1;
1333 if (out)
1334 cmd->out = -1;
1335 if (err)
1336 cmd->err = -1;
1338 if (start_command(cmd) < 0)
1339 return -1;
1341 if (in) {
1342 io[nr].fd = cmd->in;
1343 io[nr].type = POLLOUT;
1344 io[nr].u.out.buf = in;
1345 io[nr].u.out.len = in_len;
1346 nr++;
1348 if (out) {
1349 io[nr].fd = cmd->out;
1350 io[nr].type = POLLIN;
1351 io[nr].u.in.buf = out;
1352 io[nr].u.in.hint = out_hint;
1353 nr++;
1355 if (err) {
1356 io[nr].fd = cmd->err;
1357 io[nr].type = POLLIN;
1358 io[nr].u.in.buf = err;
1359 io[nr].u.in.hint = err_hint;
1360 nr++;
1363 if (pump_io(io, nr) < 0) {
1364 finish_command(cmd); /* throw away exit code */
1365 return -1;
1368 return finish_command(cmd);
1371 enum child_state {
1372 GIT_CP_FREE,
1373 GIT_CP_WORKING,
1374 GIT_CP_WAIT_CLEANUP,
1377 struct parallel_processes {
1378 void *data;
1380 int max_processes;
1381 int nr_processes;
1383 get_next_task_fn get_next_task;
1384 start_failure_fn start_failure;
1385 task_finished_fn task_finished;
1387 struct {
1388 enum child_state state;
1389 struct child_process process;
1390 struct strbuf err;
1391 void *data;
1392 } *children;
1394 * The struct pollfd is logically part of *children,
1395 * but the system call expects it as its own array.
1397 struct pollfd *pfd;
1399 unsigned shutdown : 1;
1401 int output_owner;
1402 struct strbuf buffered_output; /* of finished children */
1405 static int default_start_failure(struct strbuf *out,
1406 void *pp_cb,
1407 void *pp_task_cb)
1409 return 0;
1412 static int default_task_finished(int result,
1413 struct strbuf *out,
1414 void *pp_cb,
1415 void *pp_task_cb)
1417 return 0;
1420 static void kill_children(struct parallel_processes *pp, int signo)
1422 int i, n = pp->max_processes;
1424 for (i = 0; i < n; i++)
1425 if (pp->children[i].state == GIT_CP_WORKING)
1426 kill(pp->children[i].process.pid, signo);
1429 static struct parallel_processes *pp_for_signal;
1431 static void handle_children_on_signal(int signo)
1433 kill_children(pp_for_signal, signo);
1434 sigchain_pop(signo);
1435 raise(signo);
1438 static void pp_init(struct parallel_processes *pp,
1439 int n,
1440 get_next_task_fn get_next_task,
1441 start_failure_fn start_failure,
1442 task_finished_fn task_finished,
1443 void *data)
1445 int i;
1447 if (n < 1)
1448 n = online_cpus();
1450 pp->max_processes = n;
1452 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1454 pp->data = data;
1455 if (!get_next_task)
1456 die("BUG: you need to specify a get_next_task function");
1457 pp->get_next_task = get_next_task;
1459 pp->start_failure = start_failure ? start_failure : default_start_failure;
1460 pp->task_finished = task_finished ? task_finished : default_task_finished;
1462 pp->nr_processes = 0;
1463 pp->output_owner = 0;
1464 pp->shutdown = 0;
1465 pp->children = xcalloc(n, sizeof(*pp->children));
1466 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1467 strbuf_init(&pp->buffered_output, 0);
1469 for (i = 0; i < n; i++) {
1470 strbuf_init(&pp->children[i].err, 0);
1471 child_process_init(&pp->children[i].process);
1472 pp->pfd[i].events = POLLIN | POLLHUP;
1473 pp->pfd[i].fd = -1;
1476 pp_for_signal = pp;
1477 sigchain_push_common(handle_children_on_signal);
1480 static void pp_cleanup(struct parallel_processes *pp)
1482 int i;
1484 trace_printf("run_processes_parallel: done");
1485 for (i = 0; i < pp->max_processes; i++) {
1486 strbuf_release(&pp->children[i].err);
1487 child_process_clear(&pp->children[i].process);
1490 free(pp->children);
1491 free(pp->pfd);
1494 * When get_next_task added messages to the buffer in its last
1495 * iteration, the buffered output is non empty.
1497 strbuf_write(&pp->buffered_output, stderr);
1498 strbuf_release(&pp->buffered_output);
1500 sigchain_pop_common();
1503 /* returns
1504 * 0 if a new task was started.
1505 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1506 * problem with starting a new command)
1507 * <0 no new job was started, user wishes to shutdown early. Use negative code
1508 * to signal the children.
1510 static int pp_start_one(struct parallel_processes *pp)
1512 int i, code;
1514 for (i = 0; i < pp->max_processes; i++)
1515 if (pp->children[i].state == GIT_CP_FREE)
1516 break;
1517 if (i == pp->max_processes)
1518 die("BUG: bookkeeping is hard");
1520 code = pp->get_next_task(&pp->children[i].process,
1521 &pp->children[i].err,
1522 pp->data,
1523 &pp->children[i].data);
1524 if (!code) {
1525 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1526 strbuf_reset(&pp->children[i].err);
1527 return 1;
1529 pp->children[i].process.err = -1;
1530 pp->children[i].process.stdout_to_stderr = 1;
1531 pp->children[i].process.no_stdin = 1;
1533 if (start_command(&pp->children[i].process)) {
1534 code = pp->start_failure(&pp->children[i].err,
1535 pp->data,
1536 &pp->children[i].data);
1537 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1538 strbuf_reset(&pp->children[i].err);
1539 if (code)
1540 pp->shutdown = 1;
1541 return code;
1544 pp->nr_processes++;
1545 pp->children[i].state = GIT_CP_WORKING;
1546 pp->pfd[i].fd = pp->children[i].process.err;
1547 return 0;
1550 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1552 int i;
1554 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1555 if (errno == EINTR)
1556 continue;
1557 pp_cleanup(pp);
1558 die_errno("poll");
1561 /* Buffer output from all pipes. */
1562 for (i = 0; i < pp->max_processes; i++) {
1563 if (pp->children[i].state == GIT_CP_WORKING &&
1564 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1565 int n = strbuf_read_once(&pp->children[i].err,
1566 pp->children[i].process.err, 0);
1567 if (n == 0) {
1568 close(pp->children[i].process.err);
1569 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1570 } else if (n < 0)
1571 if (errno != EAGAIN)
1572 die_errno("read");
1577 static void pp_output(struct parallel_processes *pp)
1579 int i = pp->output_owner;
1580 if (pp->children[i].state == GIT_CP_WORKING &&
1581 pp->children[i].err.len) {
1582 strbuf_write(&pp->children[i].err, stderr);
1583 strbuf_reset(&pp->children[i].err);
1587 static int pp_collect_finished(struct parallel_processes *pp)
1589 int i, code;
1590 int n = pp->max_processes;
1591 int result = 0;
1593 while (pp->nr_processes > 0) {
1594 for (i = 0; i < pp->max_processes; i++)
1595 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1596 break;
1597 if (i == pp->max_processes)
1598 break;
1600 code = finish_command(&pp->children[i].process);
1602 code = pp->task_finished(code,
1603 &pp->children[i].err, pp->data,
1604 &pp->children[i].data);
1606 if (code)
1607 result = code;
1608 if (code < 0)
1609 break;
1611 pp->nr_processes--;
1612 pp->children[i].state = GIT_CP_FREE;
1613 pp->pfd[i].fd = -1;
1614 child_process_init(&pp->children[i].process);
1616 if (i != pp->output_owner) {
1617 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1618 strbuf_reset(&pp->children[i].err);
1619 } else {
1620 strbuf_write(&pp->children[i].err, stderr);
1621 strbuf_reset(&pp->children[i].err);
1623 /* Output all other finished child processes */
1624 strbuf_write(&pp->buffered_output, stderr);
1625 strbuf_reset(&pp->buffered_output);
1628 * Pick next process to output live.
1629 * NEEDSWORK:
1630 * For now we pick it randomly by doing a round
1631 * robin. Later we may want to pick the one with
1632 * the most output or the longest or shortest
1633 * running process time.
1635 for (i = 0; i < n; i++)
1636 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1637 break;
1638 pp->output_owner = (pp->output_owner + i) % n;
1641 return result;
1644 int run_processes_parallel(int n,
1645 get_next_task_fn get_next_task,
1646 start_failure_fn start_failure,
1647 task_finished_fn task_finished,
1648 void *pp_cb)
1650 int i, code;
1651 int output_timeout = 100;
1652 int spawn_cap = 4;
1653 struct parallel_processes pp;
1655 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1656 while (1) {
1657 for (i = 0;
1658 i < spawn_cap && !pp.shutdown &&
1659 pp.nr_processes < pp.max_processes;
1660 i++) {
1661 code = pp_start_one(&pp);
1662 if (!code)
1663 continue;
1664 if (code < 0) {
1665 pp.shutdown = 1;
1666 kill_children(&pp, -code);
1668 break;
1670 if (!pp.nr_processes)
1671 break;
1672 pp_buffer_stderr(&pp, output_timeout);
1673 pp_output(&pp);
1674 code = pp_collect_finished(&pp);
1675 if (code) {
1676 pp.shutdown = 1;
1677 if (code < 0)
1678 kill_children(&pp, -code);
1682 pp_cleanup(&pp);
1683 return 0;