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;
224 enum child_errcode err;
225 int syserr; /* errno */
228 static void child_die(enum child_errcode err)
230 struct child_err buf;
235 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
236 xwrite(child_notifier, &buf, sizeof(buf));
240 static void child_dup2(int fd, int to)
242 if (dup2(fd, to) < 0)
243 child_die(CHILD_ERR_DUP2);
246 static void child_close(int fd)
249 child_die(CHILD_ERR_CLOSE);
252 static void child_close_pair(int fd[2])
259 * parent will make it look like the child spewed a fatal error and died
260 * this is needed to prevent changes to t0061.
262 static void fake_fatal(const char *err, va_list params)
264 vreportf("fatal: ", err, params);
267 static void child_error_fn(const char *err, va_list params)
269 const char msg[] = "error() should not be called in child\n";
270 xwrite(2, msg, sizeof(msg) - 1);
273 static void child_warn_fn(const char *err, va_list params)
275 const char msg[] = "warn() should not be called in child\n";
276 xwrite(2, msg, sizeof(msg) - 1);
279 static void NORETURN child_die_fn(const char *err, va_list params)
281 const char msg[] = "die() should not be called in child\n";
282 xwrite(2, msg, sizeof(msg) - 1);
286 /* this runs in the parent process */
287 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
289 static void (*old_errfn)(const char *err, va_list params);
291 old_errfn = get_error_routine();
292 set_error_routine(fake_fatal);
293 errno = cerr->syserr;
296 case CHILD_ERR_CHDIR:
297 error_errno("exec '%s': cd to '%s' failed",
298 cmd->argv[0], cmd->dir);
301 error_errno("dup2() in child failed");
303 case CHILD_ERR_CLOSE:
304 error_errno("close() in child failed");
306 case CHILD_ERR_ENOENT:
307 error_errno("cannot run %s", cmd->argv[0]);
309 case CHILD_ERR_SILENT:
311 case CHILD_ERR_ERRNO:
312 error_errno("cannot exec '%s'", cmd->argv[0]);
315 set_error_routine(old_errfn);
318 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
321 die("BUG: command is empty");
324 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
325 * attempt to interpret the command with 'sh'.
327 argv_array_push(out, SHELL_PATH);
330 argv_array_push(out, "git");
331 argv_array_pushv(out, cmd->argv);
332 } else if (cmd->use_shell) {
333 prepare_shell_cmd(out, cmd->argv);
335 argv_array_pushv(out, cmd->argv);
339 * If there are no '/' characters in the command then perform a path
340 * lookup and use the resolved path as the command to exec. If there
341 * are no '/' characters or if the command wasn't found in the path,
342 * have exec attempt to invoke the command directly.
344 if (!strchr(out->argv[1], '/')) {
345 char *program = locate_in_PATH(out->argv[1]);
347 free((char *)out->argv[1]);
348 out->argv[1] = program;
353 static char **prep_childenv(const char *const *deltaenv)
355 extern char **environ;
357 struct string_list env = STRING_LIST_INIT_DUP;
358 struct strbuf key = STRBUF_INIT;
359 const char *const *p;
362 /* Construct a sorted string list consisting of the current environ */
363 for (p = (const char *const *) environ; p && *p; p++) {
364 const char *equals = strchr(*p, '=');
368 strbuf_add(&key, *p, equals - *p);
369 string_list_append(&env, key.buf)->util = (void *) *p;
371 string_list_append(&env, *p)->util = (void *) *p;
374 string_list_sort(&env);
376 /* Merge in 'deltaenv' with the current environ */
377 for (p = deltaenv; p && *p; p++) {
378 const char *equals = strchr(*p, '=');
381 /* ('key=value'), insert or replace entry */
383 strbuf_add(&key, *p, equals - *p);
384 string_list_insert(&env, key.buf)->util = (void *) *p;
386 /* otherwise ('key') remove existing entry */
387 string_list_remove(&env, *p, 0);
391 /* Create an array of 'char *' to be used as the childenv */
392 childenv = xmalloc((env.nr + 1) * sizeof(char *));
393 for (i = 0; i < env.nr; i++)
394 childenv[i] = env.items[i].util;
395 childenv[env.nr] = NULL;
397 string_list_clear(&env, 0);
398 strbuf_release(&key);
403 static inline void set_cloexec(int fd)
405 int flags = fcntl(fd, F_GETFD);
407 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
410 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
412 int status, code = -1;
414 int failed_errno = 0;
416 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
422 failed_errno = errno;
423 error_errno("waitpid for %s failed", argv0);
424 } else if (waiting != pid) {
425 error("waitpid is confused (%s)", argv0);
426 } else if (WIFSIGNALED(status)) {
427 code = WTERMSIG(status);
428 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
429 error("%s died of signal %d", argv0, code);
431 * This return value is chosen so that code & 0xff
432 * mimics the exit code that a POSIX shell would report for
433 * a program that died from this signal.
436 } else if (WIFEXITED(status)) {
437 code = WEXITSTATUS(status);
439 error("waitpid is confused (%s)", argv0);
442 clear_child_for_cleanup(pid);
444 errno = failed_errno;
448 int start_command(struct child_process *cmd)
450 int need_in, need_out, need_err;
451 int fdin[2], fdout[2], fderr[2];
456 cmd->argv = cmd->args.argv;
458 cmd->env = cmd->env_array.argv;
461 * In case of errors we must keep the promise to close FDs
462 * that have been passed in via ->in and ->out.
465 need_in = !cmd->no_stdin && cmd->in < 0;
467 if (pipe(fdin) < 0) {
468 failed_errno = errno;
471 str = "standard input";
477 need_out = !cmd->no_stdout
478 && !cmd->stdout_to_stderr
481 if (pipe(fdout) < 0) {
482 failed_errno = errno;
487 str = "standard output";
493 need_err = !cmd->no_stderr && cmd->err < 0;
495 if (pipe(fderr) < 0) {
496 failed_errno = errno;
505 str = "standard error";
507 error("cannot create %s pipe for %s: %s",
508 str, cmd->argv[0], strerror(failed_errno));
509 child_process_clear(cmd);
510 errno = failed_errno;
516 trace_argv_printf(cmd->argv, "trace: run_command:");
519 #ifndef GIT_WINDOWS_NATIVE
524 struct argv_array argv = ARGV_ARRAY_INIT;
525 struct child_err cerr;
527 if (pipe(notify_pipe))
528 notify_pipe[0] = notify_pipe[1] = -1;
530 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
531 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
533 die_errno(_("open /dev/null failed"));
534 set_cloexec(null_fd);
537 prepare_cmd(&argv, cmd);
538 childenv = prep_childenv(cmd->env);
541 * NOTE: In order to prevent deadlocking when using threads special
542 * care should be taken with the function calls made in between the
543 * fork() and exec() calls. No calls should be made to functions which
544 * require acquiring a lock (e.g. malloc) as the lock could have been
545 * held by another thread at the time of forking, causing the lock to
546 * never be released in the child process. This means only
547 * Async-Signal-Safe functions are permitted in the child.
550 failed_errno = errno;
553 * Ensure the default die/error/warn routines do not get
554 * called, they can take stdio locks and malloc.
556 set_die_routine(child_die_fn);
557 set_error_routine(child_error_fn);
558 set_warn_routine(child_warn_fn);
560 close(notify_pipe[0]);
561 set_cloexec(notify_pipe[1]);
562 child_notifier = notify_pipe[1];
565 child_dup2(null_fd, 0);
567 child_dup2(fdin[0], 0);
568 child_close_pair(fdin);
569 } else if (cmd->in) {
570 child_dup2(cmd->in, 0);
571 child_close(cmd->in);
575 child_dup2(null_fd, 2);
577 child_dup2(fderr[1], 2);
578 child_close_pair(fderr);
579 } else if (cmd->err > 1) {
580 child_dup2(cmd->err, 2);
581 child_close(cmd->err);
585 child_dup2(null_fd, 1);
586 else if (cmd->stdout_to_stderr)
589 child_dup2(fdout[1], 1);
590 child_close_pair(fdout);
591 } else if (cmd->out > 1) {
592 child_dup2(cmd->out, 1);
593 child_close(cmd->out);
596 if (cmd->dir && chdir(cmd->dir))
597 child_die(CHILD_ERR_CHDIR);
600 * Attempt to exec using the command and arguments starting at
601 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
602 * be used in the event exec failed with ENOEXEC at which point
603 * we will try to interpret the command using 'sh'.
605 execve(argv.argv[1], (char *const *) argv.argv + 1,
606 (char *const *) childenv);
607 if (errno == ENOEXEC)
608 execve(argv.argv[0], (char *const *) argv.argv,
609 (char *const *) childenv);
611 if (errno == ENOENT) {
612 if (cmd->silent_exec_failure)
613 child_die(CHILD_ERR_SILENT);
614 child_die(CHILD_ERR_ENOENT);
616 child_die(CHILD_ERR_ERRNO);
620 error_errno("cannot fork() for %s", cmd->argv[0]);
621 else if (cmd->clean_on_exit)
622 mark_child_for_cleanup(cmd->pid, cmd);
625 * Wait for child's exec. If the exec succeeds (or if fork()
626 * failed), EOF is seen immediately by the parent. Otherwise, the
627 * child process sends a child_err struct.
628 * Note that use of this infrastructure is completely advisory,
629 * therefore, we keep error checks minimal.
631 close(notify_pipe[1]);
632 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
634 * At this point we know that fork() succeeded, but exec()
635 * failed. Errors have been reported to our stderr.
637 wait_or_whine(cmd->pid, cmd->argv[0], 0);
638 child_err_spew(cmd, &cerr);
639 failed_errno = errno;
642 close(notify_pipe[0]);
646 argv_array_clear(&argv);
651 int fhin = 0, fhout = 1, fherr = 2;
652 const char **sargv = cmd->argv;
653 struct argv_array nargv = ARGV_ARRAY_INIT;
656 fhin = open("/dev/null", O_RDWR);
663 fherr = open("/dev/null", O_RDWR);
665 fherr = dup(fderr[1]);
666 else if (cmd->err > 2)
667 fherr = dup(cmd->err);
670 fhout = open("/dev/null", O_RDWR);
671 else if (cmd->stdout_to_stderr)
674 fhout = dup(fdout[1]);
675 else if (cmd->out > 1)
676 fhout = dup(cmd->out);
679 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
680 else if (cmd->use_shell)
681 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
683 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
684 cmd->dir, fhin, fhout, fherr);
685 failed_errno = errno;
686 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
687 error_errno("cannot spawn %s", cmd->argv[0]);
688 if (cmd->clean_on_exit && cmd->pid >= 0)
689 mark_child_for_cleanup(cmd->pid, cmd);
691 argv_array_clear(&nargv);
715 child_process_clear(cmd);
716 errno = failed_errno;
738 int finish_command(struct child_process *cmd)
740 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
741 child_process_clear(cmd);
745 int finish_command_in_signal(struct child_process *cmd)
747 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
751 int run_command(struct child_process *cmd)
755 if (cmd->out < 0 || cmd->err < 0)
756 die("BUG: run_command with a pipe can cause deadlock");
758 code = start_command(cmd);
761 return finish_command(cmd);
764 int run_command_v_opt(const char **argv, int opt)
766 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
769 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
771 struct child_process cmd = CHILD_PROCESS_INIT;
773 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
774 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
775 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
776 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
777 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
778 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
781 return run_command(&cmd);
785 static pthread_t main_thread;
786 static int main_thread_set;
787 static pthread_key_t async_key;
788 static pthread_key_t async_die_counter;
790 static void *run_thread(void *data)
792 struct async *async = data;
795 if (async->isolate_sigpipe) {
798 sigaddset(&mask, SIGPIPE);
799 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
800 ret = error("unable to block SIGPIPE in async thread");
805 pthread_setspecific(async_key, async);
806 ret = async->proc(async->proc_in, async->proc_out, async->data);
810 static NORETURN void die_async(const char *err, va_list params)
812 vreportf("fatal: ", err, params);
815 struct async *async = pthread_getspecific(async_key);
816 if (async->proc_in >= 0)
817 close(async->proc_in);
818 if (async->proc_out >= 0)
819 close(async->proc_out);
820 pthread_exit((void *)128);
826 static int async_die_is_recursing(void)
828 void *ret = pthread_getspecific(async_die_counter);
829 pthread_setspecific(async_die_counter, (void *)1);
835 if (!main_thread_set)
836 return 0; /* no asyncs started yet */
837 return !pthread_equal(main_thread, pthread_self());
840 static void NORETURN async_exit(int code)
842 pthread_exit((void *)(intptr_t)code);
848 void (**handlers)(void);
853 static int git_atexit_installed;
855 static void git_atexit_dispatch(void)
859 for (i=git_atexit_hdlrs.nr ; i ; i--)
860 git_atexit_hdlrs.handlers[i-1]();
863 static void git_atexit_clear(void)
865 free(git_atexit_hdlrs.handlers);
866 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
867 git_atexit_installed = 0;
871 int git_atexit(void (*handler)(void))
873 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
874 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
875 if (!git_atexit_installed) {
876 if (atexit(&git_atexit_dispatch))
878 git_atexit_installed = 1;
882 #define atexit git_atexit
884 static int process_is_async;
887 return process_is_async;
890 static void NORETURN async_exit(int code)
897 void check_pipe(int err)
903 signal(SIGPIPE, SIG_DFL);
905 /* Should never happen, but just in case... */
910 int start_async(struct async *async)
912 int need_in, need_out;
913 int fdin[2], fdout[2];
914 int proc_in, proc_out;
916 need_in = async->in < 0;
918 if (pipe(fdin) < 0) {
921 return error_errno("cannot create pipe");
926 need_out = async->out < 0;
928 if (pipe(fdout) < 0) {
933 return error_errno("cannot create pipe");
935 async->out = fdout[0];
948 proc_out = async->out;
953 /* Flush stdio before fork() to avoid cloning buffers */
957 if (async->pid < 0) {
958 error_errno("fork (async) failed");
967 process_is_async = 1;
968 exit(!!async->proc(proc_in, proc_out, async->data));
971 mark_child_for_cleanup(async->pid, NULL);
983 if (!main_thread_set) {
985 * We assume that the first time that start_async is called
986 * it is from the main thread.
989 main_thread = pthread_self();
990 pthread_key_create(&async_key, NULL);
991 pthread_key_create(&async_die_counter, NULL);
992 set_die_routine(die_async);
993 set_die_is_recursing_routine(async_die_is_recursing);
997 set_cloexec(proc_in);
999 set_cloexec(proc_out);
1000 async->proc_in = proc_in;
1001 async->proc_out = proc_out;
1003 int err = pthread_create(&async->tid, NULL, run_thread, async);
1005 error_errno("cannot create thread");
1020 else if (async->out)
1025 int finish_async(struct async *async)
1028 return wait_or_whine(async->pid, "child process", 0);
1030 void *ret = (void *)(intptr_t)(-1);
1032 if (pthread_join(async->tid, &ret))
1033 error("pthread_join failed");
1034 return (int)(intptr_t)ret;
1038 const char *find_hook(const char *name)
1040 static struct strbuf path = STRBUF_INIT;
1042 strbuf_reset(&path);
1043 strbuf_git_path(&path, "hooks/%s", name);
1044 if (access(path.buf, X_OK) < 0) {
1045 #ifdef STRIP_EXTENSION
1046 strbuf_addstr(&path, STRIP_EXTENSION);
1047 if (access(path.buf, X_OK) >= 0)
1055 int run_hook_ve(const char *const *env, const char *name, va_list args)
1057 struct child_process hook = CHILD_PROCESS_INIT;
1060 p = find_hook(name);
1064 argv_array_push(&hook.args, p);
1065 while ((p = va_arg(args, const char *)))
1066 argv_array_push(&hook.args, p);
1069 hook.stdout_to_stderr = 1;
1071 return run_command(&hook);
1074 int run_hook_le(const char *const *env, const char *name, ...)
1079 va_start(args, name);
1080 ret = run_hook_ve(env, name, args);
1087 /* initialized by caller */
1089 int type; /* POLLOUT or POLLIN */
1101 /* returned by pump_io */
1102 int error; /* 0 for success, otherwise errno */
1108 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1113 for (i = 0; i < nr; i++) {
1114 struct io_pump *io = &slots[i];
1117 pfd[pollsize].fd = io->fd;
1118 pfd[pollsize].events = io->type;
1119 io->pfd = &pfd[pollsize++];
1125 if (poll(pfd, pollsize, -1) < 0) {
1128 die_errno("poll failed");
1131 for (i = 0; i < nr; i++) {
1132 struct io_pump *io = &slots[i];
1137 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1140 if (io->type == POLLOUT) {
1141 ssize_t len = xwrite(io->fd,
1142 io->u.out.buf, io->u.out.len);
1148 io->u.out.buf += len;
1149 io->u.out.len -= len;
1150 if (!io->u.out.len) {
1157 if (io->type == POLLIN) {
1158 ssize_t len = strbuf_read_once(io->u.in.buf,
1159 io->fd, io->u.in.hint);
1172 static int pump_io(struct io_pump *slots, int nr)
1177 for (i = 0; i < nr; i++)
1180 ALLOC_ARRAY(pfd, nr);
1181 while (pump_io_round(slots, nr, pfd))
1185 /* There may be multiple errno values, so just pick the first. */
1186 for (i = 0; i < nr; i++) {
1187 if (slots[i].error) {
1188 errno = slots[i].error;
1196 int pipe_command(struct child_process *cmd,
1197 const char *in, size_t in_len,
1198 struct strbuf *out, size_t out_hint,
1199 struct strbuf *err, size_t err_hint)
1201 struct io_pump io[3];
1211 if (start_command(cmd) < 0)
1215 io[nr].fd = cmd->in;
1216 io[nr].type = POLLOUT;
1217 io[nr].u.out.buf = in;
1218 io[nr].u.out.len = in_len;
1222 io[nr].fd = cmd->out;
1223 io[nr].type = POLLIN;
1224 io[nr].u.in.buf = out;
1225 io[nr].u.in.hint = out_hint;
1229 io[nr].fd = cmd->err;
1230 io[nr].type = POLLIN;
1231 io[nr].u.in.buf = err;
1232 io[nr].u.in.hint = err_hint;
1236 if (pump_io(io, nr) < 0) {
1237 finish_command(cmd); /* throw away exit code */
1241 return finish_command(cmd);
1247 GIT_CP_WAIT_CLEANUP,
1250 struct parallel_processes {
1256 get_next_task_fn get_next_task;
1257 start_failure_fn start_failure;
1258 task_finished_fn task_finished;
1261 enum child_state state;
1262 struct child_process process;
1267 * The struct pollfd is logically part of *children,
1268 * but the system call expects it as its own array.
1272 unsigned shutdown : 1;
1275 struct strbuf buffered_output; /* of finished children */
1278 static int default_start_failure(struct strbuf *out,
1285 static int default_task_finished(int result,
1293 static void kill_children(struct parallel_processes *pp, int signo)
1295 int i, n = pp->max_processes;
1297 for (i = 0; i < n; i++)
1298 if (pp->children[i].state == GIT_CP_WORKING)
1299 kill(pp->children[i].process.pid, signo);
1302 static struct parallel_processes *pp_for_signal;
1304 static void handle_children_on_signal(int signo)
1306 kill_children(pp_for_signal, signo);
1307 sigchain_pop(signo);
1311 static void pp_init(struct parallel_processes *pp,
1313 get_next_task_fn get_next_task,
1314 start_failure_fn start_failure,
1315 task_finished_fn task_finished,
1323 pp->max_processes = n;
1325 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1329 die("BUG: you need to specify a get_next_task function");
1330 pp->get_next_task = get_next_task;
1332 pp->start_failure = start_failure ? start_failure : default_start_failure;
1333 pp->task_finished = task_finished ? task_finished : default_task_finished;
1335 pp->nr_processes = 0;
1336 pp->output_owner = 0;
1338 pp->children = xcalloc(n, sizeof(*pp->children));
1339 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1340 strbuf_init(&pp->buffered_output, 0);
1342 for (i = 0; i < n; i++) {
1343 strbuf_init(&pp->children[i].err, 0);
1344 child_process_init(&pp->children[i].process);
1345 pp->pfd[i].events = POLLIN | POLLHUP;
1350 sigchain_push_common(handle_children_on_signal);
1353 static void pp_cleanup(struct parallel_processes *pp)
1357 trace_printf("run_processes_parallel: done");
1358 for (i = 0; i < pp->max_processes; i++) {
1359 strbuf_release(&pp->children[i].err);
1360 child_process_clear(&pp->children[i].process);
1367 * When get_next_task added messages to the buffer in its last
1368 * iteration, the buffered output is non empty.
1370 strbuf_write(&pp->buffered_output, stderr);
1371 strbuf_release(&pp->buffered_output);
1373 sigchain_pop_common();
1377 * 0 if a new task was started.
1378 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1379 * problem with starting a new command)
1380 * <0 no new job was started, user wishes to shutdown early. Use negative code
1381 * to signal the children.
1383 static int pp_start_one(struct parallel_processes *pp)
1387 for (i = 0; i < pp->max_processes; i++)
1388 if (pp->children[i].state == GIT_CP_FREE)
1390 if (i == pp->max_processes)
1391 die("BUG: bookkeeping is hard");
1393 code = pp->get_next_task(&pp->children[i].process,
1394 &pp->children[i].err,
1396 &pp->children[i].data);
1398 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1399 strbuf_reset(&pp->children[i].err);
1402 pp->children[i].process.err = -1;
1403 pp->children[i].process.stdout_to_stderr = 1;
1404 pp->children[i].process.no_stdin = 1;
1406 if (start_command(&pp->children[i].process)) {
1407 code = pp->start_failure(&pp->children[i].err,
1409 &pp->children[i].data);
1410 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1411 strbuf_reset(&pp->children[i].err);
1418 pp->children[i].state = GIT_CP_WORKING;
1419 pp->pfd[i].fd = pp->children[i].process.err;
1423 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1427 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1434 /* Buffer output from all pipes. */
1435 for (i = 0; i < pp->max_processes; i++) {
1436 if (pp->children[i].state == GIT_CP_WORKING &&
1437 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1438 int n = strbuf_read_once(&pp->children[i].err,
1439 pp->children[i].process.err, 0);
1441 close(pp->children[i].process.err);
1442 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1444 if (errno != EAGAIN)
1450 static void pp_output(struct parallel_processes *pp)
1452 int i = pp->output_owner;
1453 if (pp->children[i].state == GIT_CP_WORKING &&
1454 pp->children[i].err.len) {
1455 strbuf_write(&pp->children[i].err, stderr);
1456 strbuf_reset(&pp->children[i].err);
1460 static int pp_collect_finished(struct parallel_processes *pp)
1463 int n = pp->max_processes;
1466 while (pp->nr_processes > 0) {
1467 for (i = 0; i < pp->max_processes; i++)
1468 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1470 if (i == pp->max_processes)
1473 code = finish_command(&pp->children[i].process);
1475 code = pp->task_finished(code,
1476 &pp->children[i].err, pp->data,
1477 &pp->children[i].data);
1485 pp->children[i].state = GIT_CP_FREE;
1487 child_process_init(&pp->children[i].process);
1489 if (i != pp->output_owner) {
1490 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1491 strbuf_reset(&pp->children[i].err);
1493 strbuf_write(&pp->children[i].err, stderr);
1494 strbuf_reset(&pp->children[i].err);
1496 /* Output all other finished child processes */
1497 strbuf_write(&pp->buffered_output, stderr);
1498 strbuf_reset(&pp->buffered_output);
1501 * Pick next process to output live.
1503 * For now we pick it randomly by doing a round
1504 * robin. Later we may want to pick the one with
1505 * the most output or the longest or shortest
1506 * running process time.
1508 for (i = 0; i < n; i++)
1509 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1511 pp->output_owner = (pp->output_owner + i) % n;
1517 int run_processes_parallel(int n,
1518 get_next_task_fn get_next_task,
1519 start_failure_fn start_failure,
1520 task_finished_fn task_finished,
1524 int output_timeout = 100;
1526 struct parallel_processes pp;
1528 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1531 i < spawn_cap && !pp.shutdown &&
1532 pp.nr_processes < pp.max_processes;
1534 code = pp_start_one(&pp);
1539 kill_children(&pp, -code);
1543 if (!pp.nr_processes)
1545 pp_buffer_stderr(&pp, output_timeout);
1547 code = pp_collect_finished(&pp);
1551 kill_children(&pp, -code);