2 #include "run-command.h"
3 #include "environment.h"
8 #include "thread-utils.h"
10 #include "string-list.h"
17 #include "compat/nonblock.h"
19 void child_process_init(struct child_process
*child
)
21 struct child_process blank
= CHILD_PROCESS_INIT
;
22 memcpy(child
, &blank
, sizeof(*child
));
25 void child_process_clear(struct child_process
*child
)
27 strvec_clear(&child
->args
);
28 strvec_clear(&child
->env
);
31 struct child_to_clean
{
33 struct child_process
*process
;
34 struct child_to_clean
*next
;
36 static struct child_to_clean
*children_to_clean
;
37 static int installed_child_cleanup_handler
;
39 static void cleanup_children(int sig
, int in_signal
)
41 struct child_to_clean
*children_to_wait_for
= NULL
;
43 while (children_to_clean
) {
44 struct child_to_clean
*p
= children_to_clean
;
45 children_to_clean
= p
->next
;
47 if (p
->process
&& !in_signal
) {
48 struct child_process
*process
= p
->process
;
49 if (process
->clean_on_exit_handler
) {
51 "trace: run_command: running exit handler for pid %"
52 PRIuMAX
, (uintmax_t)p
->pid
54 process
->clean_on_exit_handler(process
);
60 if (p
->process
&& p
->process
->wait_after_clean
) {
61 p
->next
= children_to_wait_for
;
62 children_to_wait_for
= p
;
69 while (children_to_wait_for
) {
70 struct child_to_clean
*p
= children_to_wait_for
;
71 children_to_wait_for
= p
->next
;
73 while (waitpid(p
->pid
, NULL
, 0) < 0 && errno
== EINTR
)
74 ; /* spin waiting for process exit or error */
81 static void cleanup_children_on_signal(int sig
)
83 cleanup_children(sig
, 1);
88 static void cleanup_children_on_exit(void)
90 cleanup_children(SIGTERM
, 0);
93 static void mark_child_for_cleanup(pid_t pid
, struct child_process
*process
)
95 struct child_to_clean
*p
= xmalloc(sizeof(*p
));
98 p
->next
= children_to_clean
;
99 children_to_clean
= p
;
101 if (!installed_child_cleanup_handler
) {
102 atexit(cleanup_children_on_exit
);
103 sigchain_push_common(cleanup_children_on_signal
);
104 installed_child_cleanup_handler
= 1;
108 static void clear_child_for_cleanup(pid_t pid
)
110 struct child_to_clean
**pp
;
112 for (pp
= &children_to_clean
; *pp
; pp
= &(*pp
)->next
) {
113 struct child_to_clean
*clean_me
= *pp
;
115 if (clean_me
->pid
== pid
) {
116 *pp
= clean_me
->next
;
123 static inline void close_pair(int fd
[2])
129 int is_executable(const char *name
)
133 if (stat(name
, &st
) || /* stat, not lstat */
134 !S_ISREG(st
.st_mode
))
137 #if defined(GIT_WINDOWS_NATIVE)
139 * On Windows there is no executable bit. The file extension
140 * indicates whether it can be run as an executable, and Git
141 * has special-handling to detect scripts and launch them
142 * through the indicated script interpreter. We test for the
143 * file extension first because virus scanners may make
144 * it quite expensive to open many files.
146 if (ends_with(name
, ".exe"))
151 * Now that we know it does not have an executable extension,
152 * peek into the file instead.
156 int fd
= open(name
, O_RDONLY
);
157 st
.st_mode
&= ~S_IXUSR
;
159 n
= read(fd
, buf
, 2);
161 /* look for a she-bang */
162 if (!strcmp(buf
, "#!"))
163 st
.st_mode
|= S_IXUSR
;
168 return st
.st_mode
& S_IXUSR
;
172 * Search $PATH for a command. This emulates the path search that
173 * execvp would perform, without actually executing the command so it
174 * can be used before fork() to prepare to run a command using
175 * execve() or after execvp() to diagnose why it failed.
177 * The caller should ensure that file contains no directory
180 * Returns the path to the command, as found in $PATH or NULL if the
181 * command could not be found. The caller inherits ownership of the memory
182 * used to store the resultant path.
184 * This should not be used on Windows, where the $PATH search rules
185 * are more complicated (e.g., a search for "foo" should find
188 static char *locate_in_PATH(const char *file
)
190 const char *p
= getenv("PATH");
191 struct strbuf buf
= STRBUF_INIT
;
197 const char *end
= strchrnul(p
, ':');
201 /* POSIX specifies an empty entry as the current directory. */
203 strbuf_add(&buf
, p
, end
- p
);
204 strbuf_addch(&buf
, '/');
206 strbuf_addstr(&buf
, file
);
208 if (is_executable(buf
.buf
))
209 return strbuf_detach(&buf
, NULL
);
216 strbuf_release(&buf
);
220 int exists_in_PATH(const char *command
)
222 char *r
= locate_in_PATH(command
);
223 int found
= r
!= NULL
;
228 int sane_execvp(const char *file
, char * const argv
[])
230 #ifndef GIT_WINDOWS_NATIVE
232 * execvp() doesn't return, so we all we can do is tell trace2
233 * what we are about to do and let it leave a hint in the log
234 * (unless of course the execvp() fails).
236 * we skip this for Windows because the compat layer already
237 * has to emulate the execvp() call anyway.
239 int exec_id
= trace2_exec(file
, (const char **)argv
);
242 if (!execvp(file
, argv
))
243 return 0; /* cannot happen ;-) */
245 #ifndef GIT_WINDOWS_NATIVE
248 trace2_exec_result(exec_id
, ec
);
254 * When a command can't be found because one of the directories
255 * listed in $PATH is unsearchable, execvp reports EACCES, but
256 * careful usability testing (read: analysis of occasional bug
257 * reports) reveals that "No such file or directory" is more
260 * We avoid commands with "/", because execvp will not do $PATH
261 * lookups in that case.
263 * The reassignment of EACCES to errno looks like a no-op below,
264 * but we need to protect against exists_in_PATH overwriting errno.
266 if (errno
== EACCES
&& !strchr(file
, '/'))
267 errno
= exists_in_PATH(file
) ? EACCES
: ENOENT
;
268 else if (errno
== ENOTDIR
&& !strchr(file
, '/'))
273 static const char **prepare_shell_cmd(struct strvec
*out
, const char **argv
)
276 BUG("shell command is empty");
278 if (strcspn(argv
[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv
[0])) {
279 #ifndef GIT_WINDOWS_NATIVE
280 strvec_push(out
, SHELL_PATH
);
282 strvec_push(out
, "sh");
284 strvec_push(out
, "-c");
287 * If we have no extra arguments, we do not even need to
288 * bother with the "$@" magic.
291 strvec_push(out
, argv
[0]);
293 strvec_pushf(out
, "%s \"$@\"", argv
[0]);
296 strvec_pushv(out
, argv
);
300 #ifndef GIT_WINDOWS_NATIVE
301 static int child_notifier
= -1;
307 CHILD_ERR_SIGPROCMASK
,
314 enum child_errcode err
;
315 int syserr
; /* errno */
318 static void child_die(enum child_errcode err
)
320 struct child_err buf
;
325 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
326 xwrite(child_notifier
, &buf
, sizeof(buf
));
330 static void child_dup2(int fd
, int to
)
332 if (dup2(fd
, to
) < 0)
333 child_die(CHILD_ERR_DUP2
);
336 static void child_close(int fd
)
339 child_die(CHILD_ERR_CLOSE
);
342 static void child_close_pair(int fd
[2])
348 static void child_error_fn(const char *err UNUSED
, va_list params UNUSED
)
350 const char msg
[] = "error() should not be called in child\n";
351 xwrite(2, msg
, sizeof(msg
) - 1);
354 static void child_warn_fn(const char *err UNUSED
, va_list params UNUSED
)
356 const char msg
[] = "warn() should not be called in child\n";
357 xwrite(2, msg
, sizeof(msg
) - 1);
360 static void NORETURN
child_die_fn(const char *err UNUSED
, va_list params UNUSED
)
362 const char msg
[] = "die() should not be called in child\n";
363 xwrite(2, msg
, sizeof(msg
) - 1);
367 /* this runs in the parent process */
368 static void child_err_spew(struct child_process
*cmd
, struct child_err
*cerr
)
370 static void (*old_errfn
)(const char *err
, va_list params
);
371 report_fn die_message_routine
= get_die_message_routine();
373 old_errfn
= get_error_routine();
374 set_error_routine(die_message_routine
);
375 errno
= cerr
->syserr
;
378 case CHILD_ERR_CHDIR
:
379 error_errno("exec '%s': cd to '%s' failed",
380 cmd
->args
.v
[0], cmd
->dir
);
383 error_errno("dup2() in child failed");
385 case CHILD_ERR_CLOSE
:
386 error_errno("close() in child failed");
388 case CHILD_ERR_SIGPROCMASK
:
389 error_errno("sigprocmask failed restoring signals");
391 case CHILD_ERR_ENOENT
:
392 error_errno("cannot run %s", cmd
->args
.v
[0]);
394 case CHILD_ERR_SILENT
:
396 case CHILD_ERR_ERRNO
:
397 error_errno("cannot exec '%s'", cmd
->args
.v
[0]);
400 set_error_routine(old_errfn
);
403 static int prepare_cmd(struct strvec
*out
, const struct child_process
*cmd
)
406 BUG("command is empty");
409 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
410 * attempt to interpret the command with 'sh'.
412 strvec_push(out
, SHELL_PATH
);
415 prepare_git_cmd(out
, cmd
->args
.v
);
416 } else if (cmd
->use_shell
) {
417 prepare_shell_cmd(out
, cmd
->args
.v
);
419 strvec_pushv(out
, cmd
->args
.v
);
423 * If there are no dir separator characters in the command then perform
424 * a path lookup and use the resolved path as the command to exec. If
425 * there are dir separator characters, we have exec attempt to invoke
426 * the command directly.
428 if (!has_dir_sep(out
->v
[1])) {
429 char *program
= locate_in_PATH(out
->v
[1]);
431 free((char *)out
->v
[1]);
443 static char **prep_childenv(const char *const *deltaenv
)
445 extern char **environ
;
447 struct string_list env
= STRING_LIST_INIT_DUP
;
448 struct strbuf key
= STRBUF_INIT
;
449 const char *const *p
;
452 /* Construct a sorted string list consisting of the current environ */
453 for (p
= (const char *const *) environ
; p
&& *p
; p
++) {
454 const char *equals
= strchr(*p
, '=');
458 strbuf_add(&key
, *p
, equals
- *p
);
459 string_list_append(&env
, key
.buf
)->util
= (void *) *p
;
461 string_list_append(&env
, *p
)->util
= (void *) *p
;
464 string_list_sort(&env
);
466 /* Merge in 'deltaenv' with the current environ */
467 for (p
= deltaenv
; p
&& *p
; p
++) {
468 const char *equals
= strchr(*p
, '=');
471 /* ('key=value'), insert or replace entry */
473 strbuf_add(&key
, *p
, equals
- *p
);
474 string_list_insert(&env
, key
.buf
)->util
= (void *) *p
;
476 /* otherwise ('key') remove existing entry */
477 string_list_remove(&env
, *p
, 0);
481 /* Create an array of 'char *' to be used as the childenv */
482 ALLOC_ARRAY(childenv
, env
.nr
+ 1);
483 for (i
= 0; i
< env
.nr
; i
++)
484 childenv
[i
] = env
.items
[i
].util
;
485 childenv
[env
.nr
] = NULL
;
487 string_list_clear(&env
, 0);
488 strbuf_release(&key
);
492 struct atfork_state
{
499 #define CHECK_BUG(err, msg) \
503 BUG("%s: %s", msg, strerror(e)); \
506 static void atfork_prepare(struct atfork_state
*as
)
510 if (sigfillset(&all
))
511 die_errno("sigfillset");
513 if (sigprocmask(SIG_SETMASK
, &all
, &as
->old
))
514 die_errno("sigprocmask");
516 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &all
, &as
->old
),
517 "blocking all signals");
518 CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &as
->cs
),
519 "disabling cancellation");
523 static void atfork_parent(struct atfork_state
*as
)
526 if (sigprocmask(SIG_SETMASK
, &as
->old
, NULL
))
527 die_errno("sigprocmask");
529 CHECK_BUG(pthread_setcancelstate(as
->cs
, NULL
),
530 "re-enabling cancellation");
531 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &as
->old
, NULL
),
532 "restoring signal mask");
535 #endif /* GIT_WINDOWS_NATIVE */
537 static inline void set_cloexec(int fd
)
539 int flags
= fcntl(fd
, F_GETFD
);
541 fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
544 static int wait_or_whine(pid_t pid
, const char *argv0
, int in_signal
)
546 int status
, code
= -1;
548 int failed_errno
= 0;
550 while ((waiting
= waitpid(pid
, &status
, 0)) < 0 && errno
== EINTR
)
554 failed_errno
= errno
;
556 error_errno("waitpid for %s failed", argv0
);
557 } else if (waiting
!= pid
) {
559 error("waitpid is confused (%s)", argv0
);
560 } else if (WIFSIGNALED(status
)) {
561 code
= WTERMSIG(status
);
562 if (!in_signal
&& code
!= SIGINT
&& code
!= SIGQUIT
&& code
!= SIGPIPE
)
563 error("%s died of signal %d", argv0
, code
);
565 * This return value is chosen so that code & 0xff
566 * mimics the exit code that a POSIX shell would report for
567 * a program that died from this signal.
570 } else if (WIFEXITED(status
)) {
571 code
= WEXITSTATUS(status
);
574 error("waitpid is confused (%s)", argv0
);
578 clear_child_for_cleanup(pid
);
580 errno
= failed_errno
;
584 static void trace_add_env(struct strbuf
*dst
, const char *const *deltaenv
)
586 struct string_list envs
= STRING_LIST_INIT_DUP
;
587 const char *const *e
;
589 int printed_unset
= 0;
591 /* Last one wins, see run-command.c:prep_childenv() for context */
592 for (e
= deltaenv
; e
&& *e
; e
++) {
593 struct strbuf key
= STRBUF_INIT
;
594 char *equals
= strchr(*e
, '=');
597 strbuf_add(&key
, *e
, equals
- *e
);
598 string_list_insert(&envs
, key
.buf
)->util
= equals
+ 1;
600 string_list_insert(&envs
, *e
)->util
= NULL
;
602 strbuf_release(&key
);
605 /* "unset X Y...;" */
606 for (i
= 0; i
< envs
.nr
; i
++) {
607 const char *var
= envs
.items
[i
].string
;
608 const char *val
= envs
.items
[i
].util
;
610 if (val
|| !getenv(var
))
613 if (!printed_unset
) {
614 strbuf_addstr(dst
, " unset");
617 strbuf_addf(dst
, " %s", var
);
620 strbuf_addch(dst
, ';');
622 /* ... followed by "A=B C=D ..." */
623 for (i
= 0; i
< envs
.nr
; i
++) {
624 const char *var
= envs
.items
[i
].string
;
625 const char *val
= envs
.items
[i
].util
;
631 oldval
= getenv(var
);
632 if (oldval
&& !strcmp(val
, oldval
))
635 strbuf_addf(dst
, " %s=", var
);
636 sq_quote_buf_pretty(dst
, val
);
638 string_list_clear(&envs
, 0);
641 static void trace_run_command(const struct child_process
*cp
)
643 struct strbuf buf
= STRBUF_INIT
;
645 if (!trace_want(&trace_default_key
))
648 strbuf_addstr(&buf
, "trace: run_command:");
650 strbuf_addstr(&buf
, " cd ");
651 sq_quote_buf_pretty(&buf
, cp
->dir
);
652 strbuf_addch(&buf
, ';');
654 trace_add_env(&buf
, cp
->env
.v
);
656 strbuf_addstr(&buf
, " git");
657 sq_quote_argv_pretty(&buf
, cp
->args
.v
);
659 trace_printf("%s", buf
.buf
);
660 strbuf_release(&buf
);
663 int start_command(struct child_process
*cmd
)
665 int need_in
, need_out
, need_err
;
666 int fdin
[2], fdout
[2], fderr
[2];
671 * In case of errors we must keep the promise to close FDs
672 * that have been passed in via ->in and ->out.
675 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
677 if (pipe(fdin
) < 0) {
678 failed_errno
= errno
;
681 str
= "standard input";
687 need_out
= !cmd
->no_stdout
688 && !cmd
->stdout_to_stderr
691 if (pipe(fdout
) < 0) {
692 failed_errno
= errno
;
697 str
= "standard output";
703 need_err
= !cmd
->no_stderr
&& cmd
->err
< 0;
705 if (pipe(fderr
) < 0) {
706 failed_errno
= errno
;
715 str
= "standard error";
717 error("cannot create %s pipe for %s: %s",
718 str
, cmd
->args
.v
[0], strerror(failed_errno
));
719 child_process_clear(cmd
);
720 errno
= failed_errno
;
726 trace2_child_start(cmd
);
727 trace_run_command(cmd
);
731 if (cmd
->close_object_store
)
732 close_object_store(the_repository
->objects
);
734 #ifndef GIT_WINDOWS_NATIVE
739 struct strvec argv
= STRVEC_INIT
;
740 struct child_err cerr
;
741 struct atfork_state as
;
743 if (prepare_cmd(&argv
, cmd
) < 0) {
744 failed_errno
= errno
;
746 if (!cmd
->silent_exec_failure
)
747 error_errno("cannot run %s", cmd
->args
.v
[0]);
751 if (pipe(notify_pipe
))
752 notify_pipe
[0] = notify_pipe
[1] = -1;
754 if (cmd
->no_stdin
|| cmd
->no_stdout
|| cmd
->no_stderr
) {
755 null_fd
= xopen("/dev/null", O_RDWR
| O_CLOEXEC
);
756 set_cloexec(null_fd
);
759 childenv
= prep_childenv(cmd
->env
.v
);
763 * NOTE: In order to prevent deadlocking when using threads special
764 * care should be taken with the function calls made in between the
765 * fork() and exec() calls. No calls should be made to functions which
766 * require acquiring a lock (e.g. malloc) as the lock could have been
767 * held by another thread at the time of forking, causing the lock to
768 * never be released in the child process. This means only
769 * Async-Signal-Safe functions are permitted in the child.
772 failed_errno
= errno
;
776 * Ensure the default die/error/warn routines do not get
777 * called, they can take stdio locks and malloc.
779 set_die_routine(child_die_fn
);
780 set_error_routine(child_error_fn
);
781 set_warn_routine(child_warn_fn
);
783 close(notify_pipe
[0]);
784 set_cloexec(notify_pipe
[1]);
785 child_notifier
= notify_pipe
[1];
788 child_dup2(null_fd
, 0);
790 child_dup2(fdin
[0], 0);
791 child_close_pair(fdin
);
792 } else if (cmd
->in
) {
793 child_dup2(cmd
->in
, 0);
794 child_close(cmd
->in
);
798 child_dup2(null_fd
, 2);
800 child_dup2(fderr
[1], 2);
801 child_close_pair(fderr
);
802 } else if (cmd
->err
> 1) {
803 child_dup2(cmd
->err
, 2);
804 child_close(cmd
->err
);
808 child_dup2(null_fd
, 1);
809 else if (cmd
->stdout_to_stderr
)
812 child_dup2(fdout
[1], 1);
813 child_close_pair(fdout
);
814 } else if (cmd
->out
> 1) {
815 child_dup2(cmd
->out
, 1);
816 child_close(cmd
->out
);
819 if (cmd
->dir
&& chdir(cmd
->dir
))
820 child_die(CHILD_ERR_CHDIR
);
823 * restore default signal handlers here, in case
824 * we catch a signal right before execve below
826 for (sig
= 1; sig
< NSIG
; sig
++) {
827 /* ignored signals get reset to SIG_DFL on execve */
828 if (signal(sig
, SIG_DFL
) == SIG_IGN
)
829 signal(sig
, SIG_IGN
);
832 if (sigprocmask(SIG_SETMASK
, &as
.old
, NULL
) != 0)
833 child_die(CHILD_ERR_SIGPROCMASK
);
836 * Attempt to exec using the command and arguments starting at
837 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
838 * be used in the event exec failed with ENOEXEC at which point
839 * we will try to interpret the command using 'sh'.
841 execve(argv
.v
[1], (char *const *) argv
.v
+ 1,
842 (char *const *) childenv
);
843 if (errno
== ENOEXEC
)
844 execve(argv
.v
[0], (char *const *) argv
.v
,
845 (char *const *) childenv
);
847 if (errno
== ENOENT
) {
848 if (cmd
->silent_exec_failure
)
849 child_die(CHILD_ERR_SILENT
);
850 child_die(CHILD_ERR_ENOENT
);
852 child_die(CHILD_ERR_ERRNO
);
857 error_errno("cannot fork() for %s", cmd
->args
.v
[0]);
858 else if (cmd
->clean_on_exit
)
859 mark_child_for_cleanup(cmd
->pid
, cmd
);
862 * Wait for child's exec. If the exec succeeds (or if fork()
863 * failed), EOF is seen immediately by the parent. Otherwise, the
864 * child process sends a child_err struct.
865 * Note that use of this infrastructure is completely advisory,
866 * therefore, we keep error checks minimal.
868 close(notify_pipe
[1]);
869 if (xread(notify_pipe
[0], &cerr
, sizeof(cerr
)) == sizeof(cerr
)) {
871 * At this point we know that fork() succeeded, but exec()
872 * failed. Errors have been reported to our stderr.
874 wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
875 child_err_spew(cmd
, &cerr
);
876 failed_errno
= errno
;
879 close(notify_pipe
[0]);
890 int fhin
= 0, fhout
= 1, fherr
= 2;
891 const char **sargv
= cmd
->args
.v
;
892 struct strvec nargv
= STRVEC_INIT
;
895 fhin
= open("/dev/null", O_RDWR
);
902 fherr
= open("/dev/null", O_RDWR
);
904 fherr
= dup(fderr
[1]);
905 else if (cmd
->err
> 2)
906 fherr
= dup(cmd
->err
);
909 fhout
= open("/dev/null", O_RDWR
);
910 else if (cmd
->stdout_to_stderr
)
913 fhout
= dup(fdout
[1]);
914 else if (cmd
->out
> 1)
915 fhout
= dup(cmd
->out
);
918 cmd
->args
.v
= prepare_git_cmd(&nargv
, sargv
);
919 else if (cmd
->use_shell
)
920 cmd
->args
.v
= prepare_shell_cmd(&nargv
, sargv
);
922 cmd
->pid
= mingw_spawnvpe(cmd
->args
.v
[0], cmd
->args
.v
,
924 cmd
->dir
, fhin
, fhout
, fherr
);
925 failed_errno
= errno
;
926 if (cmd
->pid
< 0 && (!cmd
->silent_exec_failure
|| errno
!= ENOENT
))
927 error_errno("cannot spawn %s", cmd
->args
.v
[0]);
928 if (cmd
->clean_on_exit
&& cmd
->pid
>= 0)
929 mark_child_for_cleanup(cmd
->pid
, cmd
);
931 strvec_clear(&nargv
);
943 trace2_child_exit(cmd
, -1);
957 child_process_clear(cmd
);
958 errno
= failed_errno
;
980 int finish_command(struct child_process
*cmd
)
982 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
983 trace2_child_exit(cmd
, ret
);
984 child_process_clear(cmd
);
985 invalidate_lstat_cache();
989 int finish_command_in_signal(struct child_process
*cmd
)
991 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 1);
993 trace2_child_exit(cmd
, ret
);
998 int run_command(struct child_process
*cmd
)
1002 if (cmd
->out
< 0 || cmd
->err
< 0)
1003 BUG("run_command with a pipe can cause deadlock");
1005 code
= start_command(cmd
);
1008 return finish_command(cmd
);
1012 static pthread_t main_thread
;
1013 static int main_thread_set
;
1014 static pthread_key_t async_key
;
1015 static pthread_key_t async_die_counter
;
1017 static void *run_thread(void *data
)
1019 struct async
*async
= data
;
1022 if (async
->isolate_sigpipe
) {
1025 sigaddset(&mask
, SIGPIPE
);
1026 if (pthread_sigmask(SIG_BLOCK
, &mask
, NULL
)) {
1027 ret
= error("unable to block SIGPIPE in async thread");
1032 pthread_setspecific(async_key
, async
);
1033 ret
= async
->proc(async
->proc_in
, async
->proc_out
, async
->data
);
1037 static NORETURN
void die_async(const char *err
, va_list params
)
1039 report_fn die_message_fn
= get_die_message_routine();
1041 die_message_fn(err
, params
);
1044 struct async
*async
= pthread_getspecific(async_key
);
1045 if (async
->proc_in
>= 0)
1046 close(async
->proc_in
);
1047 if (async
->proc_out
>= 0)
1048 close(async
->proc_out
);
1049 pthread_exit((void *)128);
1055 static int async_die_is_recursing(void)
1057 void *ret
= pthread_getspecific(async_die_counter
);
1058 pthread_setspecific(async_die_counter
, &async_die_counter
); /* set to any non-NULL valid pointer */
1064 if (!main_thread_set
)
1065 return 0; /* no asyncs started yet */
1066 return !pthread_equal(main_thread
, pthread_self());
1069 static void NORETURN
async_exit(int code
)
1071 pthread_exit((void *)(intptr_t)code
);
1077 void (**handlers
)(void);
1082 static int git_atexit_installed
;
1084 static void git_atexit_dispatch(void)
1088 for (i
=git_atexit_hdlrs
.nr
; i
; i
--)
1089 git_atexit_hdlrs
.handlers
[i
-1]();
1092 static void git_atexit_clear(void)
1094 free(git_atexit_hdlrs
.handlers
);
1095 memset(&git_atexit_hdlrs
, 0, sizeof(git_atexit_hdlrs
));
1096 git_atexit_installed
= 0;
1100 int git_atexit(void (*handler
)(void))
1102 ALLOC_GROW(git_atexit_hdlrs
.handlers
, git_atexit_hdlrs
.nr
+ 1, git_atexit_hdlrs
.alloc
);
1103 git_atexit_hdlrs
.handlers
[git_atexit_hdlrs
.nr
++] = handler
;
1104 if (!git_atexit_installed
) {
1105 if (atexit(&git_atexit_dispatch
))
1107 git_atexit_installed
= 1;
1111 #define atexit git_atexit
1113 static int process_is_async
;
1116 return process_is_async
;
1119 static void NORETURN
async_exit(int code
)
1126 void check_pipe(int err
)
1132 signal(SIGPIPE
, SIG_DFL
);
1134 /* Should never happen, but just in case... */
1139 int start_async(struct async
*async
)
1141 int need_in
, need_out
;
1142 int fdin
[2], fdout
[2];
1143 int proc_in
, proc_out
;
1145 need_in
= async
->in
< 0;
1147 if (pipe(fdin
) < 0) {
1150 return error_errno("cannot create pipe");
1152 async
->in
= fdin
[1];
1155 need_out
= async
->out
< 0;
1157 if (pipe(fdout
) < 0) {
1162 return error_errno("cannot create pipe");
1164 async
->out
= fdout
[0];
1170 proc_in
= async
->in
;
1175 proc_out
= fdout
[1];
1176 else if (async
->out
)
1177 proc_out
= async
->out
;
1182 /* Flush stdio before fork() to avoid cloning buffers */
1185 async
->pid
= fork();
1186 if (async
->pid
< 0) {
1187 error_errno("fork (async) failed");
1196 process_is_async
= 1;
1197 exit(!!async
->proc(proc_in
, proc_out
, async
->data
));
1200 mark_child_for_cleanup(async
->pid
, NULL
);
1209 else if (async
->out
)
1212 if (!main_thread_set
) {
1214 * We assume that the first time that start_async is called
1215 * it is from the main thread.
1217 main_thread_set
= 1;
1218 main_thread
= pthread_self();
1219 pthread_key_create(&async_key
, NULL
);
1220 pthread_key_create(&async_die_counter
, NULL
);
1221 set_die_routine(die_async
);
1222 set_die_is_recursing_routine(async_die_is_recursing
);
1226 set_cloexec(proc_in
);
1228 set_cloexec(proc_out
);
1229 async
->proc_in
= proc_in
;
1230 async
->proc_out
= proc_out
;
1232 int err
= pthread_create(&async
->tid
, NULL
, run_thread
, async
);
1234 error(_("cannot create async thread: %s"), strerror(err
));
1249 else if (async
->out
)
1254 int finish_async(struct async
*async
)
1257 int ret
= wait_or_whine(async
->pid
, "child process", 0);
1259 invalidate_lstat_cache();
1263 void *ret
= (void *)(intptr_t)(-1);
1265 if (pthread_join(async
->tid
, &ret
))
1266 error("pthread_join failed");
1267 invalidate_lstat_cache();
1268 return (int)(intptr_t)ret
;
1273 int async_with_fork(void)
1283 /* initialized by caller */
1285 int type
; /* POLLOUT or POLLIN */
1297 /* returned by pump_io */
1298 int error
; /* 0 for success, otherwise errno */
1304 static int pump_io_round(struct io_pump
*slots
, int nr
, struct pollfd
*pfd
)
1309 for (i
= 0; i
< nr
; i
++) {
1310 struct io_pump
*io
= &slots
[i
];
1313 pfd
[pollsize
].fd
= io
->fd
;
1314 pfd
[pollsize
].events
= io
->type
;
1315 io
->pfd
= &pfd
[pollsize
++];
1321 if (poll(pfd
, pollsize
, -1) < 0) {
1324 die_errno("poll failed");
1327 for (i
= 0; i
< nr
; i
++) {
1328 struct io_pump
*io
= &slots
[i
];
1333 if (!(io
->pfd
->revents
& (POLLOUT
|POLLIN
|POLLHUP
|POLLERR
|POLLNVAL
)))
1336 if (io
->type
== POLLOUT
) {
1340 * Don't use xwrite() here. It loops forever on EAGAIN,
1341 * and we're in our own poll() loop here.
1343 * Note that we lose xwrite()'s handling of MAX_IO_SIZE
1344 * and EINTR, so we have to implement those ourselves.
1346 len
= write(io
->fd
, io
->u
.out
.buf
,
1347 io
->u
.out
.len
<= MAX_IO_SIZE
?
1348 io
->u
.out
.len
: MAX_IO_SIZE
);
1350 if (errno
!= EINTR
&& errno
!= EAGAIN
&&
1357 io
->u
.out
.buf
+= len
;
1358 io
->u
.out
.len
-= len
;
1359 if (!io
->u
.out
.len
) {
1366 if (io
->type
== POLLIN
) {
1367 ssize_t len
= strbuf_read_once(io
->u
.in
.buf
,
1368 io
->fd
, io
->u
.in
.hint
);
1381 static int pump_io(struct io_pump
*slots
, int nr
)
1386 for (i
= 0; i
< nr
; i
++)
1389 ALLOC_ARRAY(pfd
, nr
);
1390 while (pump_io_round(slots
, nr
, pfd
))
1394 /* There may be multiple errno values, so just pick the first. */
1395 for (i
= 0; i
< nr
; i
++) {
1396 if (slots
[i
].error
) {
1397 errno
= slots
[i
].error
;
1405 int pipe_command(struct child_process
*cmd
,
1406 const char *in
, size_t in_len
,
1407 struct strbuf
*out
, size_t out_hint
,
1408 struct strbuf
*err
, size_t err_hint
)
1410 struct io_pump io
[3];
1420 if (start_command(cmd
) < 0)
1424 if (enable_pipe_nonblock(cmd
->in
) < 0) {
1425 error_errno("unable to make pipe non-blocking");
1433 io
[nr
].fd
= cmd
->in
;
1434 io
[nr
].type
= POLLOUT
;
1435 io
[nr
].u
.out
.buf
= in
;
1436 io
[nr
].u
.out
.len
= in_len
;
1440 io
[nr
].fd
= cmd
->out
;
1441 io
[nr
].type
= POLLIN
;
1442 io
[nr
].u
.in
.buf
= out
;
1443 io
[nr
].u
.in
.hint
= out_hint
;
1447 io
[nr
].fd
= cmd
->err
;
1448 io
[nr
].type
= POLLIN
;
1449 io
[nr
].u
.in
.buf
= err
;
1450 io
[nr
].u
.in
.hint
= err_hint
;
1454 if (pump_io(io
, nr
) < 0) {
1455 finish_command(cmd
); /* throw away exit code */
1459 return finish_command(cmd
);
1465 GIT_CP_WAIT_CLEANUP
,
1468 struct parallel_processes
{
1469 size_t nr_processes
;
1472 enum child_state state
;
1473 struct child_process process
;
1478 * The struct pollfd is logically part of *children,
1479 * but the system call expects it as its own array.
1483 unsigned shutdown
: 1;
1485 size_t output_owner
;
1486 struct strbuf buffered_output
; /* of finished children */
1489 struct parallel_processes_for_signal
{
1490 const struct run_process_parallel_opts
*opts
;
1491 const struct parallel_processes
*pp
;
1494 static void kill_children(const struct parallel_processes
*pp
,
1495 const struct run_process_parallel_opts
*opts
,
1498 for (size_t i
= 0; i
< opts
->processes
; i
++)
1499 if (pp
->children
[i
].state
== GIT_CP_WORKING
)
1500 kill(pp
->children
[i
].process
.pid
, signo
);
1503 static void kill_children_signal(const struct parallel_processes_for_signal
*pp_sig
,
1506 kill_children(pp_sig
->pp
, pp_sig
->opts
, signo
);
1509 static struct parallel_processes_for_signal
*pp_for_signal
;
1511 static void handle_children_on_signal(int signo
)
1513 kill_children_signal(pp_for_signal
, signo
);
1514 sigchain_pop(signo
);
1518 static void pp_init(struct parallel_processes
*pp
,
1519 const struct run_process_parallel_opts
*opts
,
1520 struct parallel_processes_for_signal
*pp_sig
)
1522 const size_t n
= opts
->processes
;
1525 BUG("you must provide a non-zero number of processes!");
1527 trace_printf("run_processes_parallel: preparing to run up to %"PRIuMAX
" tasks",
1530 if (!opts
->get_next_task
)
1531 BUG("you need to specify a get_next_task function");
1533 CALLOC_ARRAY(pp
->children
, n
);
1535 CALLOC_ARRAY(pp
->pfd
, n
);
1537 for (size_t i
= 0; i
< n
; i
++) {
1538 strbuf_init(&pp
->children
[i
].err
, 0);
1539 child_process_init(&pp
->children
[i
].process
);
1541 pp
->pfd
[i
].events
= POLLIN
| POLLHUP
;
1547 pp_sig
->opts
= opts
;
1548 pp_for_signal
= pp_sig
;
1549 sigchain_push_common(handle_children_on_signal
);
1552 static void pp_cleanup(struct parallel_processes
*pp
,
1553 const struct run_process_parallel_opts
*opts
)
1555 trace_printf("run_processes_parallel: done");
1556 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1557 strbuf_release(&pp
->children
[i
].err
);
1558 child_process_clear(&pp
->children
[i
].process
);
1565 * When get_next_task added messages to the buffer in its last
1566 * iteration, the buffered output is non empty.
1568 strbuf_write(&pp
->buffered_output
, stderr
);
1569 strbuf_release(&pp
->buffered_output
);
1571 sigchain_pop_common();
1575 * 0 if a new task was started.
1576 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1577 * problem with starting a new command)
1578 * <0 no new job was started, user wishes to shutdown early. Use negative code
1579 * to signal the children.
1581 static int pp_start_one(struct parallel_processes
*pp
,
1582 const struct run_process_parallel_opts
*opts
)
1587 for (i
= 0; i
< opts
->processes
; i
++)
1588 if (pp
->children
[i
].state
== GIT_CP_FREE
)
1590 if (i
== opts
->processes
)
1591 BUG("bookkeeping is hard");
1594 * By default, do not inherit stdin from the parent process - otherwise,
1595 * all children would share stdin! Users may overwrite this to provide
1596 * something to the child's stdin by having their 'get_next_task'
1597 * callback assign 0 to .no_stdin and an appropriate integer to .in.
1599 pp
->children
[i
].process
.no_stdin
= 1;
1601 code
= opts
->get_next_task(&pp
->children
[i
].process
,
1602 opts
->ungroup
? NULL
: &pp
->children
[i
].err
,
1604 &pp
->children
[i
].data
);
1606 if (!opts
->ungroup
) {
1607 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1608 strbuf_reset(&pp
->children
[i
].err
);
1612 if (!opts
->ungroup
) {
1613 pp
->children
[i
].process
.err
= -1;
1614 pp
->children
[i
].process
.stdout_to_stderr
= 1;
1617 if (start_command(&pp
->children
[i
].process
)) {
1618 if (opts
->start_failure
)
1619 code
= opts
->start_failure(opts
->ungroup
? NULL
:
1620 &pp
->children
[i
].err
,
1622 pp
->children
[i
].data
);
1626 if (!opts
->ungroup
) {
1627 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1628 strbuf_reset(&pp
->children
[i
].err
);
1636 pp
->children
[i
].state
= GIT_CP_WORKING
;
1638 pp
->pfd
[i
].fd
= pp
->children
[i
].process
.err
;
1642 static void pp_buffer_stderr(struct parallel_processes
*pp
,
1643 const struct run_process_parallel_opts
*opts
,
1646 while (poll(pp
->pfd
, opts
->processes
, output_timeout
) < 0) {
1649 pp_cleanup(pp
, opts
);
1653 /* Buffer output from all pipes. */
1654 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1655 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1656 pp
->pfd
[i
].revents
& (POLLIN
| POLLHUP
)) {
1657 int n
= strbuf_read_once(&pp
->children
[i
].err
,
1658 pp
->children
[i
].process
.err
, 0);
1660 close(pp
->children
[i
].process
.err
);
1661 pp
->children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1663 if (errno
!= EAGAIN
)
1669 static void pp_output(const struct parallel_processes
*pp
)
1671 size_t i
= pp
->output_owner
;
1673 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1674 pp
->children
[i
].err
.len
) {
1675 strbuf_write(&pp
->children
[i
].err
, stderr
);
1676 strbuf_reset(&pp
->children
[i
].err
);
1680 static int pp_collect_finished(struct parallel_processes
*pp
,
1681 const struct run_process_parallel_opts
*opts
)
1687 while (pp
->nr_processes
> 0) {
1688 for (i
= 0; i
< opts
->processes
; i
++)
1689 if (pp
->children
[i
].state
== GIT_CP_WAIT_CLEANUP
)
1691 if (i
== opts
->processes
)
1694 code
= finish_command(&pp
->children
[i
].process
);
1696 if (opts
->task_finished
)
1697 code
= opts
->task_finished(code
, opts
->ungroup
? NULL
:
1698 &pp
->children
[i
].err
, opts
->data
,
1699 pp
->children
[i
].data
);
1709 pp
->children
[i
].state
= GIT_CP_FREE
;
1712 child_process_init(&pp
->children
[i
].process
);
1714 if (opts
->ungroup
) {
1715 ; /* no strbuf_*() work to do here */
1716 } else if (i
!= pp
->output_owner
) {
1717 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1718 strbuf_reset(&pp
->children
[i
].err
);
1720 const size_t n
= opts
->processes
;
1722 strbuf_write(&pp
->children
[i
].err
, stderr
);
1723 strbuf_reset(&pp
->children
[i
].err
);
1725 /* Output all other finished child processes */
1726 strbuf_write(&pp
->buffered_output
, stderr
);
1727 strbuf_reset(&pp
->buffered_output
);
1730 * Pick next process to output live.
1732 * For now we pick it randomly by doing a round
1733 * robin. Later we may want to pick the one with
1734 * the most output or the longest or shortest
1735 * running process time.
1737 for (i
= 0; i
< n
; i
++)
1738 if (pp
->children
[(pp
->output_owner
+ i
) % n
].state
== GIT_CP_WORKING
)
1740 pp
->output_owner
= (pp
->output_owner
+ i
) % n
;
1746 void run_processes_parallel(const struct run_process_parallel_opts
*opts
)
1749 int output_timeout
= 100;
1751 struct parallel_processes_for_signal pp_sig
;
1752 struct parallel_processes pp
= {
1753 .buffered_output
= STRBUF_INIT
,
1756 const char *tr2_category
= opts
->tr2_category
;
1757 const char *tr2_label
= opts
->tr2_label
;
1758 const int do_trace2
= tr2_category
&& tr2_label
;
1761 trace2_region_enter_printf(tr2_category
, tr2_label
, NULL
,
1762 "max:%d", opts
->processes
);
1764 pp_init(&pp
, opts
, &pp_sig
);
1767 i
< spawn_cap
&& !pp
.shutdown
&&
1768 pp
.nr_processes
< opts
->processes
;
1770 code
= pp_start_one(&pp
, opts
);
1775 kill_children(&pp
, opts
, -code
);
1779 if (!pp
.nr_processes
)
1781 if (opts
->ungroup
) {
1782 for (size_t i
= 0; i
< opts
->processes
; i
++)
1783 pp
.children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1785 pp_buffer_stderr(&pp
, opts
, output_timeout
);
1788 code
= pp_collect_finished(&pp
, opts
);
1792 kill_children(&pp
, opts
,-code
);
1796 pp_cleanup(&pp
, opts
);
1799 trace2_region_leave(tr2_category
, tr2_label
, NULL
);
1802 int run_auto_maintenance(int quiet
)
1805 struct child_process maint
= CHILD_PROCESS_INIT
;
1807 if (!git_config_get_bool("maintenance.auto", &enabled
) &&
1812 maint
.close_object_store
= 1;
1813 strvec_pushl(&maint
.args
, "maintenance", "run", "--auto", NULL
);
1814 strvec_push(&maint
.args
, quiet
? "--quiet" : "--no-quiet");
1816 return run_command(&maint
);
1819 void prepare_other_repo_env(struct strvec
*env
, const char *new_git_dir
)
1821 const char * const *var
;
1823 for (var
= local_repo_env
; *var
; var
++) {
1824 if (strcmp(*var
, CONFIG_DATA_ENVIRONMENT
) &&
1825 strcmp(*var
, CONFIG_COUNT_ENVIRONMENT
))
1826 strvec_push(env
, *var
);
1828 strvec_pushf(env
, "%s=%s", GIT_DIR_ENVIRONMENT
, new_git_dir
);
1831 enum start_bg_result
start_bg_command(struct child_process
*cmd
,
1832 start_bg_wait_cb
*wait_cb
,
1834 unsigned int timeout_sec
)
1836 enum start_bg_result sbgr
= SBGR_ERROR
;
1843 * We do not allow clean-on-exit because the child process
1844 * should persist in the background and possibly/probably
1845 * after this process exits. So we don't want to kill the
1846 * child during our atexit routine.
1848 if (cmd
->clean_on_exit
)
1849 BUG("start_bg_command() does not allow non-zero clean_on_exit");
1851 if (!cmd
->trace2_child_class
)
1852 cmd
->trace2_child_class
= "background";
1854 ret
= start_command(cmd
);
1857 * We assume that if `start_command()` fails, we
1858 * either get a complete `trace2_child_start() /
1859 * trace2_child_exit()` pair or it fails before the
1860 * `trace2_child_start()` is emitted, so we do not
1861 * need to worry about it here.
1863 * We also assume that `start_command()` does not add
1864 * us to the cleanup list. And that it calls
1865 * `child_process_clear()`.
1872 time_limit
+= timeout_sec
;
1875 pid_seen
= waitpid(cmd
->pid
, &wait_status
, WNOHANG
);
1879 * The child is currently running. Ask the callback
1880 * if the child is ready to do work or whether we
1881 * should keep waiting for it to boot up.
1883 ret
= (*wait_cb
)(cmd
, cb_data
);
1886 * The child is running and "ready".
1888 trace2_child_ready(cmd
, "ready");
1891 } else if (ret
> 0) {
1893 * The callback said to give it more time to boot up
1894 * (subject to our timeout limit).
1899 if (now
< time_limit
)
1903 * Our timeout has expired. We don't try to
1904 * kill the child, but rather let it continue
1905 * (hopefully) trying to startup.
1907 trace2_child_ready(cmd
, "timeout");
1908 sbgr
= SBGR_TIMEOUT
;
1912 * The cb gave up on this child. It is still running,
1913 * but our cb got an error trying to probe it.
1915 trace2_child_ready(cmd
, "error");
1916 sbgr
= SBGR_CB_ERROR
;
1921 else if (pid_seen
== cmd
->pid
) {
1922 int child_code
= -1;
1925 * The child started, but exited or was terminated
1926 * before becoming "ready".
1928 * We try to match the behavior of `wait_or_whine()`
1929 * WRT the handling of WIFSIGNALED() and WIFEXITED()
1930 * and convert the child's status to a return code for
1931 * tracing purposes and emit the `trace2_child_exit()`
1934 * We do not want the wait_or_whine() error message
1935 * because we will be called by client-side library
1938 if (WIFEXITED(wait_status
))
1939 child_code
= WEXITSTATUS(wait_status
);
1940 else if (WIFSIGNALED(wait_status
))
1941 child_code
= WTERMSIG(wait_status
) + 128;
1942 trace2_child_exit(cmd
, child_code
);
1948 else if (pid_seen
< 0 && errno
== EINTR
)
1951 trace2_child_exit(cmd
, -1);
1955 child_process_clear(cmd
);
1956 invalidate_lstat_cache();