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 int 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 '/' characters, we have exec attempt to invoke the command
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
;
413 argv_array_clear(out
);
422 static char **prep_childenv(const char *const *deltaenv
)
424 extern char **environ
;
426 struct string_list env
= STRING_LIST_INIT_DUP
;
427 struct strbuf key
= STRBUF_INIT
;
428 const char *const *p
;
431 /* Construct a sorted string list consisting of the current environ */
432 for (p
= (const char *const *) environ
; p
&& *p
; p
++) {
433 const char *equals
= strchr(*p
, '=');
437 strbuf_add(&key
, *p
, equals
- *p
);
438 string_list_append(&env
, key
.buf
)->util
= (void *) *p
;
440 string_list_append(&env
, *p
)->util
= (void *) *p
;
443 string_list_sort(&env
);
445 /* Merge in 'deltaenv' with the current environ */
446 for (p
= deltaenv
; p
&& *p
; p
++) {
447 const char *equals
= strchr(*p
, '=');
450 /* ('key=value'), insert or replace entry */
452 strbuf_add(&key
, *p
, equals
- *p
);
453 string_list_insert(&env
, key
.buf
)->util
= (void *) *p
;
455 /* otherwise ('key') remove existing entry */
456 string_list_remove(&env
, *p
, 0);
460 /* Create an array of 'char *' to be used as the childenv */
461 ALLOC_ARRAY(childenv
, env
.nr
+ 1);
462 for (i
= 0; i
< env
.nr
; i
++)
463 childenv
[i
] = env
.items
[i
].util
;
464 childenv
[env
.nr
] = NULL
;
466 string_list_clear(&env
, 0);
467 strbuf_release(&key
);
471 struct atfork_state
{
479 static void bug_die(int err
, const char *msg
)
483 die_errno("BUG: %s", msg
);
488 static void atfork_prepare(struct atfork_state
*as
)
492 if (sigfillset(&all
))
493 die_errno("sigfillset");
495 if (sigprocmask(SIG_SETMASK
, &all
, &as
->old
))
496 die_errno("sigprocmask");
498 bug_die(pthread_sigmask(SIG_SETMASK
, &all
, &as
->old
),
499 "blocking all signals");
500 bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &as
->cs
),
501 "disabling cancellation");
505 static void atfork_parent(struct atfork_state
*as
)
508 if (sigprocmask(SIG_SETMASK
, &as
->old
, NULL
))
509 die_errno("sigprocmask");
511 bug_die(pthread_setcancelstate(as
->cs
, NULL
),
512 "re-enabling cancellation");
513 bug_die(pthread_sigmask(SIG_SETMASK
, &as
->old
, NULL
),
514 "restoring signal mask");
517 #endif /* GIT_WINDOWS_NATIVE */
519 static inline void set_cloexec(int fd
)
521 int flags
= fcntl(fd
, F_GETFD
);
523 fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
526 static int wait_or_whine(pid_t pid
, const char *argv0
, int in_signal
)
528 int status
, code
= -1;
530 int failed_errno
= 0;
532 while ((waiting
= waitpid(pid
, &status
, 0)) < 0 && errno
== EINTR
)
538 failed_errno
= errno
;
539 error_errno("waitpid for %s failed", argv0
);
540 } else if (waiting
!= pid
) {
541 error("waitpid is confused (%s)", argv0
);
542 } else if (WIFSIGNALED(status
)) {
543 code
= WTERMSIG(status
);
544 if (code
!= SIGINT
&& code
!= SIGQUIT
&& code
!= SIGPIPE
)
545 error("%s died of signal %d", argv0
, code
);
547 * This return value is chosen so that code & 0xff
548 * mimics the exit code that a POSIX shell would report for
549 * a program that died from this signal.
552 } else if (WIFEXITED(status
)) {
553 code
= WEXITSTATUS(status
);
555 error("waitpid is confused (%s)", argv0
);
558 clear_child_for_cleanup(pid
);
560 errno
= failed_errno
;
564 int start_command(struct child_process
*cmd
)
566 int need_in
, need_out
, need_err
;
567 int fdin
[2], fdout
[2], fderr
[2];
572 cmd
->argv
= cmd
->args
.argv
;
574 cmd
->env
= cmd
->env_array
.argv
;
577 * In case of errors we must keep the promise to close FDs
578 * that have been passed in via ->in and ->out.
581 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
583 if (pipe(fdin
) < 0) {
584 failed_errno
= errno
;
587 str
= "standard input";
593 need_out
= !cmd
->no_stdout
594 && !cmd
->stdout_to_stderr
597 if (pipe(fdout
) < 0) {
598 failed_errno
= errno
;
603 str
= "standard output";
609 need_err
= !cmd
->no_stderr
&& cmd
->err
< 0;
611 if (pipe(fderr
) < 0) {
612 failed_errno
= errno
;
621 str
= "standard error";
623 error("cannot create %s pipe for %s: %s",
624 str
, cmd
->argv
[0], strerror(failed_errno
));
625 child_process_clear(cmd
);
626 errno
= failed_errno
;
632 trace_argv_printf(cmd
->argv
, "trace: run_command:");
635 #ifndef GIT_WINDOWS_NATIVE
640 struct argv_array argv
= ARGV_ARRAY_INIT
;
641 struct child_err cerr
;
642 struct atfork_state as
;
644 if (prepare_cmd(&argv
, cmd
) < 0) {
645 failed_errno
= errno
;
650 if (pipe(notify_pipe
))
651 notify_pipe
[0] = notify_pipe
[1] = -1;
653 if (cmd
->no_stdin
|| cmd
->no_stdout
|| cmd
->no_stderr
) {
654 null_fd
= open("/dev/null", O_RDWR
| O_CLOEXEC
);
656 die_errno(_("open /dev/null failed"));
657 set_cloexec(null_fd
);
660 childenv
= prep_childenv(cmd
->env
);
664 * NOTE: In order to prevent deadlocking when using threads special
665 * care should be taken with the function calls made in between the
666 * fork() and exec() calls. No calls should be made to functions which
667 * require acquiring a lock (e.g. malloc) as the lock could have been
668 * held by another thread at the time of forking, causing the lock to
669 * never be released in the child process. This means only
670 * Async-Signal-Safe functions are permitted in the child.
673 failed_errno
= errno
;
677 * Ensure the default die/error/warn routines do not get
678 * called, they can take stdio locks and malloc.
680 set_die_routine(child_die_fn
);
681 set_error_routine(child_error_fn
);
682 set_warn_routine(child_warn_fn
);
684 close(notify_pipe
[0]);
685 set_cloexec(notify_pipe
[1]);
686 child_notifier
= notify_pipe
[1];
689 child_dup2(null_fd
, 0);
691 child_dup2(fdin
[0], 0);
692 child_close_pair(fdin
);
693 } else if (cmd
->in
) {
694 child_dup2(cmd
->in
, 0);
695 child_close(cmd
->in
);
699 child_dup2(null_fd
, 2);
701 child_dup2(fderr
[1], 2);
702 child_close_pair(fderr
);
703 } else if (cmd
->err
> 1) {
704 child_dup2(cmd
->err
, 2);
705 child_close(cmd
->err
);
709 child_dup2(null_fd
, 1);
710 else if (cmd
->stdout_to_stderr
)
713 child_dup2(fdout
[1], 1);
714 child_close_pair(fdout
);
715 } else if (cmd
->out
> 1) {
716 child_dup2(cmd
->out
, 1);
717 child_close(cmd
->out
);
720 if (cmd
->dir
&& chdir(cmd
->dir
))
721 child_die(CHILD_ERR_CHDIR
);
724 * restore default signal handlers here, in case
725 * we catch a signal right before execve below
727 for (sig
= 1; sig
< NSIG
; sig
++) {
728 /* ignored signals get reset to SIG_DFL on execve */
729 if (signal(sig
, SIG_DFL
) == SIG_IGN
)
730 signal(sig
, SIG_IGN
);
733 if (sigprocmask(SIG_SETMASK
, &as
.old
, NULL
) != 0)
734 child_die(CHILD_ERR_SIGPROCMASK
);
737 * Attempt to exec using the command and arguments starting at
738 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
739 * be used in the event exec failed with ENOEXEC at which point
740 * we will try to interpret the command using 'sh'.
742 execve(argv
.argv
[1], (char *const *) argv
.argv
+ 1,
743 (char *const *) childenv
);
744 if (errno
== ENOEXEC
)
745 execve(argv
.argv
[0], (char *const *) argv
.argv
,
746 (char *const *) childenv
);
748 if (errno
== ENOENT
) {
749 if (cmd
->silent_exec_failure
)
750 child_die(CHILD_ERR_SILENT
);
751 child_die(CHILD_ERR_ENOENT
);
753 child_die(CHILD_ERR_ERRNO
);
758 error_errno("cannot fork() for %s", cmd
->argv
[0]);
759 else if (cmd
->clean_on_exit
)
760 mark_child_for_cleanup(cmd
->pid
, cmd
);
763 * Wait for child's exec. If the exec succeeds (or if fork()
764 * failed), EOF is seen immediately by the parent. Otherwise, the
765 * child process sends a child_err struct.
766 * Note that use of this infrastructure is completely advisory,
767 * therefore, we keep error checks minimal.
769 close(notify_pipe
[1]);
770 if (xread(notify_pipe
[0], &cerr
, sizeof(cerr
)) == sizeof(cerr
)) {
772 * At this point we know that fork() succeeded, but exec()
773 * failed. Errors have been reported to our stderr.
775 wait_or_whine(cmd
->pid
, cmd
->argv
[0], 0);
776 child_err_spew(cmd
, &cerr
);
777 failed_errno
= errno
;
780 close(notify_pipe
[0]);
784 argv_array_clear(&argv
);
791 int fhin
= 0, fhout
= 1, fherr
= 2;
792 const char **sargv
= cmd
->argv
;
793 struct argv_array nargv
= ARGV_ARRAY_INIT
;
796 fhin
= open("/dev/null", O_RDWR
);
803 fherr
= open("/dev/null", O_RDWR
);
805 fherr
= dup(fderr
[1]);
806 else if (cmd
->err
> 2)
807 fherr
= dup(cmd
->err
);
810 fhout
= open("/dev/null", O_RDWR
);
811 else if (cmd
->stdout_to_stderr
)
814 fhout
= dup(fdout
[1]);
815 else if (cmd
->out
> 1)
816 fhout
= dup(cmd
->out
);
819 cmd
->argv
= prepare_git_cmd(&nargv
, cmd
->argv
);
820 else if (cmd
->use_shell
)
821 cmd
->argv
= prepare_shell_cmd(&nargv
, cmd
->argv
);
823 cmd
->pid
= mingw_spawnvpe(cmd
->argv
[0], cmd
->argv
, (char**) cmd
->env
,
824 cmd
->dir
, fhin
, fhout
, fherr
);
825 failed_errno
= errno
;
826 if (cmd
->pid
< 0 && (!cmd
->silent_exec_failure
|| errno
!= ENOENT
))
827 error_errno("cannot spawn %s", cmd
->argv
[0]);
828 if (cmd
->clean_on_exit
&& cmd
->pid
>= 0)
829 mark_child_for_cleanup(cmd
->pid
, cmd
);
831 argv_array_clear(&nargv
);
855 child_process_clear(cmd
);
856 errno
= failed_errno
;
878 int finish_command(struct child_process
*cmd
)
880 int ret
= wait_or_whine(cmd
->pid
, cmd
->argv
[0], 0);
881 child_process_clear(cmd
);
885 int finish_command_in_signal(struct child_process
*cmd
)
887 return wait_or_whine(cmd
->pid
, cmd
->argv
[0], 1);
891 int run_command(struct child_process
*cmd
)
895 if (cmd
->out
< 0 || cmd
->err
< 0)
896 die("BUG: run_command with a pipe can cause deadlock");
898 code
= start_command(cmd
);
901 return finish_command(cmd
);
904 int run_command_v_opt(const char **argv
, int opt
)
906 return run_command_v_opt_cd_env(argv
, opt
, NULL
, NULL
);
909 int run_command_v_opt_cd_env(const char **argv
, int opt
, const char *dir
, const char *const *env
)
911 struct child_process cmd
= CHILD_PROCESS_INIT
;
913 cmd
.no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
914 cmd
.git_cmd
= opt
& RUN_GIT_CMD
? 1 : 0;
915 cmd
.stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
916 cmd
.silent_exec_failure
= opt
& RUN_SILENT_EXEC_FAILURE
? 1 : 0;
917 cmd
.use_shell
= opt
& RUN_USING_SHELL
? 1 : 0;
918 cmd
.clean_on_exit
= opt
& RUN_CLEAN_ON_EXIT
? 1 : 0;
921 return run_command(&cmd
);
925 static pthread_t main_thread
;
926 static int main_thread_set
;
927 static pthread_key_t async_key
;
928 static pthread_key_t async_die_counter
;
930 static void *run_thread(void *data
)
932 struct async
*async
= data
;
935 if (async
->isolate_sigpipe
) {
938 sigaddset(&mask
, SIGPIPE
);
939 if (pthread_sigmask(SIG_BLOCK
, &mask
, NULL
) < 0) {
940 ret
= error("unable to block SIGPIPE in async thread");
945 pthread_setspecific(async_key
, async
);
946 ret
= async
->proc(async
->proc_in
, async
->proc_out
, async
->data
);
950 static NORETURN
void die_async(const char *err
, va_list params
)
952 vreportf("fatal: ", err
, params
);
955 struct async
*async
= pthread_getspecific(async_key
);
956 if (async
->proc_in
>= 0)
957 close(async
->proc_in
);
958 if (async
->proc_out
>= 0)
959 close(async
->proc_out
);
960 pthread_exit((void *)128);
966 static int async_die_is_recursing(void)
968 void *ret
= pthread_getspecific(async_die_counter
);
969 pthread_setspecific(async_die_counter
, (void *)1);
975 if (!main_thread_set
)
976 return 0; /* no asyncs started yet */
977 return !pthread_equal(main_thread
, pthread_self());
980 static void NORETURN
async_exit(int code
)
982 pthread_exit((void *)(intptr_t)code
);
988 void (**handlers
)(void);
993 static int git_atexit_installed
;
995 static void git_atexit_dispatch(void)
999 for (i
=git_atexit_hdlrs
.nr
; i
; i
--)
1000 git_atexit_hdlrs
.handlers
[i
-1]();
1003 static void git_atexit_clear(void)
1005 free(git_atexit_hdlrs
.handlers
);
1006 memset(&git_atexit_hdlrs
, 0, sizeof(git_atexit_hdlrs
));
1007 git_atexit_installed
= 0;
1011 int git_atexit(void (*handler
)(void))
1013 ALLOC_GROW(git_atexit_hdlrs
.handlers
, git_atexit_hdlrs
.nr
+ 1, git_atexit_hdlrs
.alloc
);
1014 git_atexit_hdlrs
.handlers
[git_atexit_hdlrs
.nr
++] = handler
;
1015 if (!git_atexit_installed
) {
1016 if (atexit(&git_atexit_dispatch
))
1018 git_atexit_installed
= 1;
1022 #define atexit git_atexit
1024 static int process_is_async
;
1027 return process_is_async
;
1030 static void NORETURN
async_exit(int code
)
1037 void check_pipe(int err
)
1043 signal(SIGPIPE
, SIG_DFL
);
1045 /* Should never happen, but just in case... */
1050 int start_async(struct async
*async
)
1052 int need_in
, need_out
;
1053 int fdin
[2], fdout
[2];
1054 int proc_in
, proc_out
;
1056 need_in
= async
->in
< 0;
1058 if (pipe(fdin
) < 0) {
1061 return error_errno("cannot create pipe");
1063 async
->in
= fdin
[1];
1066 need_out
= async
->out
< 0;
1068 if (pipe(fdout
) < 0) {
1073 return error_errno("cannot create pipe");
1075 async
->out
= fdout
[0];
1081 proc_in
= async
->in
;
1086 proc_out
= fdout
[1];
1087 else if (async
->out
)
1088 proc_out
= async
->out
;
1093 /* Flush stdio before fork() to avoid cloning buffers */
1096 async
->pid
= fork();
1097 if (async
->pid
< 0) {
1098 error_errno("fork (async) failed");
1107 process_is_async
= 1;
1108 exit(!!async
->proc(proc_in
, proc_out
, async
->data
));
1111 mark_child_for_cleanup(async
->pid
, NULL
);
1120 else if (async
->out
)
1123 if (!main_thread_set
) {
1125 * We assume that the first time that start_async is called
1126 * it is from the main thread.
1128 main_thread_set
= 1;
1129 main_thread
= pthread_self();
1130 pthread_key_create(&async_key
, NULL
);
1131 pthread_key_create(&async_die_counter
, NULL
);
1132 set_die_routine(die_async
);
1133 set_die_is_recursing_routine(async_die_is_recursing
);
1137 set_cloexec(proc_in
);
1139 set_cloexec(proc_out
);
1140 async
->proc_in
= proc_in
;
1141 async
->proc_out
= proc_out
;
1143 int err
= pthread_create(&async
->tid
, NULL
, run_thread
, async
);
1145 error_errno("cannot create thread");
1160 else if (async
->out
)
1165 int finish_async(struct async
*async
)
1168 return wait_or_whine(async
->pid
, "child process", 0);
1170 void *ret
= (void *)(intptr_t)(-1);
1172 if (pthread_join(async
->tid
, &ret
))
1173 error("pthread_join failed");
1174 return (int)(intptr_t)ret
;
1178 const char *find_hook(const char *name
)
1180 static struct strbuf path
= STRBUF_INIT
;
1182 strbuf_reset(&path
);
1183 strbuf_git_path(&path
, "hooks/%s", name
);
1184 if (access(path
.buf
, X_OK
) < 0) {
1185 #ifdef STRIP_EXTENSION
1186 strbuf_addstr(&path
, STRIP_EXTENSION
);
1187 if (access(path
.buf
, X_OK
) >= 0)
1195 int run_hook_ve(const char *const *env
, const char *name
, va_list args
)
1197 struct child_process hook
= CHILD_PROCESS_INIT
;
1200 p
= find_hook(name
);
1204 argv_array_push(&hook
.args
, p
);
1205 while ((p
= va_arg(args
, const char *)))
1206 argv_array_push(&hook
.args
, p
);
1209 hook
.stdout_to_stderr
= 1;
1211 return run_command(&hook
);
1214 int run_hook_le(const char *const *env
, const char *name
, ...)
1219 va_start(args
, name
);
1220 ret
= run_hook_ve(env
, name
, args
);
1227 /* initialized by caller */
1229 int type
; /* POLLOUT or POLLIN */
1241 /* returned by pump_io */
1242 int error
; /* 0 for success, otherwise errno */
1248 static int pump_io_round(struct io_pump
*slots
, int nr
, struct pollfd
*pfd
)
1253 for (i
= 0; i
< nr
; i
++) {
1254 struct io_pump
*io
= &slots
[i
];
1257 pfd
[pollsize
].fd
= io
->fd
;
1258 pfd
[pollsize
].events
= io
->type
;
1259 io
->pfd
= &pfd
[pollsize
++];
1265 if (poll(pfd
, pollsize
, -1) < 0) {
1268 die_errno("poll failed");
1271 for (i
= 0; i
< nr
; i
++) {
1272 struct io_pump
*io
= &slots
[i
];
1277 if (!(io
->pfd
->revents
& (POLLOUT
|POLLIN
|POLLHUP
|POLLERR
|POLLNVAL
)))
1280 if (io
->type
== POLLOUT
) {
1281 ssize_t len
= xwrite(io
->fd
,
1282 io
->u
.out
.buf
, io
->u
.out
.len
);
1288 io
->u
.out
.buf
+= len
;
1289 io
->u
.out
.len
-= len
;
1290 if (!io
->u
.out
.len
) {
1297 if (io
->type
== POLLIN
) {
1298 ssize_t len
= strbuf_read_once(io
->u
.in
.buf
,
1299 io
->fd
, io
->u
.in
.hint
);
1312 static int pump_io(struct io_pump
*slots
, int nr
)
1317 for (i
= 0; i
< nr
; i
++)
1320 ALLOC_ARRAY(pfd
, nr
);
1321 while (pump_io_round(slots
, nr
, pfd
))
1325 /* There may be multiple errno values, so just pick the first. */
1326 for (i
= 0; i
< nr
; i
++) {
1327 if (slots
[i
].error
) {
1328 errno
= slots
[i
].error
;
1336 int pipe_command(struct child_process
*cmd
,
1337 const char *in
, size_t in_len
,
1338 struct strbuf
*out
, size_t out_hint
,
1339 struct strbuf
*err
, size_t err_hint
)
1341 struct io_pump io
[3];
1351 if (start_command(cmd
) < 0)
1355 io
[nr
].fd
= cmd
->in
;
1356 io
[nr
].type
= POLLOUT
;
1357 io
[nr
].u
.out
.buf
= in
;
1358 io
[nr
].u
.out
.len
= in_len
;
1362 io
[nr
].fd
= cmd
->out
;
1363 io
[nr
].type
= POLLIN
;
1364 io
[nr
].u
.in
.buf
= out
;
1365 io
[nr
].u
.in
.hint
= out_hint
;
1369 io
[nr
].fd
= cmd
->err
;
1370 io
[nr
].type
= POLLIN
;
1371 io
[nr
].u
.in
.buf
= err
;
1372 io
[nr
].u
.in
.hint
= err_hint
;
1376 if (pump_io(io
, nr
) < 0) {
1377 finish_command(cmd
); /* throw away exit code */
1381 return finish_command(cmd
);
1387 GIT_CP_WAIT_CLEANUP
,
1390 struct parallel_processes
{
1396 get_next_task_fn get_next_task
;
1397 start_failure_fn start_failure
;
1398 task_finished_fn task_finished
;
1401 enum child_state state
;
1402 struct child_process process
;
1407 * The struct pollfd is logically part of *children,
1408 * but the system call expects it as its own array.
1412 unsigned shutdown
: 1;
1415 struct strbuf buffered_output
; /* of finished children */
1418 static int default_start_failure(struct strbuf
*out
,
1425 static int default_task_finished(int result
,
1433 static void kill_children(struct parallel_processes
*pp
, int signo
)
1435 int i
, n
= pp
->max_processes
;
1437 for (i
= 0; i
< n
; i
++)
1438 if (pp
->children
[i
].state
== GIT_CP_WORKING
)
1439 kill(pp
->children
[i
].process
.pid
, signo
);
1442 static struct parallel_processes
*pp_for_signal
;
1444 static void handle_children_on_signal(int signo
)
1446 kill_children(pp_for_signal
, signo
);
1447 sigchain_pop(signo
);
1451 static void pp_init(struct parallel_processes
*pp
,
1453 get_next_task_fn get_next_task
,
1454 start_failure_fn start_failure
,
1455 task_finished_fn task_finished
,
1463 pp
->max_processes
= n
;
1465 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n
);
1469 die("BUG: you need to specify a get_next_task function");
1470 pp
->get_next_task
= get_next_task
;
1472 pp
->start_failure
= start_failure
? start_failure
: default_start_failure
;
1473 pp
->task_finished
= task_finished
? task_finished
: default_task_finished
;
1475 pp
->nr_processes
= 0;
1476 pp
->output_owner
= 0;
1478 pp
->children
= xcalloc(n
, sizeof(*pp
->children
));
1479 pp
->pfd
= xcalloc(n
, sizeof(*pp
->pfd
));
1480 strbuf_init(&pp
->buffered_output
, 0);
1482 for (i
= 0; i
< n
; i
++) {
1483 strbuf_init(&pp
->children
[i
].err
, 0);
1484 child_process_init(&pp
->children
[i
].process
);
1485 pp
->pfd
[i
].events
= POLLIN
| POLLHUP
;
1490 sigchain_push_common(handle_children_on_signal
);
1493 static void pp_cleanup(struct parallel_processes
*pp
)
1497 trace_printf("run_processes_parallel: done");
1498 for (i
= 0; i
< pp
->max_processes
; i
++) {
1499 strbuf_release(&pp
->children
[i
].err
);
1500 child_process_clear(&pp
->children
[i
].process
);
1507 * When get_next_task added messages to the buffer in its last
1508 * iteration, the buffered output is non empty.
1510 strbuf_write(&pp
->buffered_output
, stderr
);
1511 strbuf_release(&pp
->buffered_output
);
1513 sigchain_pop_common();
1517 * 0 if a new task was started.
1518 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1519 * problem with starting a new command)
1520 * <0 no new job was started, user wishes to shutdown early. Use negative code
1521 * to signal the children.
1523 static int pp_start_one(struct parallel_processes
*pp
)
1527 for (i
= 0; i
< pp
->max_processes
; i
++)
1528 if (pp
->children
[i
].state
== GIT_CP_FREE
)
1530 if (i
== pp
->max_processes
)
1531 die("BUG: bookkeeping is hard");
1533 code
= pp
->get_next_task(&pp
->children
[i
].process
,
1534 &pp
->children
[i
].err
,
1536 &pp
->children
[i
].data
);
1538 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1539 strbuf_reset(&pp
->children
[i
].err
);
1542 pp
->children
[i
].process
.err
= -1;
1543 pp
->children
[i
].process
.stdout_to_stderr
= 1;
1544 pp
->children
[i
].process
.no_stdin
= 1;
1546 if (start_command(&pp
->children
[i
].process
)) {
1547 code
= pp
->start_failure(&pp
->children
[i
].err
,
1549 pp
->children
[i
].data
);
1550 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1551 strbuf_reset(&pp
->children
[i
].err
);
1558 pp
->children
[i
].state
= GIT_CP_WORKING
;
1559 pp
->pfd
[i
].fd
= pp
->children
[i
].process
.err
;
1563 static void pp_buffer_stderr(struct parallel_processes
*pp
, int output_timeout
)
1567 while ((i
= poll(pp
->pfd
, pp
->max_processes
, output_timeout
)) < 0) {
1574 /* Buffer output from all pipes. */
1575 for (i
= 0; i
< pp
->max_processes
; i
++) {
1576 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1577 pp
->pfd
[i
].revents
& (POLLIN
| POLLHUP
)) {
1578 int n
= strbuf_read_once(&pp
->children
[i
].err
,
1579 pp
->children
[i
].process
.err
, 0);
1581 close(pp
->children
[i
].process
.err
);
1582 pp
->children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1584 if (errno
!= EAGAIN
)
1590 static void pp_output(struct parallel_processes
*pp
)
1592 int i
= pp
->output_owner
;
1593 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1594 pp
->children
[i
].err
.len
) {
1595 strbuf_write(&pp
->children
[i
].err
, stderr
);
1596 strbuf_reset(&pp
->children
[i
].err
);
1600 static int pp_collect_finished(struct parallel_processes
*pp
)
1603 int n
= pp
->max_processes
;
1606 while (pp
->nr_processes
> 0) {
1607 for (i
= 0; i
< pp
->max_processes
; i
++)
1608 if (pp
->children
[i
].state
== GIT_CP_WAIT_CLEANUP
)
1610 if (i
== pp
->max_processes
)
1613 code
= finish_command(&pp
->children
[i
].process
);
1615 code
= pp
->task_finished(code
,
1616 &pp
->children
[i
].err
, pp
->data
,
1617 pp
->children
[i
].data
);
1625 pp
->children
[i
].state
= GIT_CP_FREE
;
1627 child_process_init(&pp
->children
[i
].process
);
1629 if (i
!= pp
->output_owner
) {
1630 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1631 strbuf_reset(&pp
->children
[i
].err
);
1633 strbuf_write(&pp
->children
[i
].err
, stderr
);
1634 strbuf_reset(&pp
->children
[i
].err
);
1636 /* Output all other finished child processes */
1637 strbuf_write(&pp
->buffered_output
, stderr
);
1638 strbuf_reset(&pp
->buffered_output
);
1641 * Pick next process to output live.
1643 * For now we pick it randomly by doing a round
1644 * robin. Later we may want to pick the one with
1645 * the most output or the longest or shortest
1646 * running process time.
1648 for (i
= 0; i
< n
; i
++)
1649 if (pp
->children
[(pp
->output_owner
+ i
) % n
].state
== GIT_CP_WORKING
)
1651 pp
->output_owner
= (pp
->output_owner
+ i
) % n
;
1657 int run_processes_parallel(int n
,
1658 get_next_task_fn get_next_task
,
1659 start_failure_fn start_failure
,
1660 task_finished_fn task_finished
,
1664 int output_timeout
= 100;
1666 struct parallel_processes pp
;
1668 pp_init(&pp
, n
, get_next_task
, start_failure
, task_finished
, pp_cb
);
1671 i
< spawn_cap
&& !pp
.shutdown
&&
1672 pp
.nr_processes
< pp
.max_processes
;
1674 code
= pp_start_one(&pp
);
1679 kill_children(&pp
, -code
);
1683 if (!pp
.nr_processes
)
1685 pp_buffer_stderr(&pp
, output_timeout
);
1687 code
= pp_collect_finished(&pp
);
1691 kill_children(&pp
, -code
);