2 #include "run-command.h"
5 #include "argv-array.h"
6 #include "thread-utils.h"
8 #include "string-list.h"
10 void child_process_init(struct child_process
*child
)
12 memset(child
, 0, sizeof(*child
));
13 argv_array_init(&child
->args
);
14 argv_array_init(&child
->env_array
);
17 void child_process_clear(struct child_process
*child
)
19 argv_array_clear(&child
->args
);
20 argv_array_clear(&child
->env_array
);
23 struct child_to_clean
{
25 struct child_process
*process
;
26 struct child_to_clean
*next
;
28 static struct child_to_clean
*children_to_clean
;
29 static int installed_child_cleanup_handler
;
31 static void cleanup_children(int sig
, int in_signal
)
33 struct child_to_clean
*children_to_wait_for
= NULL
;
35 while (children_to_clean
) {
36 struct child_to_clean
*p
= children_to_clean
;
37 children_to_clean
= p
->next
;
39 if (p
->process
&& !in_signal
) {
40 struct child_process
*process
= p
->process
;
41 if (process
->clean_on_exit_handler
) {
43 "trace: run_command: running exit handler for pid %"
44 PRIuMAX
, (uintmax_t)p
->pid
46 process
->clean_on_exit_handler(process
);
52 if (p
->process
&& p
->process
->wait_after_clean
) {
53 p
->next
= children_to_wait_for
;
54 children_to_wait_for
= p
;
61 while (children_to_wait_for
) {
62 struct child_to_clean
*p
= children_to_wait_for
;
63 children_to_wait_for
= p
->next
;
65 while (waitpid(p
->pid
, NULL
, 0) < 0 && errno
== EINTR
)
66 ; /* spin waiting for process exit or error */
73 static void cleanup_children_on_signal(int sig
)
75 cleanup_children(sig
, 1);
80 static void cleanup_children_on_exit(void)
82 cleanup_children(SIGTERM
, 0);
85 static void mark_child_for_cleanup(pid_t pid
, struct child_process
*process
)
87 struct child_to_clean
*p
= xmalloc(sizeof(*p
));
90 p
->next
= children_to_clean
;
91 children_to_clean
= p
;
93 if (!installed_child_cleanup_handler
) {
94 atexit(cleanup_children_on_exit
);
95 sigchain_push_common(cleanup_children_on_signal
);
96 installed_child_cleanup_handler
= 1;
100 static void clear_child_for_cleanup(pid_t pid
)
102 struct child_to_clean
**pp
;
104 for (pp
= &children_to_clean
; *pp
; pp
= &(*pp
)->next
) {
105 struct child_to_clean
*clean_me
= *pp
;
107 if (clean_me
->pid
== pid
) {
108 *pp
= clean_me
->next
;
115 static inline void close_pair(int fd
[2])
121 int is_executable(const char *name
)
125 if (stat(name
, &st
) || /* stat, not lstat */
126 !S_ISREG(st
.st_mode
))
129 #if defined(GIT_WINDOWS_NATIVE)
131 * On Windows there is no executable bit. The file extension
132 * indicates whether it can be run as an executable, and Git
133 * has special-handling to detect scripts and launch them
134 * through the indicated script interpreter. We test for the
135 * file extension first because virus scanners may make
136 * it quite expensive to open many files.
138 if (ends_with(name
, ".exe"))
143 * Now that we know it does not have an executable extension,
144 * peek into the file instead.
148 int fd
= open(name
, O_RDONLY
);
149 st
.st_mode
&= ~S_IXUSR
;
151 n
= read(fd
, buf
, 2);
153 /* look for a she-bang */
154 if (!strcmp(buf
, "#!"))
155 st
.st_mode
|= S_IXUSR
;
160 return st
.st_mode
& S_IXUSR
;
164 * Search $PATH for a command. This emulates the path search that
165 * execvp would perform, without actually executing the command so it
166 * can be used before fork() to prepare to run a command using
167 * execve() or after execvp() to diagnose why it failed.
169 * The caller should ensure that file contains no directory
172 * Returns the path to the command, as found in $PATH or NULL if the
173 * command could not be found. The caller inherits ownership of the memory
174 * used to store the resultant path.
176 * This should not be used on Windows, where the $PATH search rules
177 * are more complicated (e.g., a search for "foo" should find
180 static char *locate_in_PATH(const char *file
)
182 const char *p
= getenv("PATH");
183 struct strbuf buf
= STRBUF_INIT
;
189 const char *end
= strchrnul(p
, ':');
193 /* POSIX specifies an empty entry as the current directory. */
195 strbuf_add(&buf
, p
, end
- p
);
196 strbuf_addch(&buf
, '/');
198 strbuf_addstr(&buf
, file
);
200 if (is_executable(buf
.buf
))
201 return strbuf_detach(&buf
, NULL
);
208 strbuf_release(&buf
);
212 static int exists_in_PATH(const char *file
)
214 char *r
= locate_in_PATH(file
);
219 int sane_execvp(const char *file
, char * const argv
[])
221 if (!execvp(file
, argv
))
222 return 0; /* cannot happen ;-) */
225 * When a command can't be found because one of the directories
226 * listed in $PATH is unsearchable, execvp reports EACCES, but
227 * careful usability testing (read: analysis of occasional bug
228 * reports) reveals that "No such file or directory" is more
231 * We avoid commands with "/", because execvp will not do $PATH
232 * lookups in that case.
234 * The reassignment of EACCES to errno looks like a no-op below,
235 * but we need to protect against exists_in_PATH overwriting errno.
237 if (errno
== EACCES
&& !strchr(file
, '/'))
238 errno
= exists_in_PATH(file
) ? EACCES
: ENOENT
;
239 else if (errno
== ENOTDIR
&& !strchr(file
, '/'))
244 static const char **prepare_shell_cmd(struct argv_array
*out
, const char **argv
)
247 die("BUG: shell command is empty");
249 if (strcspn(argv
[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv
[0])) {
250 #ifndef GIT_WINDOWS_NATIVE
251 argv_array_push(out
, SHELL_PATH
);
253 argv_array_push(out
, "sh");
255 argv_array_push(out
, "-c");
258 * If we have no extra arguments, we do not even need to
259 * bother with the "$@" magic.
262 argv_array_push(out
, argv
[0]);
264 argv_array_pushf(out
, "%s \"$@\"", argv
[0]);
267 argv_array_pushv(out
, argv
);
271 #ifndef GIT_WINDOWS_NATIVE
272 static int child_notifier
= -1;
278 CHILD_ERR_SIGPROCMASK
,
285 enum child_errcode err
;
286 int syserr
; /* errno */
289 static void child_die(enum child_errcode err
)
291 struct child_err buf
;
296 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
297 xwrite(child_notifier
, &buf
, sizeof(buf
));
301 static void child_dup2(int fd
, int to
)
303 if (dup2(fd
, to
) < 0)
304 child_die(CHILD_ERR_DUP2
);
307 static void child_close(int fd
)
310 child_die(CHILD_ERR_CLOSE
);
313 static void child_close_pair(int fd
[2])
320 * parent will make it look like the child spewed a fatal error and died
321 * this is needed to prevent changes to t0061.
323 static void fake_fatal(const char *err
, va_list params
)
325 vreportf("fatal: ", err
, params
);
328 static void child_error_fn(const char *err
, va_list params
)
330 const char msg
[] = "error() should not be called in child\n";
331 xwrite(2, msg
, sizeof(msg
) - 1);
334 static void child_warn_fn(const char *err
, va_list params
)
336 const char msg
[] = "warn() should not be called in child\n";
337 xwrite(2, msg
, sizeof(msg
) - 1);
340 static void NORETURN
child_die_fn(const char *err
, va_list params
)
342 const char msg
[] = "die() should not be called in child\n";
343 xwrite(2, msg
, sizeof(msg
) - 1);
347 /* this runs in the parent process */
348 static void child_err_spew(struct child_process
*cmd
, struct child_err
*cerr
)
350 static void (*old_errfn
)(const char *err
, va_list params
);
352 old_errfn
= get_error_routine();
353 set_error_routine(fake_fatal
);
354 errno
= cerr
->syserr
;
357 case CHILD_ERR_CHDIR
:
358 error_errno("exec '%s': cd to '%s' failed",
359 cmd
->argv
[0], cmd
->dir
);
362 error_errno("dup2() in child failed");
364 case CHILD_ERR_CLOSE
:
365 error_errno("close() in child failed");
367 case CHILD_ERR_SIGPROCMASK
:
368 error_errno("sigprocmask failed restoring signals");
370 case CHILD_ERR_ENOENT
:
371 error_errno("cannot run %s", cmd
->argv
[0]);
373 case CHILD_ERR_SILENT
:
375 case CHILD_ERR_ERRNO
:
376 error_errno("cannot exec '%s'", cmd
->argv
[0]);
379 set_error_routine(old_errfn
);
382 static void prepare_cmd(struct argv_array
*out
, const struct child_process
*cmd
)
385 die("BUG: command is empty");
388 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
389 * attempt to interpret the command with 'sh'.
391 argv_array_push(out
, SHELL_PATH
);
394 argv_array_push(out
, "git");
395 argv_array_pushv(out
, cmd
->argv
);
396 } else if (cmd
->use_shell
) {
397 prepare_shell_cmd(out
, cmd
->argv
);
399 argv_array_pushv(out
, cmd
->argv
);
403 * If there are no '/' characters in the command then perform a path
404 * lookup and use the resolved path as the command to exec. If there
405 * are no '/' characters or if the command wasn't found in the path,
406 * have exec attempt to invoke the command directly.
408 if (!strchr(out
->argv
[1], '/')) {
409 char *program
= locate_in_PATH(out
->argv
[1]);
411 free((char *)out
->argv
[1]);
412 out
->argv
[1] = program
;
417 static char **prep_childenv(const char *const *deltaenv
)
419 extern char **environ
;
421 struct string_list env
= STRING_LIST_INIT_DUP
;
422 struct strbuf key
= STRBUF_INIT
;
423 const char *const *p
;
426 /* Construct a sorted string list consisting of the current environ */
427 for (p
= (const char *const *) environ
; p
&& *p
; p
++) {
428 const char *equals
= strchr(*p
, '=');
432 strbuf_add(&key
, *p
, equals
- *p
);
433 string_list_append(&env
, key
.buf
)->util
= (void *) *p
;
435 string_list_append(&env
, *p
)->util
= (void *) *p
;
438 string_list_sort(&env
);
440 /* Merge in 'deltaenv' with the current environ */
441 for (p
= deltaenv
; p
&& *p
; p
++) {
442 const char *equals
= strchr(*p
, '=');
445 /* ('key=value'), insert or replace entry */
447 strbuf_add(&key
, *p
, equals
- *p
);
448 string_list_insert(&env
, key
.buf
)->util
= (void *) *p
;
450 /* otherwise ('key') remove existing entry */
451 string_list_remove(&env
, *p
, 0);
455 /* Create an array of 'char *' to be used as the childenv */
456 ALLOC_ARRAY(childenv
, env
.nr
+ 1);
457 for (i
= 0; i
< env
.nr
; i
++)
458 childenv
[i
] = env
.items
[i
].util
;
459 childenv
[env
.nr
] = NULL
;
461 string_list_clear(&env
, 0);
462 strbuf_release(&key
);
466 struct atfork_state
{
474 static void bug_die(int err
, const char *msg
)
478 die_errno("BUG: %s", msg
);
483 static void atfork_prepare(struct atfork_state
*as
)
487 if (sigfillset(&all
))
488 die_errno("sigfillset");
490 if (sigprocmask(SIG_SETMASK
, &all
, &as
->old
))
491 die_errno("sigprocmask");
493 bug_die(pthread_sigmask(SIG_SETMASK
, &all
, &as
->old
),
494 "blocking all signals");
495 bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &as
->cs
),
496 "disabling cancellation");
500 static void atfork_parent(struct atfork_state
*as
)
503 if (sigprocmask(SIG_SETMASK
, &as
->old
, NULL
))
504 die_errno("sigprocmask");
506 bug_die(pthread_setcancelstate(as
->cs
, NULL
),
507 "re-enabling cancellation");
508 bug_die(pthread_sigmask(SIG_SETMASK
, &as
->old
, NULL
),
509 "restoring signal mask");
512 #endif /* GIT_WINDOWS_NATIVE */
514 static inline void set_cloexec(int fd
)
516 int flags
= fcntl(fd
, F_GETFD
);
518 fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
521 static int wait_or_whine(pid_t pid
, const char *argv0
, int in_signal
)
523 int status
, code
= -1;
525 int failed_errno
= 0;
527 while ((waiting
= waitpid(pid
, &status
, 0)) < 0 && errno
== EINTR
)
533 failed_errno
= errno
;
534 error_errno("waitpid for %s failed", argv0
);
535 } else if (waiting
!= pid
) {
536 error("waitpid is confused (%s)", argv0
);
537 } else if (WIFSIGNALED(status
)) {
538 code
= WTERMSIG(status
);
539 if (code
!= SIGINT
&& code
!= SIGQUIT
&& code
!= SIGPIPE
)
540 error("%s died of signal %d", argv0
, code
);
542 * This return value is chosen so that code & 0xff
543 * mimics the exit code that a POSIX shell would report for
544 * a program that died from this signal.
547 } else if (WIFEXITED(status
)) {
548 code
= WEXITSTATUS(status
);
550 error("waitpid is confused (%s)", argv0
);
553 clear_child_for_cleanup(pid
);
555 errno
= failed_errno
;
559 int start_command(struct child_process
*cmd
)
561 int need_in
, need_out
, need_err
;
562 int fdin
[2], fdout
[2], fderr
[2];
567 cmd
->argv
= cmd
->args
.argv
;
569 cmd
->env
= cmd
->env_array
.argv
;
572 * In case of errors we must keep the promise to close FDs
573 * that have been passed in via ->in and ->out.
576 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
578 if (pipe(fdin
) < 0) {
579 failed_errno
= errno
;
582 str
= "standard input";
588 need_out
= !cmd
->no_stdout
589 && !cmd
->stdout_to_stderr
592 if (pipe(fdout
) < 0) {
593 failed_errno
= errno
;
598 str
= "standard output";
604 need_err
= !cmd
->no_stderr
&& cmd
->err
< 0;
606 if (pipe(fderr
) < 0) {
607 failed_errno
= errno
;
616 str
= "standard error";
618 error("cannot create %s pipe for %s: %s",
619 str
, cmd
->argv
[0], strerror(failed_errno
));
620 child_process_clear(cmd
);
621 errno
= failed_errno
;
627 trace_argv_printf(cmd
->argv
, "trace: run_command:");
630 #ifndef GIT_WINDOWS_NATIVE
635 struct argv_array argv
= ARGV_ARRAY_INIT
;
636 struct child_err cerr
;
637 struct atfork_state as
;
639 if (pipe(notify_pipe
))
640 notify_pipe
[0] = notify_pipe
[1] = -1;
642 if (cmd
->no_stdin
|| cmd
->no_stdout
|| cmd
->no_stderr
) {
643 null_fd
= open("/dev/null", O_RDWR
| O_CLOEXEC
);
645 die_errno(_("open /dev/null failed"));
646 set_cloexec(null_fd
);
649 prepare_cmd(&argv
, cmd
);
650 childenv
= prep_childenv(cmd
->env
);
654 * NOTE: In order to prevent deadlocking when using threads special
655 * care should be taken with the function calls made in between the
656 * fork() and exec() calls. No calls should be made to functions which
657 * require acquiring a lock (e.g. malloc) as the lock could have been
658 * held by another thread at the time of forking, causing the lock to
659 * never be released in the child process. This means only
660 * Async-Signal-Safe functions are permitted in the child.
663 failed_errno
= errno
;
667 * Ensure the default die/error/warn routines do not get
668 * called, they can take stdio locks and malloc.
670 set_die_routine(child_die_fn
);
671 set_error_routine(child_error_fn
);
672 set_warn_routine(child_warn_fn
);
674 close(notify_pipe
[0]);
675 set_cloexec(notify_pipe
[1]);
676 child_notifier
= notify_pipe
[1];
679 child_dup2(null_fd
, 0);
681 child_dup2(fdin
[0], 0);
682 child_close_pair(fdin
);
683 } else if (cmd
->in
) {
684 child_dup2(cmd
->in
, 0);
685 child_close(cmd
->in
);
689 child_dup2(null_fd
, 2);
691 child_dup2(fderr
[1], 2);
692 child_close_pair(fderr
);
693 } else if (cmd
->err
> 1) {
694 child_dup2(cmd
->err
, 2);
695 child_close(cmd
->err
);
699 child_dup2(null_fd
, 1);
700 else if (cmd
->stdout_to_stderr
)
703 child_dup2(fdout
[1], 1);
704 child_close_pair(fdout
);
705 } else if (cmd
->out
> 1) {
706 child_dup2(cmd
->out
, 1);
707 child_close(cmd
->out
);
710 if (cmd
->dir
&& chdir(cmd
->dir
))
711 child_die(CHILD_ERR_CHDIR
);
714 * restore default signal handlers here, in case
715 * we catch a signal right before execve below
717 for (sig
= 1; sig
< NSIG
; sig
++) {
718 /* ignored signals get reset to SIG_DFL on execve */
719 if (signal(sig
, SIG_DFL
) == SIG_IGN
)
720 signal(sig
, SIG_IGN
);
723 if (sigprocmask(SIG_SETMASK
, &as
.old
, NULL
) != 0)
724 child_die(CHILD_ERR_SIGPROCMASK
);
727 * Attempt to exec using the command and arguments starting at
728 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
729 * be used in the event exec failed with ENOEXEC at which point
730 * we will try to interpret the command using 'sh'.
732 execve(argv
.argv
[1], (char *const *) argv
.argv
+ 1,
733 (char *const *) childenv
);
734 if (errno
== ENOEXEC
)
735 execve(argv
.argv
[0], (char *const *) argv
.argv
,
736 (char *const *) childenv
);
738 if (errno
== ENOENT
) {
739 if (cmd
->silent_exec_failure
)
740 child_die(CHILD_ERR_SILENT
);
741 child_die(CHILD_ERR_ENOENT
);
743 child_die(CHILD_ERR_ERRNO
);
748 error_errno("cannot fork() for %s", cmd
->argv
[0]);
749 else if (cmd
->clean_on_exit
)
750 mark_child_for_cleanup(cmd
->pid
, cmd
);
753 * Wait for child's exec. If the exec succeeds (or if fork()
754 * failed), EOF is seen immediately by the parent. Otherwise, the
755 * child process sends a child_err struct.
756 * Note that use of this infrastructure is completely advisory,
757 * therefore, we keep error checks minimal.
759 close(notify_pipe
[1]);
760 if (xread(notify_pipe
[0], &cerr
, sizeof(cerr
)) == sizeof(cerr
)) {
762 * At this point we know that fork() succeeded, but exec()
763 * failed. Errors have been reported to our stderr.
765 wait_or_whine(cmd
->pid
, cmd
->argv
[0], 0);
766 child_err_spew(cmd
, &cerr
);
767 failed_errno
= errno
;
770 close(notify_pipe
[0]);
774 argv_array_clear(&argv
);
779 int fhin
= 0, fhout
= 1, fherr
= 2;
780 const char **sargv
= cmd
->argv
;
781 struct argv_array nargv
= ARGV_ARRAY_INIT
;
784 fhin
= open("/dev/null", O_RDWR
);
791 fherr
= open("/dev/null", O_RDWR
);
793 fherr
= dup(fderr
[1]);
794 else if (cmd
->err
> 2)
795 fherr
= dup(cmd
->err
);
798 fhout
= open("/dev/null", O_RDWR
);
799 else if (cmd
->stdout_to_stderr
)
802 fhout
= dup(fdout
[1]);
803 else if (cmd
->out
> 1)
804 fhout
= dup(cmd
->out
);
807 cmd
->argv
= prepare_git_cmd(&nargv
, cmd
->argv
);
808 else if (cmd
->use_shell
)
809 cmd
->argv
= prepare_shell_cmd(&nargv
, cmd
->argv
);
811 cmd
->pid
= mingw_spawnvpe(cmd
->argv
[0], cmd
->argv
, (char**) cmd
->env
,
812 cmd
->dir
, fhin
, fhout
, fherr
);
813 failed_errno
= errno
;
814 if (cmd
->pid
< 0 && (!cmd
->silent_exec_failure
|| errno
!= ENOENT
))
815 error_errno("cannot spawn %s", cmd
->argv
[0]);
816 if (cmd
->clean_on_exit
&& cmd
->pid
>= 0)
817 mark_child_for_cleanup(cmd
->pid
, cmd
);
819 argv_array_clear(&nargv
);
843 child_process_clear(cmd
);
844 errno
= failed_errno
;
866 int finish_command(struct child_process
*cmd
)
868 int ret
= wait_or_whine(cmd
->pid
, cmd
->argv
[0], 0);
869 child_process_clear(cmd
);
873 int finish_command_in_signal(struct child_process
*cmd
)
875 return wait_or_whine(cmd
->pid
, cmd
->argv
[0], 1);
879 int run_command(struct child_process
*cmd
)
883 if (cmd
->out
< 0 || cmd
->err
< 0)
884 die("BUG: run_command with a pipe can cause deadlock");
886 code
= start_command(cmd
);
889 return finish_command(cmd
);
892 int run_command_v_opt(const char **argv
, int opt
)
894 return run_command_v_opt_cd_env(argv
, opt
, NULL
, NULL
);
897 int run_command_v_opt_cd_env(const char **argv
, int opt
, const char *dir
, const char *const *env
)
899 struct child_process cmd
= CHILD_PROCESS_INIT
;
901 cmd
.no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
902 cmd
.git_cmd
= opt
& RUN_GIT_CMD
? 1 : 0;
903 cmd
.stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
904 cmd
.silent_exec_failure
= opt
& RUN_SILENT_EXEC_FAILURE
? 1 : 0;
905 cmd
.use_shell
= opt
& RUN_USING_SHELL
? 1 : 0;
906 cmd
.clean_on_exit
= opt
& RUN_CLEAN_ON_EXIT
? 1 : 0;
909 return run_command(&cmd
);
913 static pthread_t main_thread
;
914 static int main_thread_set
;
915 static pthread_key_t async_key
;
916 static pthread_key_t async_die_counter
;
918 static void *run_thread(void *data
)
920 struct async
*async
= data
;
923 if (async
->isolate_sigpipe
) {
926 sigaddset(&mask
, SIGPIPE
);
927 if (pthread_sigmask(SIG_BLOCK
, &mask
, NULL
) < 0) {
928 ret
= error("unable to block SIGPIPE in async thread");
933 pthread_setspecific(async_key
, async
);
934 ret
= async
->proc(async
->proc_in
, async
->proc_out
, async
->data
);
938 static NORETURN
void die_async(const char *err
, va_list params
)
940 vreportf("fatal: ", err
, params
);
943 struct async
*async
= pthread_getspecific(async_key
);
944 if (async
->proc_in
>= 0)
945 close(async
->proc_in
);
946 if (async
->proc_out
>= 0)
947 close(async
->proc_out
);
948 pthread_exit((void *)128);
954 static int async_die_is_recursing(void)
956 void *ret
= pthread_getspecific(async_die_counter
);
957 pthread_setspecific(async_die_counter
, (void *)1);
963 if (!main_thread_set
)
964 return 0; /* no asyncs started yet */
965 return !pthread_equal(main_thread
, pthread_self());
968 static void NORETURN
async_exit(int code
)
970 pthread_exit((void *)(intptr_t)code
);
976 void (**handlers
)(void);
981 static int git_atexit_installed
;
983 static void git_atexit_dispatch(void)
987 for (i
=git_atexit_hdlrs
.nr
; i
; i
--)
988 git_atexit_hdlrs
.handlers
[i
-1]();
991 static void git_atexit_clear(void)
993 free(git_atexit_hdlrs
.handlers
);
994 memset(&git_atexit_hdlrs
, 0, sizeof(git_atexit_hdlrs
));
995 git_atexit_installed
= 0;
999 int git_atexit(void (*handler
)(void))
1001 ALLOC_GROW(git_atexit_hdlrs
.handlers
, git_atexit_hdlrs
.nr
+ 1, git_atexit_hdlrs
.alloc
);
1002 git_atexit_hdlrs
.handlers
[git_atexit_hdlrs
.nr
++] = handler
;
1003 if (!git_atexit_installed
) {
1004 if (atexit(&git_atexit_dispatch
))
1006 git_atexit_installed
= 1;
1010 #define atexit git_atexit
1012 static int process_is_async
;
1015 return process_is_async
;
1018 static void NORETURN
async_exit(int code
)
1025 void check_pipe(int err
)
1031 signal(SIGPIPE
, SIG_DFL
);
1033 /* Should never happen, but just in case... */
1038 int start_async(struct async
*async
)
1040 int need_in
, need_out
;
1041 int fdin
[2], fdout
[2];
1042 int proc_in
, proc_out
;
1044 need_in
= async
->in
< 0;
1046 if (pipe(fdin
) < 0) {
1049 return error_errno("cannot create pipe");
1051 async
->in
= fdin
[1];
1054 need_out
= async
->out
< 0;
1056 if (pipe(fdout
) < 0) {
1061 return error_errno("cannot create pipe");
1063 async
->out
= fdout
[0];
1069 proc_in
= async
->in
;
1074 proc_out
= fdout
[1];
1075 else if (async
->out
)
1076 proc_out
= async
->out
;
1081 /* Flush stdio before fork() to avoid cloning buffers */
1084 async
->pid
= fork();
1085 if (async
->pid
< 0) {
1086 error_errno("fork (async) failed");
1095 process_is_async
= 1;
1096 exit(!!async
->proc(proc_in
, proc_out
, async
->data
));
1099 mark_child_for_cleanup(async
->pid
, NULL
);
1108 else if (async
->out
)
1111 if (!main_thread_set
) {
1113 * We assume that the first time that start_async is called
1114 * it is from the main thread.
1116 main_thread_set
= 1;
1117 main_thread
= pthread_self();
1118 pthread_key_create(&async_key
, NULL
);
1119 pthread_key_create(&async_die_counter
, NULL
);
1120 set_die_routine(die_async
);
1121 set_die_is_recursing_routine(async_die_is_recursing
);
1125 set_cloexec(proc_in
);
1127 set_cloexec(proc_out
);
1128 async
->proc_in
= proc_in
;
1129 async
->proc_out
= proc_out
;
1131 int err
= pthread_create(&async
->tid
, NULL
, run_thread
, async
);
1133 error_errno("cannot create thread");
1148 else if (async
->out
)
1153 int finish_async(struct async
*async
)
1156 return wait_or_whine(async
->pid
, "child process", 0);
1158 void *ret
= (void *)(intptr_t)(-1);
1160 if (pthread_join(async
->tid
, &ret
))
1161 error("pthread_join failed");
1162 return (int)(intptr_t)ret
;
1166 const char *find_hook(const char *name
)
1168 static struct strbuf path
= STRBUF_INIT
;
1170 strbuf_reset(&path
);
1171 strbuf_git_path(&path
, "hooks/%s", name
);
1172 if (access(path
.buf
, X_OK
) < 0) {
1175 #ifdef STRIP_EXTENSION
1176 strbuf_addstr(&path
, STRIP_EXTENSION
);
1177 if (access(path
.buf
, X_OK
) >= 0)
1179 if (errno
== EACCES
)
1183 if (err
== EACCES
&& advice_ignored_hook
) {
1184 static struct string_list advise_given
= STRING_LIST_INIT_DUP
;
1186 if (!string_list_lookup(&advise_given
, name
)) {
1187 string_list_insert(&advise_given
, name
);
1188 advise(_("The '%s' hook was ignored because "
1189 "it's not set as executable.\n"
1190 "You can disable this warning with "
1191 "`git config advice.ignoredHook false`."),
1200 int run_hook_ve(const char *const *env
, const char *name
, va_list args
)
1202 struct child_process hook
= CHILD_PROCESS_INIT
;
1205 p
= find_hook(name
);
1209 argv_array_push(&hook
.args
, p
);
1210 while ((p
= va_arg(args
, const char *)))
1211 argv_array_push(&hook
.args
, p
);
1214 hook
.stdout_to_stderr
= 1;
1216 return run_command(&hook
);
1219 int run_hook_le(const char *const *env
, const char *name
, ...)
1224 va_start(args
, name
);
1225 ret
= run_hook_ve(env
, name
, args
);
1232 /* initialized by caller */
1234 int type
; /* POLLOUT or POLLIN */
1246 /* returned by pump_io */
1247 int error
; /* 0 for success, otherwise errno */
1253 static int pump_io_round(struct io_pump
*slots
, int nr
, struct pollfd
*pfd
)
1258 for (i
= 0; i
< nr
; i
++) {
1259 struct io_pump
*io
= &slots
[i
];
1262 pfd
[pollsize
].fd
= io
->fd
;
1263 pfd
[pollsize
].events
= io
->type
;
1264 io
->pfd
= &pfd
[pollsize
++];
1270 if (poll(pfd
, pollsize
, -1) < 0) {
1273 die_errno("poll failed");
1276 for (i
= 0; i
< nr
; i
++) {
1277 struct io_pump
*io
= &slots
[i
];
1282 if (!(io
->pfd
->revents
& (POLLOUT
|POLLIN
|POLLHUP
|POLLERR
|POLLNVAL
)))
1285 if (io
->type
== POLLOUT
) {
1286 ssize_t len
= xwrite(io
->fd
,
1287 io
->u
.out
.buf
, io
->u
.out
.len
);
1293 io
->u
.out
.buf
+= len
;
1294 io
->u
.out
.len
-= len
;
1295 if (!io
->u
.out
.len
) {
1302 if (io
->type
== POLLIN
) {
1303 ssize_t len
= strbuf_read_once(io
->u
.in
.buf
,
1304 io
->fd
, io
->u
.in
.hint
);
1317 static int pump_io(struct io_pump
*slots
, int nr
)
1322 for (i
= 0; i
< nr
; i
++)
1325 ALLOC_ARRAY(pfd
, nr
);
1326 while (pump_io_round(slots
, nr
, pfd
))
1330 /* There may be multiple errno values, so just pick the first. */
1331 for (i
= 0; i
< nr
; i
++) {
1332 if (slots
[i
].error
) {
1333 errno
= slots
[i
].error
;
1341 int pipe_command(struct child_process
*cmd
,
1342 const char *in
, size_t in_len
,
1343 struct strbuf
*out
, size_t out_hint
,
1344 struct strbuf
*err
, size_t err_hint
)
1346 struct io_pump io
[3];
1356 if (start_command(cmd
) < 0)
1360 io
[nr
].fd
= cmd
->in
;
1361 io
[nr
].type
= POLLOUT
;
1362 io
[nr
].u
.out
.buf
= in
;
1363 io
[nr
].u
.out
.len
= in_len
;
1367 io
[nr
].fd
= cmd
->out
;
1368 io
[nr
].type
= POLLIN
;
1369 io
[nr
].u
.in
.buf
= out
;
1370 io
[nr
].u
.in
.hint
= out_hint
;
1374 io
[nr
].fd
= cmd
->err
;
1375 io
[nr
].type
= POLLIN
;
1376 io
[nr
].u
.in
.buf
= err
;
1377 io
[nr
].u
.in
.hint
= err_hint
;
1381 if (pump_io(io
, nr
) < 0) {
1382 finish_command(cmd
); /* throw away exit code */
1386 return finish_command(cmd
);
1392 GIT_CP_WAIT_CLEANUP
,
1395 struct parallel_processes
{
1401 get_next_task_fn get_next_task
;
1402 start_failure_fn start_failure
;
1403 task_finished_fn task_finished
;
1406 enum child_state state
;
1407 struct child_process process
;
1412 * The struct pollfd is logically part of *children,
1413 * but the system call expects it as its own array.
1417 unsigned shutdown
: 1;
1420 struct strbuf buffered_output
; /* of finished children */
1423 static int default_start_failure(struct strbuf
*out
,
1430 static int default_task_finished(int result
,
1438 static void kill_children(struct parallel_processes
*pp
, int signo
)
1440 int i
, n
= pp
->max_processes
;
1442 for (i
= 0; i
< n
; i
++)
1443 if (pp
->children
[i
].state
== GIT_CP_WORKING
)
1444 kill(pp
->children
[i
].process
.pid
, signo
);
1447 static struct parallel_processes
*pp_for_signal
;
1449 static void handle_children_on_signal(int signo
)
1451 kill_children(pp_for_signal
, signo
);
1452 sigchain_pop(signo
);
1456 static void pp_init(struct parallel_processes
*pp
,
1458 get_next_task_fn get_next_task
,
1459 start_failure_fn start_failure
,
1460 task_finished_fn task_finished
,
1468 pp
->max_processes
= n
;
1470 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n
);
1474 die("BUG: you need to specify a get_next_task function");
1475 pp
->get_next_task
= get_next_task
;
1477 pp
->start_failure
= start_failure
? start_failure
: default_start_failure
;
1478 pp
->task_finished
= task_finished
? task_finished
: default_task_finished
;
1480 pp
->nr_processes
= 0;
1481 pp
->output_owner
= 0;
1483 pp
->children
= xcalloc(n
, sizeof(*pp
->children
));
1484 pp
->pfd
= xcalloc(n
, sizeof(*pp
->pfd
));
1485 strbuf_init(&pp
->buffered_output
, 0);
1487 for (i
= 0; i
< n
; i
++) {
1488 strbuf_init(&pp
->children
[i
].err
, 0);
1489 child_process_init(&pp
->children
[i
].process
);
1490 pp
->pfd
[i
].events
= POLLIN
| POLLHUP
;
1495 sigchain_push_common(handle_children_on_signal
);
1498 static void pp_cleanup(struct parallel_processes
*pp
)
1502 trace_printf("run_processes_parallel: done");
1503 for (i
= 0; i
< pp
->max_processes
; i
++) {
1504 strbuf_release(&pp
->children
[i
].err
);
1505 child_process_clear(&pp
->children
[i
].process
);
1512 * When get_next_task added messages to the buffer in its last
1513 * iteration, the buffered output is non empty.
1515 strbuf_write(&pp
->buffered_output
, stderr
);
1516 strbuf_release(&pp
->buffered_output
);
1518 sigchain_pop_common();
1522 * 0 if a new task was started.
1523 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1524 * problem with starting a new command)
1525 * <0 no new job was started, user wishes to shutdown early. Use negative code
1526 * to signal the children.
1528 static int pp_start_one(struct parallel_processes
*pp
)
1532 for (i
= 0; i
< pp
->max_processes
; i
++)
1533 if (pp
->children
[i
].state
== GIT_CP_FREE
)
1535 if (i
== pp
->max_processes
)
1536 die("BUG: bookkeeping is hard");
1538 code
= pp
->get_next_task(&pp
->children
[i
].process
,
1539 &pp
->children
[i
].err
,
1541 &pp
->children
[i
].data
);
1543 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1544 strbuf_reset(&pp
->children
[i
].err
);
1547 pp
->children
[i
].process
.err
= -1;
1548 pp
->children
[i
].process
.stdout_to_stderr
= 1;
1549 pp
->children
[i
].process
.no_stdin
= 1;
1551 if (start_command(&pp
->children
[i
].process
)) {
1552 code
= pp
->start_failure(&pp
->children
[i
].err
,
1554 pp
->children
[i
].data
);
1555 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1556 strbuf_reset(&pp
->children
[i
].err
);
1563 pp
->children
[i
].state
= GIT_CP_WORKING
;
1564 pp
->pfd
[i
].fd
= pp
->children
[i
].process
.err
;
1568 static void pp_buffer_stderr(struct parallel_processes
*pp
, int output_timeout
)
1572 while ((i
= poll(pp
->pfd
, pp
->max_processes
, output_timeout
)) < 0) {
1579 /* Buffer output from all pipes. */
1580 for (i
= 0; i
< pp
->max_processes
; i
++) {
1581 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1582 pp
->pfd
[i
].revents
& (POLLIN
| POLLHUP
)) {
1583 int n
= strbuf_read_once(&pp
->children
[i
].err
,
1584 pp
->children
[i
].process
.err
, 0);
1586 close(pp
->children
[i
].process
.err
);
1587 pp
->children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1589 if (errno
!= EAGAIN
)
1595 static void pp_output(struct parallel_processes
*pp
)
1597 int i
= pp
->output_owner
;
1598 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1599 pp
->children
[i
].err
.len
) {
1600 strbuf_write(&pp
->children
[i
].err
, stderr
);
1601 strbuf_reset(&pp
->children
[i
].err
);
1605 static int pp_collect_finished(struct parallel_processes
*pp
)
1608 int n
= pp
->max_processes
;
1611 while (pp
->nr_processes
> 0) {
1612 for (i
= 0; i
< pp
->max_processes
; i
++)
1613 if (pp
->children
[i
].state
== GIT_CP_WAIT_CLEANUP
)
1615 if (i
== pp
->max_processes
)
1618 code
= finish_command(&pp
->children
[i
].process
);
1620 code
= pp
->task_finished(code
,
1621 &pp
->children
[i
].err
, pp
->data
,
1622 pp
->children
[i
].data
);
1630 pp
->children
[i
].state
= GIT_CP_FREE
;
1632 child_process_init(&pp
->children
[i
].process
);
1634 if (i
!= pp
->output_owner
) {
1635 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1636 strbuf_reset(&pp
->children
[i
].err
);
1638 strbuf_write(&pp
->children
[i
].err
, stderr
);
1639 strbuf_reset(&pp
->children
[i
].err
);
1641 /* Output all other finished child processes */
1642 strbuf_write(&pp
->buffered_output
, stderr
);
1643 strbuf_reset(&pp
->buffered_output
);
1646 * Pick next process to output live.
1648 * For now we pick it randomly by doing a round
1649 * robin. Later we may want to pick the one with
1650 * the most output or the longest or shortest
1651 * running process time.
1653 for (i
= 0; i
< n
; i
++)
1654 if (pp
->children
[(pp
->output_owner
+ i
) % n
].state
== GIT_CP_WORKING
)
1656 pp
->output_owner
= (pp
->output_owner
+ i
) % n
;
1662 int run_processes_parallel(int n
,
1663 get_next_task_fn get_next_task
,
1664 start_failure_fn start_failure
,
1665 task_finished_fn task_finished
,
1669 int output_timeout
= 100;
1671 struct parallel_processes pp
;
1673 pp_init(&pp
, n
, get_next_task
, start_failure
, task_finished
, pp_cb
);
1676 i
< spawn_cap
&& !pp
.shutdown
&&
1677 pp
.nr_processes
< pp
.max_processes
;
1679 code
= pp_start_one(&pp
);
1684 kill_children(&pp
, -code
);
1688 if (!pp
.nr_processes
)
1690 pp_buffer_stderr(&pp
, output_timeout
);
1692 code
= pp_collect_finished(&pp
);
1696 kill_children(&pp
, -code
);