2 #include "run-command.h"
5 #include "argv-array.h"
6 #include "thread-utils.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 {
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) {
42 "trace: run_command: running exit handler for pid %"
43 PRIuMAX, (uintmax_t)p->pid
45 process->clean_on_exit_handler(process);
51 if (p->process && p->process->wait_after_clean) {
52 p->next = children_to_wait_for;
53 children_to_wait_for = 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 */
72 static void cleanup_children_on_signal(int sig)
74 cleanup_children(sig, 1);
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));
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;
114 static inline void close_pair(int fd[2])
120 int is_executable(const char *name)
124 if (stat(name, &st) || /* stat, not lstat */
125 !S_ISREG(st.st_mode))
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"))
142 * Now that we know it does not have an executable extension,
143 * peek into the file instead.
147 int fd = open(name, O_RDONLY);
148 st.st_mode &= ~S_IXUSR;
150 n = read(fd, buf, 2);
152 /* look for a she-bang */
153 if (!strcmp(buf, "#!"))
154 st.st_mode |= S_IXUSR;
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
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
179 static char *locate_in_PATH(const char *file)
181 const char *p = getenv("PATH");
182 struct strbuf buf = STRBUF_INIT;
188 const char *end = strchrnul(p, ':');
192 /* POSIX specifies an empty entry as the current directory. */
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);
207 strbuf_release(&buf);
211 static int exists_in_PATH(const char *file)
213 char *r = locate_in_PATH(file);
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
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, '/'))
243 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
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);
252 argv_array_push(out, "sh");
254 argv_array_push(out, "-c");
257 * If we have no extra arguments, we do not even need to
258 * bother with the "$@" magic.
261 argv_array_push(out, argv[0]);
263 argv_array_pushf(out, "%s \"$@\"", argv[0]);
266 argv_array_pushv(out, argv);
270 #ifndef GIT_WINDOWS_NATIVE
271 static int child_notifier = -1;
277 CHILD_ERR_SIGPROCMASK,
284 enum child_errcode err;
285 int syserr; /* errno */
288 static void child_die(enum child_errcode err)
290 struct child_err buf;
295 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
296 xwrite(child_notifier, &buf, sizeof(buf));
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)
309 child_die(CHILD_ERR_CLOSE);
312 static void child_close_pair(int fd[2])
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);
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;
356 case CHILD_ERR_CHDIR:
357 error_errno("exec '%s': cd to '%s' failed",
358 cmd->argv[0], cmd->dir);
361 error_errno("dup2() in child failed");
363 case CHILD_ERR_CLOSE:
364 error_errno("close() in child failed");
366 case CHILD_ERR_SIGPROCMASK:
367 error_errno("sigprocmask failed restoring signals");
369 case CHILD_ERR_ENOENT:
370 error_errno("cannot run %s", cmd->argv[0]);
372 case CHILD_ERR_SILENT:
374 case CHILD_ERR_ERRNO:
375 error_errno("cannot exec '%s'", cmd->argv[0]);
378 set_error_routine(old_errfn);
381 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
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);
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);
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]);
410 free((char *)out->argv[1]);
411 out->argv[1] = program;
416 static char **prep_childenv(const char *const *deltaenv)
418 extern char **environ;
420 struct string_list env = STRING_LIST_INIT_DUP;
421 struct strbuf key = STRBUF_INIT;
422 const char *const *p;
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, '=');
431 strbuf_add(&key, *p, equals - *p);
432 string_list_append(&env, key.buf)->util = (void *) *p;
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, '=');
444 /* ('key=value'), insert or replace entry */
446 strbuf_add(&key, *p, equals - *p);
447 string_list_insert(&env, key.buf)->util = (void *) *p;
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);
465 struct atfork_state {
473 static void bug_die(int err, const char *msg)
477 die_errno("BUG: %s", msg);
482 static void atfork_prepare(struct atfork_state *as)
486 if (sigfillset(&all))
487 die_errno("sigfillset");
489 if (sigprocmask(SIG_SETMASK, &all, &as->old))
490 die_errno("sigprocmask");
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");
499 static void atfork_parent(struct atfork_state *as)
502 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
503 die_errno("sigprocmask");
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");
511 #endif /* GIT_WINDOWS_NATIVE */
513 static inline void set_cloexec(int fd)
515 int flags = fcntl(fd, F_GETFD);
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;
524 int failed_errno = 0;
526 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
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.
546 } else if (WIFEXITED(status)) {
547 code = WEXITSTATUS(status);
549 error("waitpid is confused (%s)", argv0);
552 clear_child_for_cleanup(pid);
554 errno = failed_errno;
558 int start_command(struct child_process *cmd)
560 int need_in, need_out, need_err;
561 int fdin[2], fdout[2], fderr[2];
566 cmd->argv = cmd->args.argv;
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;
577 if (pipe(fdin) < 0) {
578 failed_errno = errno;
581 str = "standard input";
587 need_out = !cmd->no_stdout
588 && !cmd->stdout_to_stderr
591 if (pipe(fdout) < 0) {
592 failed_errno = errno;
597 str = "standard output";
603 need_err = !cmd->no_stderr && cmd->err < 0;
605 if (pipe(fderr) < 0) {
606 failed_errno = errno;
615 str = "standard error";
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;
626 trace_argv_printf(cmd->argv, "trace: run_command:");
629 #ifndef GIT_WINDOWS_NATIVE
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);
644 die_errno(_("open /dev/null failed"));
645 set_cloexec(null_fd);
648 prepare_cmd(&argv, cmd);
649 childenv = prep_childenv(cmd->env);
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.
662 failed_errno = errno;
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];
678 child_dup2(null_fd, 0);
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);
688 child_dup2(null_fd, 2);
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);
698 child_dup2(null_fd, 1);
699 else if (cmd->stdout_to_stderr)
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);
742 child_die(CHILD_ERR_ERRNO);
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;
769 close(notify_pipe[0]);
773 argv_array_clear(&argv);
778 int fhin = 0, fhout = 1, fherr = 2;
779 const char **sargv = cmd->argv;
780 struct argv_array nargv = ARGV_ARRAY_INIT;
783 fhin = open("/dev/null", O_RDWR);
790 fherr = open("/dev/null", O_RDWR);
792 fherr = dup(fderr[1]);
793 else if (cmd->err > 2)
794 fherr = dup(cmd->err);
797 fhout = open("/dev/null", O_RDWR);
798 else if (cmd->stdout_to_stderr)
801 fhout = dup(fdout[1]);
802 else if (cmd->out > 1)
803 fhout = dup(cmd->out);
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);
842 child_process_clear(cmd);
843 errno = failed_errno;
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);
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)
882 if (cmd->out < 0 || cmd->err < 0)
883 die("BUG: run_command with a pipe can cause deadlock");
885 code = start_command(cmd);
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;
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;
908 return run_command(&cmd);
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;
922 if (async->isolate_sigpipe) {
925 sigaddset(&mask, SIGPIPE);
926 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
927 ret = error("unable to block SIGPIPE in async thread");
932 pthread_setspecific(async_key, async);
933 ret = async->proc(async->proc_in, async->proc_out, async->data);
937 static NORETURN void die_async(const char *err, va_list params)
939 vreportf("fatal: ", err, params);
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);
953 static int async_die_is_recursing(void)
955 void *ret = pthread_getspecific(async_die_counter);
956 pthread_setspecific(async_die_counter, (void *)1);
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);
975 void (**handlers)(void);
980 static int git_atexit_installed;
982 static void git_atexit_dispatch(void)
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;
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))
1005 git_atexit_installed = 1;
1009 #define atexit git_atexit
1011 static int process_is_async;
1014 return process_is_async;
1017 static void NORETURN async_exit(int code)
1024 void check_pipe(int err)
1030 signal(SIGPIPE, SIG_DFL);
1032 /* Should never happen, but just in case... */
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;
1045 if (pipe(fdin) < 0) {
1048 return error_errno("cannot create pipe");
1050 async->in = fdin[1];
1053 need_out = async->out < 0;
1055 if (pipe(fdout) < 0) {
1060 return error_errno("cannot create pipe");
1062 async->out = fdout[0];
1068 proc_in = async->in;
1073 proc_out = fdout[1];
1074 else if (async->out)
1075 proc_out = async->out;
1080 /* Flush stdio before fork() to avoid cloning buffers */
1083 async->pid = fork();
1084 if (async->pid < 0) {
1085 error_errno("fork (async) failed");
1094 process_is_async = 1;
1095 exit(!!async->proc(proc_in, proc_out, async->data));
1098 mark_child_for_cleanup(async->pid, NULL);
1107 else if (async->out)
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);
1124 set_cloexec(proc_in);
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);
1132 error_errno("cannot create thread");
1147 else if (async->out)
1152 int finish_async(struct async *async)
1155 return wait_or_whine(async->pid, "child process", 0);
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;
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)
1182 int run_hook_ve(const char *const *env, const char *name, va_list args)
1184 struct child_process hook = CHILD_PROCESS_INIT;
1187 p = find_hook(name);
1191 argv_array_push(&hook.args, p);
1192 while ((p = va_arg(args, const char *)))
1193 argv_array_push(&hook.args, p);
1196 hook.stdout_to_stderr = 1;
1198 return run_command(&hook);
1201 int run_hook_le(const char *const *env, const char *name, ...)
1206 va_start(args, name);
1207 ret = run_hook_ve(env, name, args);
1214 /* initialized by caller */
1216 int type; /* POLLOUT or POLLIN */
1228 /* returned by pump_io */
1229 int error; /* 0 for success, otherwise errno */
1235 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1240 for (i = 0; i < nr; i++) {
1241 struct io_pump *io = &slots[i];
1244 pfd[pollsize].fd = io->fd;
1245 pfd[pollsize].events = io->type;
1246 io->pfd = &pfd[pollsize++];
1252 if (poll(pfd, pollsize, -1) < 0) {
1255 die_errno("poll failed");
1258 for (i = 0; i < nr; i++) {
1259 struct io_pump *io = &slots[i];
1264 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1267 if (io->type == POLLOUT) {
1268 ssize_t len = xwrite(io->fd,
1269 io->u.out.buf, io->u.out.len);
1275 io->u.out.buf += len;
1276 io->u.out.len -= len;
1277 if (!io->u.out.len) {
1284 if (io->type == POLLIN) {
1285 ssize_t len = strbuf_read_once(io->u.in.buf,
1286 io->fd, io->u.in.hint);
1299 static int pump_io(struct io_pump *slots, int nr)
1304 for (i = 0; i < nr; i++)
1307 ALLOC_ARRAY(pfd, nr);
1308 while (pump_io_round(slots, nr, 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;
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];
1338 if (start_command(cmd) < 0)
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;
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;
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;
1363 if (pump_io(io, nr) < 0) {
1364 finish_command(cmd); /* throw away exit code */
1368 return finish_command(cmd);
1374 GIT_CP_WAIT_CLEANUP,
1377 struct parallel_processes {
1383 get_next_task_fn get_next_task;
1384 start_failure_fn start_failure;
1385 task_finished_fn task_finished;
1388 enum child_state state;
1389 struct child_process process;
1394 * The struct pollfd is logically part of *children,
1395 * but the system call expects it as its own array.
1399 unsigned shutdown : 1;
1402 struct strbuf buffered_output; /* of finished children */
1405 static int default_start_failure(struct strbuf *out,
1412 static int default_task_finished(int result,
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);
1438 static void pp_init(struct parallel_processes *pp,
1440 get_next_task_fn get_next_task,
1441 start_failure_fn start_failure,
1442 task_finished_fn task_finished,
1450 pp->max_processes = n;
1452 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
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;
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;
1477 sigchain_push_common(handle_children_on_signal);
1480 static void pp_cleanup(struct parallel_processes *pp)
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);
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();
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)
1514 for (i = 0; i < pp->max_processes; i++)
1515 if (pp->children[i].state == GIT_CP_FREE)
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,
1523 &pp->children[i].data);
1525 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1526 strbuf_reset(&pp->children[i].err);
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,
1536 pp->children[i].data);
1537 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1538 strbuf_reset(&pp->children[i].err);
1545 pp->children[i].state = GIT_CP_WORKING;
1546 pp->pfd[i].fd = pp->children[i].process.err;
1550 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1554 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
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);
1568 close(pp->children[i].process.err);
1569 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1571 if (errno != EAGAIN)
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)
1590 int n = pp->max_processes;
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)
1597 if (i == pp->max_processes)
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);
1612 pp->children[i].state = GIT_CP_FREE;
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);
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.
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)
1638 pp->output_owner = (pp->output_owner + i) % n;
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,
1651 int output_timeout = 100;
1653 struct parallel_processes pp;
1655 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1658 i < spawn_cap && !pp.shutdown &&
1659 pp.nr_processes < pp.max_processes;
1661 code = pp_start_one(&pp);
1666 kill_children(&pp, -code);
1670 if (!pp.nr_processes)
1672 pp_buffer_stderr(&pp, output_timeout);
1674 code = pp_collect_finished(&pp);
1678 kill_children(&pp, -code);