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 failed_errno
= errno
;
544 * Ensure the default die/error/warn routines do not get
545 * called, they can take stdio locks and malloc.
547 set_die_routine(child_die_fn
);
548 set_error_routine(child_error_fn
);
549 set_warn_routine(child_warn_fn
);
551 close(notify_pipe
[0]);
552 set_cloexec(notify_pipe
[1]);
553 child_notifier
= notify_pipe
[1];
556 child_dup2(null_fd
, 0);
558 child_dup2(fdin
[0], 0);
559 child_close_pair(fdin
);
560 } else if (cmd
->in
) {
561 child_dup2(cmd
->in
, 0);
562 child_close(cmd
->in
);
566 child_dup2(null_fd
, 2);
568 child_dup2(fderr
[1], 2);
569 child_close_pair(fderr
);
570 } else if (cmd
->err
> 1) {
571 child_dup2(cmd
->err
, 2);
572 child_close(cmd
->err
);
576 child_dup2(null_fd
, 1);
577 else if (cmd
->stdout_to_stderr
)
580 child_dup2(fdout
[1], 1);
581 child_close_pair(fdout
);
582 } else if (cmd
->out
> 1) {
583 child_dup2(cmd
->out
, 1);
584 child_close(cmd
->out
);
587 if (cmd
->dir
&& chdir(cmd
->dir
))
588 child_die(CHILD_ERR_CHDIR
);
591 * Attempt to exec using the command and arguments starting at
592 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
593 * be used in the event exec failed with ENOEXEC at which point
594 * we will try to interpret the command using 'sh'.
596 execve(argv
.argv
[1], (char *const *) argv
.argv
+ 1,
597 (char *const *) childenv
);
598 if (errno
== ENOEXEC
)
599 execve(argv
.argv
[0], (char *const *) argv
.argv
,
600 (char *const *) childenv
);
602 if (errno
== ENOENT
) {
603 if (cmd
->silent_exec_failure
)
604 child_die(CHILD_ERR_SILENT
);
605 child_die(CHILD_ERR_ENOENT
);
607 child_die(CHILD_ERR_ERRNO
);
611 error_errno("cannot fork() for %s", cmd
->argv
[0]);
612 else if (cmd
->clean_on_exit
)
613 mark_child_for_cleanup(cmd
->pid
, cmd
);
616 * Wait for child's exec. If the exec succeeds (or if fork()
617 * failed), EOF is seen immediately by the parent. Otherwise, the
618 * child process sends a child_err struct.
619 * Note that use of this infrastructure is completely advisory,
620 * therefore, we keep error checks minimal.
622 close(notify_pipe
[1]);
623 if (xread(notify_pipe
[0], &cerr
, sizeof(cerr
)) == sizeof(cerr
)) {
625 * At this point we know that fork() succeeded, but exec()
626 * failed. Errors have been reported to our stderr.
628 wait_or_whine(cmd
->pid
, cmd
->argv
[0], 0);
629 child_err_spew(cmd
, &cerr
);
630 failed_errno
= errno
;
633 close(notify_pipe
[0]);
637 argv_array_clear(&argv
);
642 int fhin
= 0, fhout
= 1, fherr
= 2;
643 const char **sargv
= cmd
->argv
;
644 struct argv_array nargv
= ARGV_ARRAY_INIT
;
647 fhin
= open("/dev/null", O_RDWR
);
654 fherr
= open("/dev/null", O_RDWR
);
656 fherr
= dup(fderr
[1]);
657 else if (cmd
->err
> 2)
658 fherr
= dup(cmd
->err
);
661 fhout
= open("/dev/null", O_RDWR
);
662 else if (cmd
->stdout_to_stderr
)
665 fhout
= dup(fdout
[1]);
666 else if (cmd
->out
> 1)
667 fhout
= dup(cmd
->out
);
670 cmd
->argv
= prepare_git_cmd(&nargv
, cmd
->argv
);
671 else if (cmd
->use_shell
)
672 cmd
->argv
= prepare_shell_cmd(&nargv
, cmd
->argv
);
674 cmd
->pid
= mingw_spawnvpe(cmd
->argv
[0], cmd
->argv
, (char**) cmd
->env
,
675 cmd
->dir
, fhin
, fhout
, fherr
);
676 failed_errno
= errno
;
677 if (cmd
->pid
< 0 && (!cmd
->silent_exec_failure
|| errno
!= ENOENT
))
678 error_errno("cannot spawn %s", cmd
->argv
[0]);
679 if (cmd
->clean_on_exit
&& cmd
->pid
>= 0)
680 mark_child_for_cleanup(cmd
->pid
, cmd
);
682 argv_array_clear(&nargv
);
706 child_process_clear(cmd
);
707 errno
= failed_errno
;
729 int finish_command(struct child_process
*cmd
)
731 int ret
= wait_or_whine(cmd
->pid
, cmd
->argv
[0], 0);
732 child_process_clear(cmd
);
736 int finish_command_in_signal(struct child_process
*cmd
)
738 return wait_or_whine(cmd
->pid
, cmd
->argv
[0], 1);
742 int run_command(struct child_process
*cmd
)
746 if (cmd
->out
< 0 || cmd
->err
< 0)
747 die("BUG: run_command with a pipe can cause deadlock");
749 code
= start_command(cmd
);
752 return finish_command(cmd
);
755 int run_command_v_opt(const char **argv
, int opt
)
757 return run_command_v_opt_cd_env(argv
, opt
, NULL
, NULL
);
760 int run_command_v_opt_cd_env(const char **argv
, int opt
, const char *dir
, const char *const *env
)
762 struct child_process cmd
= CHILD_PROCESS_INIT
;
764 cmd
.no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
765 cmd
.git_cmd
= opt
& RUN_GIT_CMD
? 1 : 0;
766 cmd
.stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
767 cmd
.silent_exec_failure
= opt
& RUN_SILENT_EXEC_FAILURE
? 1 : 0;
768 cmd
.use_shell
= opt
& RUN_USING_SHELL
? 1 : 0;
769 cmd
.clean_on_exit
= opt
& RUN_CLEAN_ON_EXIT
? 1 : 0;
772 return run_command(&cmd
);
776 static pthread_t main_thread
;
777 static int main_thread_set
;
778 static pthread_key_t async_key
;
779 static pthread_key_t async_die_counter
;
781 static void *run_thread(void *data
)
783 struct async
*async
= data
;
786 if (async
->isolate_sigpipe
) {
789 sigaddset(&mask
, SIGPIPE
);
790 if (pthread_sigmask(SIG_BLOCK
, &mask
, NULL
) < 0) {
791 ret
= error("unable to block SIGPIPE in async thread");
796 pthread_setspecific(async_key
, async
);
797 ret
= async
->proc(async
->proc_in
, async
->proc_out
, async
->data
);
801 static NORETURN
void die_async(const char *err
, va_list params
)
803 vreportf("fatal: ", err
, params
);
806 struct async
*async
= pthread_getspecific(async_key
);
807 if (async
->proc_in
>= 0)
808 close(async
->proc_in
);
809 if (async
->proc_out
>= 0)
810 close(async
->proc_out
);
811 pthread_exit((void *)128);
817 static int async_die_is_recursing(void)
819 void *ret
= pthread_getspecific(async_die_counter
);
820 pthread_setspecific(async_die_counter
, (void *)1);
826 if (!main_thread_set
)
827 return 0; /* no asyncs started yet */
828 return !pthread_equal(main_thread
, pthread_self());
831 static void NORETURN
async_exit(int code
)
833 pthread_exit((void *)(intptr_t)code
);
839 void (**handlers
)(void);
844 static int git_atexit_installed
;
846 static void git_atexit_dispatch(void)
850 for (i
=git_atexit_hdlrs
.nr
; i
; i
--)
851 git_atexit_hdlrs
.handlers
[i
-1]();
854 static void git_atexit_clear(void)
856 free(git_atexit_hdlrs
.handlers
);
857 memset(&git_atexit_hdlrs
, 0, sizeof(git_atexit_hdlrs
));
858 git_atexit_installed
= 0;
862 int git_atexit(void (*handler
)(void))
864 ALLOC_GROW(git_atexit_hdlrs
.handlers
, git_atexit_hdlrs
.nr
+ 1, git_atexit_hdlrs
.alloc
);
865 git_atexit_hdlrs
.handlers
[git_atexit_hdlrs
.nr
++] = handler
;
866 if (!git_atexit_installed
) {
867 if (atexit(&git_atexit_dispatch
))
869 git_atexit_installed
= 1;
873 #define atexit git_atexit
875 static int process_is_async
;
878 return process_is_async
;
881 static void NORETURN
async_exit(int code
)
888 void check_pipe(int err
)
894 signal(SIGPIPE
, SIG_DFL
);
896 /* Should never happen, but just in case... */
901 int start_async(struct async
*async
)
903 int need_in
, need_out
;
904 int fdin
[2], fdout
[2];
905 int proc_in
, proc_out
;
907 need_in
= async
->in
< 0;
909 if (pipe(fdin
) < 0) {
912 return error_errno("cannot create pipe");
917 need_out
= async
->out
< 0;
919 if (pipe(fdout
) < 0) {
924 return error_errno("cannot create pipe");
926 async
->out
= fdout
[0];
939 proc_out
= async
->out
;
944 /* Flush stdio before fork() to avoid cloning buffers */
948 if (async
->pid
< 0) {
949 error_errno("fork (async) failed");
958 process_is_async
= 1;
959 exit(!!async
->proc(proc_in
, proc_out
, async
->data
));
962 mark_child_for_cleanup(async
->pid
, NULL
);
974 if (!main_thread_set
) {
976 * We assume that the first time that start_async is called
977 * it is from the main thread.
980 main_thread
= pthread_self();
981 pthread_key_create(&async_key
, NULL
);
982 pthread_key_create(&async_die_counter
, NULL
);
983 set_die_routine(die_async
);
984 set_die_is_recursing_routine(async_die_is_recursing
);
988 set_cloexec(proc_in
);
990 set_cloexec(proc_out
);
991 async
->proc_in
= proc_in
;
992 async
->proc_out
= proc_out
;
994 int err
= pthread_create(&async
->tid
, NULL
, run_thread
, async
);
996 error_errno("cannot create thread");
1011 else if (async
->out
)
1016 int finish_async(struct async
*async
)
1019 return wait_or_whine(async
->pid
, "child process", 0);
1021 void *ret
= (void *)(intptr_t)(-1);
1023 if (pthread_join(async
->tid
, &ret
))
1024 error("pthread_join failed");
1025 return (int)(intptr_t)ret
;
1029 const char *find_hook(const char *name
)
1031 static struct strbuf path
= STRBUF_INIT
;
1033 strbuf_reset(&path
);
1034 strbuf_git_path(&path
, "hooks/%s", name
);
1035 if (access(path
.buf
, X_OK
) < 0) {
1036 #ifdef STRIP_EXTENSION
1037 strbuf_addstr(&path
, STRIP_EXTENSION
);
1038 if (access(path
.buf
, X_OK
) >= 0)
1046 int run_hook_ve(const char *const *env
, const char *name
, va_list args
)
1048 struct child_process hook
= CHILD_PROCESS_INIT
;
1051 p
= find_hook(name
);
1055 argv_array_push(&hook
.args
, p
);
1056 while ((p
= va_arg(args
, const char *)))
1057 argv_array_push(&hook
.args
, p
);
1060 hook
.stdout_to_stderr
= 1;
1062 return run_command(&hook
);
1065 int run_hook_le(const char *const *env
, const char *name
, ...)
1070 va_start(args
, name
);
1071 ret
= run_hook_ve(env
, name
, args
);
1078 /* initialized by caller */
1080 int type
; /* POLLOUT or POLLIN */
1092 /* returned by pump_io */
1093 int error
; /* 0 for success, otherwise errno */
1099 static int pump_io_round(struct io_pump
*slots
, int nr
, struct pollfd
*pfd
)
1104 for (i
= 0; i
< nr
; i
++) {
1105 struct io_pump
*io
= &slots
[i
];
1108 pfd
[pollsize
].fd
= io
->fd
;
1109 pfd
[pollsize
].events
= io
->type
;
1110 io
->pfd
= &pfd
[pollsize
++];
1116 if (poll(pfd
, pollsize
, -1) < 0) {
1119 die_errno("poll failed");
1122 for (i
= 0; i
< nr
; i
++) {
1123 struct io_pump
*io
= &slots
[i
];
1128 if (!(io
->pfd
->revents
& (POLLOUT
|POLLIN
|POLLHUP
|POLLERR
|POLLNVAL
)))
1131 if (io
->type
== POLLOUT
) {
1132 ssize_t len
= xwrite(io
->fd
,
1133 io
->u
.out
.buf
, io
->u
.out
.len
);
1139 io
->u
.out
.buf
+= len
;
1140 io
->u
.out
.len
-= len
;
1141 if (!io
->u
.out
.len
) {
1148 if (io
->type
== POLLIN
) {
1149 ssize_t len
= strbuf_read_once(io
->u
.in
.buf
,
1150 io
->fd
, io
->u
.in
.hint
);
1163 static int pump_io(struct io_pump
*slots
, int nr
)
1168 for (i
= 0; i
< nr
; i
++)
1171 ALLOC_ARRAY(pfd
, nr
);
1172 while (pump_io_round(slots
, nr
, pfd
))
1176 /* There may be multiple errno values, so just pick the first. */
1177 for (i
= 0; i
< nr
; i
++) {
1178 if (slots
[i
].error
) {
1179 errno
= slots
[i
].error
;
1187 int pipe_command(struct child_process
*cmd
,
1188 const char *in
, size_t in_len
,
1189 struct strbuf
*out
, size_t out_hint
,
1190 struct strbuf
*err
, size_t err_hint
)
1192 struct io_pump io
[3];
1202 if (start_command(cmd
) < 0)
1206 io
[nr
].fd
= cmd
->in
;
1207 io
[nr
].type
= POLLOUT
;
1208 io
[nr
].u
.out
.buf
= in
;
1209 io
[nr
].u
.out
.len
= in_len
;
1213 io
[nr
].fd
= cmd
->out
;
1214 io
[nr
].type
= POLLIN
;
1215 io
[nr
].u
.in
.buf
= out
;
1216 io
[nr
].u
.in
.hint
= out_hint
;
1220 io
[nr
].fd
= cmd
->err
;
1221 io
[nr
].type
= POLLIN
;
1222 io
[nr
].u
.in
.buf
= err
;
1223 io
[nr
].u
.in
.hint
= err_hint
;
1227 if (pump_io(io
, nr
) < 0) {
1228 finish_command(cmd
); /* throw away exit code */
1232 return finish_command(cmd
);
1238 GIT_CP_WAIT_CLEANUP
,
1241 struct parallel_processes
{
1247 get_next_task_fn get_next_task
;
1248 start_failure_fn start_failure
;
1249 task_finished_fn task_finished
;
1252 enum child_state state
;
1253 struct child_process process
;
1258 * The struct pollfd is logically part of *children,
1259 * but the system call expects it as its own array.
1263 unsigned shutdown
: 1;
1266 struct strbuf buffered_output
; /* of finished children */
1269 static int default_start_failure(struct strbuf
*out
,
1276 static int default_task_finished(int result
,
1284 static void kill_children(struct parallel_processes
*pp
, int signo
)
1286 int i
, n
= pp
->max_processes
;
1288 for (i
= 0; i
< n
; i
++)
1289 if (pp
->children
[i
].state
== GIT_CP_WORKING
)
1290 kill(pp
->children
[i
].process
.pid
, signo
);
1293 static struct parallel_processes
*pp_for_signal
;
1295 static void handle_children_on_signal(int signo
)
1297 kill_children(pp_for_signal
, signo
);
1298 sigchain_pop(signo
);
1302 static void pp_init(struct parallel_processes
*pp
,
1304 get_next_task_fn get_next_task
,
1305 start_failure_fn start_failure
,
1306 task_finished_fn task_finished
,
1314 pp
->max_processes
= n
;
1316 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n
);
1320 die("BUG: you need to specify a get_next_task function");
1321 pp
->get_next_task
= get_next_task
;
1323 pp
->start_failure
= start_failure
? start_failure
: default_start_failure
;
1324 pp
->task_finished
= task_finished
? task_finished
: default_task_finished
;
1326 pp
->nr_processes
= 0;
1327 pp
->output_owner
= 0;
1329 pp
->children
= xcalloc(n
, sizeof(*pp
->children
));
1330 pp
->pfd
= xcalloc(n
, sizeof(*pp
->pfd
));
1331 strbuf_init(&pp
->buffered_output
, 0);
1333 for (i
= 0; i
< n
; i
++) {
1334 strbuf_init(&pp
->children
[i
].err
, 0);
1335 child_process_init(&pp
->children
[i
].process
);
1336 pp
->pfd
[i
].events
= POLLIN
| POLLHUP
;
1341 sigchain_push_common(handle_children_on_signal
);
1344 static void pp_cleanup(struct parallel_processes
*pp
)
1348 trace_printf("run_processes_parallel: done");
1349 for (i
= 0; i
< pp
->max_processes
; i
++) {
1350 strbuf_release(&pp
->children
[i
].err
);
1351 child_process_clear(&pp
->children
[i
].process
);
1358 * When get_next_task added messages to the buffer in its last
1359 * iteration, the buffered output is non empty.
1361 strbuf_write(&pp
->buffered_output
, stderr
);
1362 strbuf_release(&pp
->buffered_output
);
1364 sigchain_pop_common();
1368 * 0 if a new task was started.
1369 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1370 * problem with starting a new command)
1371 * <0 no new job was started, user wishes to shutdown early. Use negative code
1372 * to signal the children.
1374 static int pp_start_one(struct parallel_processes
*pp
)
1378 for (i
= 0; i
< pp
->max_processes
; i
++)
1379 if (pp
->children
[i
].state
== GIT_CP_FREE
)
1381 if (i
== pp
->max_processes
)
1382 die("BUG: bookkeeping is hard");
1384 code
= pp
->get_next_task(&pp
->children
[i
].process
,
1385 &pp
->children
[i
].err
,
1387 &pp
->children
[i
].data
);
1389 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1390 strbuf_reset(&pp
->children
[i
].err
);
1393 pp
->children
[i
].process
.err
= -1;
1394 pp
->children
[i
].process
.stdout_to_stderr
= 1;
1395 pp
->children
[i
].process
.no_stdin
= 1;
1397 if (start_command(&pp
->children
[i
].process
)) {
1398 code
= pp
->start_failure(&pp
->children
[i
].err
,
1400 &pp
->children
[i
].data
);
1401 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1402 strbuf_reset(&pp
->children
[i
].err
);
1409 pp
->children
[i
].state
= GIT_CP_WORKING
;
1410 pp
->pfd
[i
].fd
= pp
->children
[i
].process
.err
;
1414 static void pp_buffer_stderr(struct parallel_processes
*pp
, int output_timeout
)
1418 while ((i
= poll(pp
->pfd
, pp
->max_processes
, output_timeout
)) < 0) {
1425 /* Buffer output from all pipes. */
1426 for (i
= 0; i
< pp
->max_processes
; i
++) {
1427 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1428 pp
->pfd
[i
].revents
& (POLLIN
| POLLHUP
)) {
1429 int n
= strbuf_read_once(&pp
->children
[i
].err
,
1430 pp
->children
[i
].process
.err
, 0);
1432 close(pp
->children
[i
].process
.err
);
1433 pp
->children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1435 if (errno
!= EAGAIN
)
1441 static void pp_output(struct parallel_processes
*pp
)
1443 int i
= pp
->output_owner
;
1444 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1445 pp
->children
[i
].err
.len
) {
1446 strbuf_write(&pp
->children
[i
].err
, stderr
);
1447 strbuf_reset(&pp
->children
[i
].err
);
1451 static int pp_collect_finished(struct parallel_processes
*pp
)
1454 int n
= pp
->max_processes
;
1457 while (pp
->nr_processes
> 0) {
1458 for (i
= 0; i
< pp
->max_processes
; i
++)
1459 if (pp
->children
[i
].state
== GIT_CP_WAIT_CLEANUP
)
1461 if (i
== pp
->max_processes
)
1464 code
= finish_command(&pp
->children
[i
].process
);
1466 code
= pp
->task_finished(code
,
1467 &pp
->children
[i
].err
, pp
->data
,
1468 &pp
->children
[i
].data
);
1476 pp
->children
[i
].state
= GIT_CP_FREE
;
1478 child_process_init(&pp
->children
[i
].process
);
1480 if (i
!= pp
->output_owner
) {
1481 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1482 strbuf_reset(&pp
->children
[i
].err
);
1484 strbuf_write(&pp
->children
[i
].err
, stderr
);
1485 strbuf_reset(&pp
->children
[i
].err
);
1487 /* Output all other finished child processes */
1488 strbuf_write(&pp
->buffered_output
, stderr
);
1489 strbuf_reset(&pp
->buffered_output
);
1492 * Pick next process to output live.
1494 * For now we pick it randomly by doing a round
1495 * robin. Later we may want to pick the one with
1496 * the most output or the longest or shortest
1497 * running process time.
1499 for (i
= 0; i
< n
; i
++)
1500 if (pp
->children
[(pp
->output_owner
+ i
) % n
].state
== GIT_CP_WORKING
)
1502 pp
->output_owner
= (pp
->output_owner
+ i
) % n
;
1508 int run_processes_parallel(int n
,
1509 get_next_task_fn get_next_task
,
1510 start_failure_fn start_failure
,
1511 task_finished_fn task_finished
,
1515 int output_timeout
= 100;
1517 struct parallel_processes pp
;
1519 pp_init(&pp
, n
, get_next_task
, start_failure
, task_finished
, pp_cb
);
1522 i
< spawn_cap
&& !pp
.shutdown
&&
1523 pp
.nr_processes
< pp
.max_processes
;
1525 code
= pp_start_one(&pp
);
1530 kill_children(&pp
, -code
);
1534 if (!pp
.nr_processes
)
1536 pp_buffer_stderr(&pp
, output_timeout
);
1538 code
= pp_collect_finished(&pp
);
1542 kill_children(&pp
, -code
);