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 static char *locate_in_PATH(const char *file)
122 const char *p = getenv("PATH");
123 struct strbuf buf = STRBUF_INIT;
129 const char *end = strchrnul(p, ':');
133 /* POSIX specifies an empty entry as the current directory. */
135 strbuf_add(&buf, p, end - p);
136 strbuf_addch(&buf, '/');
138 strbuf_addstr(&buf, file);
140 if (!access(buf.buf, F_OK))
141 return strbuf_detach(&buf, NULL);
148 strbuf_release(&buf);
152 static int exists_in_PATH(const char *file)
154 char *r = locate_in_PATH(file);
159 int sane_execvp(const char *file, char * const argv[])
161 if (!execvp(file, argv))
162 return 0; /* cannot happen ;-) */
165 * When a command can't be found because one of the directories
166 * listed in $PATH is unsearchable, execvp reports EACCES, but
167 * careful usability testing (read: analysis of occasional bug
168 * reports) reveals that "No such file or directory" is more
171 * We avoid commands with "/", because execvp will not do $PATH
172 * lookups in that case.
174 * The reassignment of EACCES to errno looks like a no-op below,
175 * but we need to protect against exists_in_PATH overwriting errno.
177 if (errno == EACCES && !strchr(file, '/'))
178 errno = exists_in_PATH(file) ? EACCES : ENOENT;
179 else if (errno == ENOTDIR && !strchr(file, '/'))
184 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
187 die("BUG: shell command is empty");
189 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
190 #ifndef GIT_WINDOWS_NATIVE
191 argv_array_push(out, SHELL_PATH);
193 argv_array_push(out, "sh");
195 argv_array_push(out, "-c");
198 * If we have no extra arguments, we do not even need to
199 * bother with the "$@" magic.
202 argv_array_push(out, argv[0]);
204 argv_array_pushf(out, "%s \"$@\"", argv[0]);
207 argv_array_pushv(out, argv);
211 #ifndef GIT_WINDOWS_NATIVE
212 static int child_notifier = -1;
218 CHILD_ERR_SIGPROCMASK,
225 enum child_errcode err;
226 int syserr; /* errno */
229 static void child_die(enum child_errcode err)
231 struct child_err buf;
236 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
237 xwrite(child_notifier, &buf, sizeof(buf));
241 static void child_dup2(int fd, int to)
243 if (dup2(fd, to) < 0)
244 child_die(CHILD_ERR_DUP2);
247 static void child_close(int fd)
250 child_die(CHILD_ERR_CLOSE);
253 static void child_close_pair(int fd[2])
260 * parent will make it look like the child spewed a fatal error and died
261 * this is needed to prevent changes to t0061.
263 static void fake_fatal(const char *err, va_list params)
265 vreportf("fatal: ", err, params);
268 static void child_error_fn(const char *err, va_list params)
270 const char msg[] = "error() should not be called in child\n";
271 xwrite(2, msg, sizeof(msg) - 1);
274 static void child_warn_fn(const char *err, va_list params)
276 const char msg[] = "warn() should not be called in child\n";
277 xwrite(2, msg, sizeof(msg) - 1);
280 static void NORETURN child_die_fn(const char *err, va_list params)
282 const char msg[] = "die() should not be called in child\n";
283 xwrite(2, msg, sizeof(msg) - 1);
287 /* this runs in the parent process */
288 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
290 static void (*old_errfn)(const char *err, va_list params);
292 old_errfn = get_error_routine();
293 set_error_routine(fake_fatal);
294 errno = cerr->syserr;
297 case CHILD_ERR_CHDIR:
298 error_errno("exec '%s': cd to '%s' failed",
299 cmd->argv[0], cmd->dir);
302 error_errno("dup2() in child failed");
304 case CHILD_ERR_CLOSE:
305 error_errno("close() in child failed");
307 case CHILD_ERR_SIGPROCMASK:
308 error_errno("sigprocmask failed restoring signals");
310 case CHILD_ERR_ENOENT:
311 error_errno("cannot run %s", cmd->argv[0]);
313 case CHILD_ERR_SILENT:
315 case CHILD_ERR_ERRNO:
316 error_errno("cannot exec '%s'", cmd->argv[0]);
319 set_error_routine(old_errfn);
322 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
325 die("BUG: command is empty");
328 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
329 * attempt to interpret the command with 'sh'.
331 argv_array_push(out, SHELL_PATH);
334 argv_array_push(out, "git");
335 argv_array_pushv(out, cmd->argv);
336 } else if (cmd->use_shell) {
337 prepare_shell_cmd(out, cmd->argv);
339 argv_array_pushv(out, cmd->argv);
343 * If there are no '/' characters in the command then perform a path
344 * lookup and use the resolved path as the command to exec. If there
345 * are no '/' characters or if the command wasn't found in the path,
346 * have exec attempt to invoke the command directly.
348 if (!strchr(out->argv[1], '/')) {
349 char *program = locate_in_PATH(out->argv[1]);
351 free((char *)out->argv[1]);
352 out->argv[1] = program;
357 static char **prep_childenv(const char *const *deltaenv)
359 extern char **environ;
361 struct string_list env = STRING_LIST_INIT_DUP;
362 struct strbuf key = STRBUF_INIT;
363 const char *const *p;
366 /* Construct a sorted string list consisting of the current environ */
367 for (p = (const char *const *) environ; p && *p; p++) {
368 const char *equals = strchr(*p, '=');
372 strbuf_add(&key, *p, equals - *p);
373 string_list_append(&env, key.buf)->util = (void *) *p;
375 string_list_append(&env, *p)->util = (void *) *p;
378 string_list_sort(&env);
380 /* Merge in 'deltaenv' with the current environ */
381 for (p = deltaenv; p && *p; p++) {
382 const char *equals = strchr(*p, '=');
385 /* ('key=value'), insert or replace entry */
387 strbuf_add(&key, *p, equals - *p);
388 string_list_insert(&env, key.buf)->util = (void *) *p;
390 /* otherwise ('key') remove existing entry */
391 string_list_remove(&env, *p, 0);
395 /* Create an array of 'char *' to be used as the childenv */
396 childenv = xmalloc((env.nr + 1) * sizeof(char *));
397 for (i = 0; i < env.nr; i++)
398 childenv[i] = env.items[i].util;
399 childenv[env.nr] = NULL;
401 string_list_clear(&env, 0);
402 strbuf_release(&key);
406 struct atfork_state {
414 static void bug_die(int err, const char *msg)
418 die_errno("BUG: %s", msg);
423 static void atfork_prepare(struct atfork_state *as)
427 if (sigfillset(&all))
428 die_errno("sigfillset");
430 if (sigprocmask(SIG_SETMASK, &all, &as->old))
431 die_errno("sigprocmask");
433 bug_die(pthread_sigmask(SIG_SETMASK, &all, &as->old),
434 "blocking all signals");
435 bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
436 "disabling cancellation");
440 static void atfork_parent(struct atfork_state *as)
443 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
444 die_errno("sigprocmask");
446 bug_die(pthread_setcancelstate(as->cs, NULL),
447 "re-enabling cancellation");
448 bug_die(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
449 "restoring signal mask");
452 #endif /* GIT_WINDOWS_NATIVE */
454 static inline void set_cloexec(int fd)
456 int flags = fcntl(fd, F_GETFD);
458 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
461 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
463 int status, code = -1;
465 int failed_errno = 0;
467 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
473 failed_errno = errno;
474 error_errno("waitpid for %s failed", argv0);
475 } else if (waiting != pid) {
476 error("waitpid is confused (%s)", argv0);
477 } else if (WIFSIGNALED(status)) {
478 code = WTERMSIG(status);
479 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
480 error("%s died of signal %d", argv0, code);
482 * This return value is chosen so that code & 0xff
483 * mimics the exit code that a POSIX shell would report for
484 * a program that died from this signal.
487 } else if (WIFEXITED(status)) {
488 code = WEXITSTATUS(status);
490 error("waitpid is confused (%s)", argv0);
493 clear_child_for_cleanup(pid);
495 errno = failed_errno;
499 int start_command(struct child_process *cmd)
501 int need_in, need_out, need_err;
502 int fdin[2], fdout[2], fderr[2];
507 cmd->argv = cmd->args.argv;
509 cmd->env = cmd->env_array.argv;
512 * In case of errors we must keep the promise to close FDs
513 * that have been passed in via ->in and ->out.
516 need_in = !cmd->no_stdin && cmd->in < 0;
518 if (pipe(fdin) < 0) {
519 failed_errno = errno;
522 str = "standard input";
528 need_out = !cmd->no_stdout
529 && !cmd->stdout_to_stderr
532 if (pipe(fdout) < 0) {
533 failed_errno = errno;
538 str = "standard output";
544 need_err = !cmd->no_stderr && cmd->err < 0;
546 if (pipe(fderr) < 0) {
547 failed_errno = errno;
556 str = "standard error";
558 error("cannot create %s pipe for %s: %s",
559 str, cmd->argv[0], strerror(failed_errno));
560 child_process_clear(cmd);
561 errno = failed_errno;
567 trace_argv_printf(cmd->argv, "trace: run_command:");
570 #ifndef GIT_WINDOWS_NATIVE
575 struct argv_array argv = ARGV_ARRAY_INIT;
576 struct child_err cerr;
577 struct atfork_state as;
579 if (pipe(notify_pipe))
580 notify_pipe[0] = notify_pipe[1] = -1;
582 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
583 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
585 die_errno(_("open /dev/null failed"));
586 set_cloexec(null_fd);
589 prepare_cmd(&argv, cmd);
590 childenv = prep_childenv(cmd->env);
594 * NOTE: In order to prevent deadlocking when using threads special
595 * care should be taken with the function calls made in between the
596 * fork() and exec() calls. No calls should be made to functions which
597 * require acquiring a lock (e.g. malloc) as the lock could have been
598 * held by another thread at the time of forking, causing the lock to
599 * never be released in the child process. This means only
600 * Async-Signal-Safe functions are permitted in the child.
603 failed_errno = errno;
607 * Ensure the default die/error/warn routines do not get
608 * called, they can take stdio locks and malloc.
610 set_die_routine(child_die_fn);
611 set_error_routine(child_error_fn);
612 set_warn_routine(child_warn_fn);
614 close(notify_pipe[0]);
615 set_cloexec(notify_pipe[1]);
616 child_notifier = notify_pipe[1];
619 child_dup2(null_fd, 0);
621 child_dup2(fdin[0], 0);
622 child_close_pair(fdin);
623 } else if (cmd->in) {
624 child_dup2(cmd->in, 0);
625 child_close(cmd->in);
629 child_dup2(null_fd, 2);
631 child_dup2(fderr[1], 2);
632 child_close_pair(fderr);
633 } else if (cmd->err > 1) {
634 child_dup2(cmd->err, 2);
635 child_close(cmd->err);
639 child_dup2(null_fd, 1);
640 else if (cmd->stdout_to_stderr)
643 child_dup2(fdout[1], 1);
644 child_close_pair(fdout);
645 } else if (cmd->out > 1) {
646 child_dup2(cmd->out, 1);
647 child_close(cmd->out);
650 if (cmd->dir && chdir(cmd->dir))
651 child_die(CHILD_ERR_CHDIR);
654 * restore default signal handlers here, in case
655 * we catch a signal right before execve below
657 for (sig = 1; sig < NSIG; sig++) {
658 /* ignored signals get reset to SIG_DFL on execve */
659 if (signal(sig, SIG_DFL) == SIG_IGN)
660 signal(sig, SIG_IGN);
663 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
664 child_die(CHILD_ERR_SIGPROCMASK);
667 * Attempt to exec using the command and arguments starting at
668 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
669 * be used in the event exec failed with ENOEXEC at which point
670 * we will try to interpret the command using 'sh'.
672 execve(argv.argv[1], (char *const *) argv.argv + 1,
673 (char *const *) childenv);
674 if (errno == ENOEXEC)
675 execve(argv.argv[0], (char *const *) argv.argv,
676 (char *const *) childenv);
678 if (errno == ENOENT) {
679 if (cmd->silent_exec_failure)
680 child_die(CHILD_ERR_SILENT);
681 child_die(CHILD_ERR_ENOENT);
683 child_die(CHILD_ERR_ERRNO);
688 error_errno("cannot fork() for %s", cmd->argv[0]);
689 else if (cmd->clean_on_exit)
690 mark_child_for_cleanup(cmd->pid, cmd);
693 * Wait for child's exec. If the exec succeeds (or if fork()
694 * failed), EOF is seen immediately by the parent. Otherwise, the
695 * child process sends a child_err struct.
696 * Note that use of this infrastructure is completely advisory,
697 * therefore, we keep error checks minimal.
699 close(notify_pipe[1]);
700 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
702 * At this point we know that fork() succeeded, but exec()
703 * failed. Errors have been reported to our stderr.
705 wait_or_whine(cmd->pid, cmd->argv[0], 0);
706 child_err_spew(cmd, &cerr);
707 failed_errno = errno;
710 close(notify_pipe[0]);
714 argv_array_clear(&argv);
719 int fhin = 0, fhout = 1, fherr = 2;
720 const char **sargv = cmd->argv;
721 struct argv_array nargv = ARGV_ARRAY_INIT;
724 fhin = open("/dev/null", O_RDWR);
731 fherr = open("/dev/null", O_RDWR);
733 fherr = dup(fderr[1]);
734 else if (cmd->err > 2)
735 fherr = dup(cmd->err);
738 fhout = open("/dev/null", O_RDWR);
739 else if (cmd->stdout_to_stderr)
742 fhout = dup(fdout[1]);
743 else if (cmd->out > 1)
744 fhout = dup(cmd->out);
747 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
748 else if (cmd->use_shell)
749 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
751 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
752 cmd->dir, fhin, fhout, fherr);
753 failed_errno = errno;
754 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
755 error_errno("cannot spawn %s", cmd->argv[0]);
756 if (cmd->clean_on_exit && cmd->pid >= 0)
757 mark_child_for_cleanup(cmd->pid, cmd);
759 argv_array_clear(&nargv);
783 child_process_clear(cmd);
784 errno = failed_errno;
806 int finish_command(struct child_process *cmd)
808 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
809 child_process_clear(cmd);
813 int finish_command_in_signal(struct child_process *cmd)
815 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
819 int run_command(struct child_process *cmd)
823 if (cmd->out < 0 || cmd->err < 0)
824 die("BUG: run_command with a pipe can cause deadlock");
826 code = start_command(cmd);
829 return finish_command(cmd);
832 int run_command_v_opt(const char **argv, int opt)
834 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
837 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
839 struct child_process cmd = CHILD_PROCESS_INIT;
841 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
842 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
843 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
844 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
845 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
846 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
849 return run_command(&cmd);
853 static pthread_t main_thread;
854 static int main_thread_set;
855 static pthread_key_t async_key;
856 static pthread_key_t async_die_counter;
858 static void *run_thread(void *data)
860 struct async *async = data;
863 if (async->isolate_sigpipe) {
866 sigaddset(&mask, SIGPIPE);
867 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
868 ret = error("unable to block SIGPIPE in async thread");
873 pthread_setspecific(async_key, async);
874 ret = async->proc(async->proc_in, async->proc_out, async->data);
878 static NORETURN void die_async(const char *err, va_list params)
880 vreportf("fatal: ", err, params);
883 struct async *async = pthread_getspecific(async_key);
884 if (async->proc_in >= 0)
885 close(async->proc_in);
886 if (async->proc_out >= 0)
887 close(async->proc_out);
888 pthread_exit((void *)128);
894 static int async_die_is_recursing(void)
896 void *ret = pthread_getspecific(async_die_counter);
897 pthread_setspecific(async_die_counter, (void *)1);
903 if (!main_thread_set)
904 return 0; /* no asyncs started yet */
905 return !pthread_equal(main_thread, pthread_self());
908 static void NORETURN async_exit(int code)
910 pthread_exit((void *)(intptr_t)code);
916 void (**handlers)(void);
921 static int git_atexit_installed;
923 static void git_atexit_dispatch(void)
927 for (i=git_atexit_hdlrs.nr ; i ; i--)
928 git_atexit_hdlrs.handlers[i-1]();
931 static void git_atexit_clear(void)
933 free(git_atexit_hdlrs.handlers);
934 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
935 git_atexit_installed = 0;
939 int git_atexit(void (*handler)(void))
941 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
942 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
943 if (!git_atexit_installed) {
944 if (atexit(&git_atexit_dispatch))
946 git_atexit_installed = 1;
950 #define atexit git_atexit
952 static int process_is_async;
955 return process_is_async;
958 static void NORETURN async_exit(int code)
965 void check_pipe(int err)
971 signal(SIGPIPE, SIG_DFL);
973 /* Should never happen, but just in case... */
978 int start_async(struct async *async)
980 int need_in, need_out;
981 int fdin[2], fdout[2];
982 int proc_in, proc_out;
984 need_in = async->in < 0;
986 if (pipe(fdin) < 0) {
989 return error_errno("cannot create pipe");
994 need_out = async->out < 0;
996 if (pipe(fdout) < 0) {
1001 return error_errno("cannot create pipe");
1003 async->out = fdout[0];
1009 proc_in = async->in;
1014 proc_out = fdout[1];
1015 else if (async->out)
1016 proc_out = async->out;
1021 /* Flush stdio before fork() to avoid cloning buffers */
1024 async->pid = fork();
1025 if (async->pid < 0) {
1026 error_errno("fork (async) failed");
1035 process_is_async = 1;
1036 exit(!!async->proc(proc_in, proc_out, async->data));
1039 mark_child_for_cleanup(async->pid, NULL);
1048 else if (async->out)
1051 if (!main_thread_set) {
1053 * We assume that the first time that start_async is called
1054 * it is from the main thread.
1056 main_thread_set = 1;
1057 main_thread = pthread_self();
1058 pthread_key_create(&async_key, NULL);
1059 pthread_key_create(&async_die_counter, NULL);
1060 set_die_routine(die_async);
1061 set_die_is_recursing_routine(async_die_is_recursing);
1065 set_cloexec(proc_in);
1067 set_cloexec(proc_out);
1068 async->proc_in = proc_in;
1069 async->proc_out = proc_out;
1071 int err = pthread_create(&async->tid, NULL, run_thread, async);
1073 error_errno("cannot create thread");
1088 else if (async->out)
1093 int finish_async(struct async *async)
1096 return wait_or_whine(async->pid, "child process", 0);
1098 void *ret = (void *)(intptr_t)(-1);
1100 if (pthread_join(async->tid, &ret))
1101 error("pthread_join failed");
1102 return (int)(intptr_t)ret;
1106 const char *find_hook(const char *name)
1108 static struct strbuf path = STRBUF_INIT;
1110 strbuf_reset(&path);
1111 strbuf_git_path(&path, "hooks/%s", name);
1112 if (access(path.buf, X_OK) < 0) {
1113 #ifdef STRIP_EXTENSION
1114 strbuf_addstr(&path, STRIP_EXTENSION);
1115 if (access(path.buf, X_OK) >= 0)
1123 int run_hook_ve(const char *const *env, const char *name, va_list args)
1125 struct child_process hook = CHILD_PROCESS_INIT;
1128 p = find_hook(name);
1132 argv_array_push(&hook.args, p);
1133 while ((p = va_arg(args, const char *)))
1134 argv_array_push(&hook.args, p);
1137 hook.stdout_to_stderr = 1;
1139 return run_command(&hook);
1142 int run_hook_le(const char *const *env, const char *name, ...)
1147 va_start(args, name);
1148 ret = run_hook_ve(env, name, args);
1155 /* initialized by caller */
1157 int type; /* POLLOUT or POLLIN */
1169 /* returned by pump_io */
1170 int error; /* 0 for success, otherwise errno */
1176 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1181 for (i = 0; i < nr; i++) {
1182 struct io_pump *io = &slots[i];
1185 pfd[pollsize].fd = io->fd;
1186 pfd[pollsize].events = io->type;
1187 io->pfd = &pfd[pollsize++];
1193 if (poll(pfd, pollsize, -1) < 0) {
1196 die_errno("poll failed");
1199 for (i = 0; i < nr; i++) {
1200 struct io_pump *io = &slots[i];
1205 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1208 if (io->type == POLLOUT) {
1209 ssize_t len = xwrite(io->fd,
1210 io->u.out.buf, io->u.out.len);
1216 io->u.out.buf += len;
1217 io->u.out.len -= len;
1218 if (!io->u.out.len) {
1225 if (io->type == POLLIN) {
1226 ssize_t len = strbuf_read_once(io->u.in.buf,
1227 io->fd, io->u.in.hint);
1240 static int pump_io(struct io_pump *slots, int nr)
1245 for (i = 0; i < nr; i++)
1248 ALLOC_ARRAY(pfd, nr);
1249 while (pump_io_round(slots, nr, pfd))
1253 /* There may be multiple errno values, so just pick the first. */
1254 for (i = 0; i < nr; i++) {
1255 if (slots[i].error) {
1256 errno = slots[i].error;
1264 int pipe_command(struct child_process *cmd,
1265 const char *in, size_t in_len,
1266 struct strbuf *out, size_t out_hint,
1267 struct strbuf *err, size_t err_hint)
1269 struct io_pump io[3];
1279 if (start_command(cmd) < 0)
1283 io[nr].fd = cmd->in;
1284 io[nr].type = POLLOUT;
1285 io[nr].u.out.buf = in;
1286 io[nr].u.out.len = in_len;
1290 io[nr].fd = cmd->out;
1291 io[nr].type = POLLIN;
1292 io[nr].u.in.buf = out;
1293 io[nr].u.in.hint = out_hint;
1297 io[nr].fd = cmd->err;
1298 io[nr].type = POLLIN;
1299 io[nr].u.in.buf = err;
1300 io[nr].u.in.hint = err_hint;
1304 if (pump_io(io, nr) < 0) {
1305 finish_command(cmd); /* throw away exit code */
1309 return finish_command(cmd);
1315 GIT_CP_WAIT_CLEANUP,
1318 struct parallel_processes {
1324 get_next_task_fn get_next_task;
1325 start_failure_fn start_failure;
1326 task_finished_fn task_finished;
1329 enum child_state state;
1330 struct child_process process;
1335 * The struct pollfd is logically part of *children,
1336 * but the system call expects it as its own array.
1340 unsigned shutdown : 1;
1343 struct strbuf buffered_output; /* of finished children */
1346 static int default_start_failure(struct strbuf *out,
1353 static int default_task_finished(int result,
1361 static void kill_children(struct parallel_processes *pp, int signo)
1363 int i, n = pp->max_processes;
1365 for (i = 0; i < n; i++)
1366 if (pp->children[i].state == GIT_CP_WORKING)
1367 kill(pp->children[i].process.pid, signo);
1370 static struct parallel_processes *pp_for_signal;
1372 static void handle_children_on_signal(int signo)
1374 kill_children(pp_for_signal, signo);
1375 sigchain_pop(signo);
1379 static void pp_init(struct parallel_processes *pp,
1381 get_next_task_fn get_next_task,
1382 start_failure_fn start_failure,
1383 task_finished_fn task_finished,
1391 pp->max_processes = n;
1393 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1397 die("BUG: you need to specify a get_next_task function");
1398 pp->get_next_task = get_next_task;
1400 pp->start_failure = start_failure ? start_failure : default_start_failure;
1401 pp->task_finished = task_finished ? task_finished : default_task_finished;
1403 pp->nr_processes = 0;
1404 pp->output_owner = 0;
1406 pp->children = xcalloc(n, sizeof(*pp->children));
1407 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1408 strbuf_init(&pp->buffered_output, 0);
1410 for (i = 0; i < n; i++) {
1411 strbuf_init(&pp->children[i].err, 0);
1412 child_process_init(&pp->children[i].process);
1413 pp->pfd[i].events = POLLIN | POLLHUP;
1418 sigchain_push_common(handle_children_on_signal);
1421 static void pp_cleanup(struct parallel_processes *pp)
1425 trace_printf("run_processes_parallel: done");
1426 for (i = 0; i < pp->max_processes; i++) {
1427 strbuf_release(&pp->children[i].err);
1428 child_process_clear(&pp->children[i].process);
1435 * When get_next_task added messages to the buffer in its last
1436 * iteration, the buffered output is non empty.
1438 strbuf_write(&pp->buffered_output, stderr);
1439 strbuf_release(&pp->buffered_output);
1441 sigchain_pop_common();
1445 * 0 if a new task was started.
1446 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1447 * problem with starting a new command)
1448 * <0 no new job was started, user wishes to shutdown early. Use negative code
1449 * to signal the children.
1451 static int pp_start_one(struct parallel_processes *pp)
1455 for (i = 0; i < pp->max_processes; i++)
1456 if (pp->children[i].state == GIT_CP_FREE)
1458 if (i == pp->max_processes)
1459 die("BUG: bookkeeping is hard");
1461 code = pp->get_next_task(&pp->children[i].process,
1462 &pp->children[i].err,
1464 &pp->children[i].data);
1466 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1467 strbuf_reset(&pp->children[i].err);
1470 pp->children[i].process.err = -1;
1471 pp->children[i].process.stdout_to_stderr = 1;
1472 pp->children[i].process.no_stdin = 1;
1474 if (start_command(&pp->children[i].process)) {
1475 code = pp->start_failure(&pp->children[i].err,
1477 &pp->children[i].data);
1478 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1479 strbuf_reset(&pp->children[i].err);
1486 pp->children[i].state = GIT_CP_WORKING;
1487 pp->pfd[i].fd = pp->children[i].process.err;
1491 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1495 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1502 /* Buffer output from all pipes. */
1503 for (i = 0; i < pp->max_processes; i++) {
1504 if (pp->children[i].state == GIT_CP_WORKING &&
1505 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1506 int n = strbuf_read_once(&pp->children[i].err,
1507 pp->children[i].process.err, 0);
1509 close(pp->children[i].process.err);
1510 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1512 if (errno != EAGAIN)
1518 static void pp_output(struct parallel_processes *pp)
1520 int i = pp->output_owner;
1521 if (pp->children[i].state == GIT_CP_WORKING &&
1522 pp->children[i].err.len) {
1523 strbuf_write(&pp->children[i].err, stderr);
1524 strbuf_reset(&pp->children[i].err);
1528 static int pp_collect_finished(struct parallel_processes *pp)
1531 int n = pp->max_processes;
1534 while (pp->nr_processes > 0) {
1535 for (i = 0; i < pp->max_processes; i++)
1536 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1538 if (i == pp->max_processes)
1541 code = finish_command(&pp->children[i].process);
1543 code = pp->task_finished(code,
1544 &pp->children[i].err, pp->data,
1545 &pp->children[i].data);
1553 pp->children[i].state = GIT_CP_FREE;
1555 child_process_init(&pp->children[i].process);
1557 if (i != pp->output_owner) {
1558 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1559 strbuf_reset(&pp->children[i].err);
1561 strbuf_write(&pp->children[i].err, stderr);
1562 strbuf_reset(&pp->children[i].err);
1564 /* Output all other finished child processes */
1565 strbuf_write(&pp->buffered_output, stderr);
1566 strbuf_reset(&pp->buffered_output);
1569 * Pick next process to output live.
1571 * For now we pick it randomly by doing a round
1572 * robin. Later we may want to pick the one with
1573 * the most output or the longest or shortest
1574 * running process time.
1576 for (i = 0; i < n; i++)
1577 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1579 pp->output_owner = (pp->output_owner + i) % n;
1585 int run_processes_parallel(int n,
1586 get_next_task_fn get_next_task,
1587 start_failure_fn start_failure,
1588 task_finished_fn task_finished,
1592 int output_timeout = 100;
1594 struct parallel_processes pp;
1596 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1599 i < spawn_cap && !pp.shutdown &&
1600 pp.nr_processes < pp.max_processes;
1602 code = pp_start_one(&pp);
1607 kill_children(&pp, -code);
1611 if (!pp.nr_processes)
1613 pp_buffer_stderr(&pp, output_timeout);
1615 code = pp_collect_finished(&pp);
1619 kill_children(&pp, -code);