2 #include "run-command.h"
6 #include "thread-utils.h"
8 #include "string-list.h"
13 #include "compat/nonblock.h"
15 void child_process_init(struct child_process
*child
)
17 struct child_process blank
= CHILD_PROCESS_INIT
;
18 memcpy(child
, &blank
, sizeof(*child
));
21 void child_process_clear(struct child_process
*child
)
23 strvec_clear(&child
->args
);
24 strvec_clear(&child
->env
);
27 struct child_to_clean
{
29 struct child_process
*process
;
30 struct child_to_clean
*next
;
32 static struct child_to_clean
*children_to_clean
;
33 static int installed_child_cleanup_handler
;
35 static void cleanup_children(int sig
, int in_signal
)
37 struct child_to_clean
*children_to_wait_for
= NULL
;
39 while (children_to_clean
) {
40 struct child_to_clean
*p
= children_to_clean
;
41 children_to_clean
= p
->next
;
43 if (p
->process
&& !in_signal
) {
44 struct child_process
*process
= p
->process
;
45 if (process
->clean_on_exit_handler
) {
47 "trace: run_command: running exit handler for pid %"
48 PRIuMAX
, (uintmax_t)p
->pid
50 process
->clean_on_exit_handler(process
);
56 if (p
->process
&& p
->process
->wait_after_clean
) {
57 p
->next
= children_to_wait_for
;
58 children_to_wait_for
= p
;
65 while (children_to_wait_for
) {
66 struct child_to_clean
*p
= children_to_wait_for
;
67 children_to_wait_for
= p
->next
;
69 while (waitpid(p
->pid
, NULL
, 0) < 0 && errno
== EINTR
)
70 ; /* spin waiting for process exit or error */
77 static void cleanup_children_on_signal(int sig
)
79 cleanup_children(sig
, 1);
84 static void cleanup_children_on_exit(void)
86 cleanup_children(SIGTERM
, 0);
89 static void mark_child_for_cleanup(pid_t pid
, struct child_process
*process
)
91 struct child_to_clean
*p
= xmalloc(sizeof(*p
));
94 p
->next
= children_to_clean
;
95 children_to_clean
= p
;
97 if (!installed_child_cleanup_handler
) {
98 atexit(cleanup_children_on_exit
);
99 sigchain_push_common(cleanup_children_on_signal
);
100 installed_child_cleanup_handler
= 1;
104 static void clear_child_for_cleanup(pid_t pid
)
106 struct child_to_clean
**pp
;
108 for (pp
= &children_to_clean
; *pp
; pp
= &(*pp
)->next
) {
109 struct child_to_clean
*clean_me
= *pp
;
111 if (clean_me
->pid
== pid
) {
112 *pp
= clean_me
->next
;
119 static inline void close_pair(int fd
[2])
125 int is_executable(const char *name
)
129 if (stat(name
, &st
) || /* stat, not lstat */
130 !S_ISREG(st
.st_mode
))
133 #if defined(GIT_WINDOWS_NATIVE)
135 * On Windows there is no executable bit. The file extension
136 * indicates whether it can be run as an executable, and Git
137 * has special-handling to detect scripts and launch them
138 * through the indicated script interpreter. We test for the
139 * file extension first because virus scanners may make
140 * it quite expensive to open many files.
142 if (ends_with(name
, ".exe"))
147 * Now that we know it does not have an executable extension,
148 * peek into the file instead.
152 int fd
= open(name
, O_RDONLY
);
153 st
.st_mode
&= ~S_IXUSR
;
155 n
= read(fd
, buf
, 2);
157 /* look for a she-bang */
158 if (!strcmp(buf
, "#!"))
159 st
.st_mode
|= S_IXUSR
;
164 return st
.st_mode
& S_IXUSR
;
168 * Search $PATH for a command. This emulates the path search that
169 * execvp would perform, without actually executing the command so it
170 * can be used before fork() to prepare to run a command using
171 * execve() or after execvp() to diagnose why it failed.
173 * The caller should ensure that file contains no directory
176 * Returns the path to the command, as found in $PATH or NULL if the
177 * command could not be found. The caller inherits ownership of the memory
178 * used to store the resultant path.
180 * This should not be used on Windows, where the $PATH search rules
181 * are more complicated (e.g., a search for "foo" should find
184 static char *locate_in_PATH(const char *file
)
186 const char *p
= getenv("PATH");
187 struct strbuf buf
= STRBUF_INIT
;
193 const char *end
= strchrnul(p
, ':');
197 /* POSIX specifies an empty entry as the current directory. */
199 strbuf_add(&buf
, p
, end
- p
);
200 strbuf_addch(&buf
, '/');
202 strbuf_addstr(&buf
, file
);
204 if (is_executable(buf
.buf
))
205 return strbuf_detach(&buf
, NULL
);
212 strbuf_release(&buf
);
216 int exists_in_PATH(const char *command
)
218 char *r
= locate_in_PATH(command
);
219 int found
= r
!= NULL
;
224 int sane_execvp(const char *file
, char * const argv
[])
226 #ifndef GIT_WINDOWS_NATIVE
228 * execvp() doesn't return, so we all we can do is tell trace2
229 * what we are about to do and let it leave a hint in the log
230 * (unless of course the execvp() fails).
232 * we skip this for Windows because the compat layer already
233 * has to emulate the execvp() call anyway.
235 int exec_id
= trace2_exec(file
, (const char **)argv
);
238 if (!execvp(file
, argv
))
239 return 0; /* cannot happen ;-) */
241 #ifndef GIT_WINDOWS_NATIVE
244 trace2_exec_result(exec_id
, ec
);
250 * When a command can't be found because one of the directories
251 * listed in $PATH is unsearchable, execvp reports EACCES, but
252 * careful usability testing (read: analysis of occasional bug
253 * reports) reveals that "No such file or directory" is more
256 * We avoid commands with "/", because execvp will not do $PATH
257 * lookups in that case.
259 * The reassignment of EACCES to errno looks like a no-op below,
260 * but we need to protect against exists_in_PATH overwriting errno.
262 if (errno
== EACCES
&& !strchr(file
, '/'))
263 errno
= exists_in_PATH(file
) ? EACCES
: ENOENT
;
264 else if (errno
== ENOTDIR
&& !strchr(file
, '/'))
269 static const char **prepare_shell_cmd(struct strvec
*out
, const char **argv
)
272 BUG("shell command is empty");
274 if (strcspn(argv
[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv
[0])) {
275 #ifndef GIT_WINDOWS_NATIVE
276 strvec_push(out
, SHELL_PATH
);
278 strvec_push(out
, "sh");
280 strvec_push(out
, "-c");
283 * If we have no extra arguments, we do not even need to
284 * bother with the "$@" magic.
287 strvec_push(out
, argv
[0]);
289 strvec_pushf(out
, "%s \"$@\"", argv
[0]);
292 strvec_pushv(out
, argv
);
296 #ifndef GIT_WINDOWS_NATIVE
297 static int child_notifier
= -1;
303 CHILD_ERR_SIGPROCMASK
,
310 enum child_errcode err
;
311 int syserr
; /* errno */
314 static void child_die(enum child_errcode err
)
316 struct child_err buf
;
321 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
322 xwrite(child_notifier
, &buf
, sizeof(buf
));
326 static void child_dup2(int fd
, int to
)
328 if (dup2(fd
, to
) < 0)
329 child_die(CHILD_ERR_DUP2
);
332 static void child_close(int fd
)
335 child_die(CHILD_ERR_CLOSE
);
338 static void child_close_pair(int fd
[2])
344 static void child_error_fn(const char *err
, va_list params
)
346 const char msg
[] = "error() should not be called in child\n";
347 xwrite(2, msg
, sizeof(msg
) - 1);
350 static void child_warn_fn(const char *err
, va_list params
)
352 const char msg
[] = "warn() should not be called in child\n";
353 xwrite(2, msg
, sizeof(msg
) - 1);
356 static void NORETURN
child_die_fn(const char *err
, va_list params
)
358 const char msg
[] = "die() should not be called in child\n";
359 xwrite(2, msg
, sizeof(msg
) - 1);
363 /* this runs in the parent process */
364 static void child_err_spew(struct child_process
*cmd
, struct child_err
*cerr
)
366 static void (*old_errfn
)(const char *err
, va_list params
);
367 report_fn die_message_routine
= get_die_message_routine();
369 old_errfn
= get_error_routine();
370 set_error_routine(die_message_routine
);
371 errno
= cerr
->syserr
;
374 case CHILD_ERR_CHDIR
:
375 error_errno("exec '%s': cd to '%s' failed",
376 cmd
->args
.v
[0], cmd
->dir
);
379 error_errno("dup2() in child failed");
381 case CHILD_ERR_CLOSE
:
382 error_errno("close() in child failed");
384 case CHILD_ERR_SIGPROCMASK
:
385 error_errno("sigprocmask failed restoring signals");
387 case CHILD_ERR_ENOENT
:
388 error_errno("cannot run %s", cmd
->args
.v
[0]);
390 case CHILD_ERR_SILENT
:
392 case CHILD_ERR_ERRNO
:
393 error_errno("cannot exec '%s'", cmd
->args
.v
[0]);
396 set_error_routine(old_errfn
);
399 static int prepare_cmd(struct strvec
*out
, const struct child_process
*cmd
)
402 BUG("command is empty");
405 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
406 * attempt to interpret the command with 'sh'.
408 strvec_push(out
, SHELL_PATH
);
411 prepare_git_cmd(out
, cmd
->args
.v
);
412 } else if (cmd
->use_shell
) {
413 prepare_shell_cmd(out
, cmd
->args
.v
);
415 strvec_pushv(out
, cmd
->args
.v
);
419 * If there are no dir separator characters in the command then perform
420 * a path lookup and use the resolved path as the command to exec. If
421 * there are dir separator characters, we have exec attempt to invoke
422 * the command directly.
424 if (!has_dir_sep(out
->v
[1])) {
425 char *program
= locate_in_PATH(out
->v
[1]);
427 free((char *)out
->v
[1]);
439 static char **prep_childenv(const char *const *deltaenv
)
441 extern char **environ
;
443 struct string_list env
= STRING_LIST_INIT_DUP
;
444 struct strbuf key
= STRBUF_INIT
;
445 const char *const *p
;
448 /* Construct a sorted string list consisting of the current environ */
449 for (p
= (const char *const *) environ
; p
&& *p
; p
++) {
450 const char *equals
= strchr(*p
, '=');
454 strbuf_add(&key
, *p
, equals
- *p
);
455 string_list_append(&env
, key
.buf
)->util
= (void *) *p
;
457 string_list_append(&env
, *p
)->util
= (void *) *p
;
460 string_list_sort(&env
);
462 /* Merge in 'deltaenv' with the current environ */
463 for (p
= deltaenv
; p
&& *p
; p
++) {
464 const char *equals
= strchr(*p
, '=');
467 /* ('key=value'), insert or replace entry */
469 strbuf_add(&key
, *p
, equals
- *p
);
470 string_list_insert(&env
, key
.buf
)->util
= (void *) *p
;
472 /* otherwise ('key') remove existing entry */
473 string_list_remove(&env
, *p
, 0);
477 /* Create an array of 'char *' to be used as the childenv */
478 ALLOC_ARRAY(childenv
, env
.nr
+ 1);
479 for (i
= 0; i
< env
.nr
; i
++)
480 childenv
[i
] = env
.items
[i
].util
;
481 childenv
[env
.nr
] = NULL
;
483 string_list_clear(&env
, 0);
484 strbuf_release(&key
);
488 struct atfork_state
{
495 #define CHECK_BUG(err, msg) \
499 BUG("%s: %s", msg, strerror(e)); \
502 static void atfork_prepare(struct atfork_state
*as
)
506 if (sigfillset(&all
))
507 die_errno("sigfillset");
509 if (sigprocmask(SIG_SETMASK
, &all
, &as
->old
))
510 die_errno("sigprocmask");
512 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &all
, &as
->old
),
513 "blocking all signals");
514 CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &as
->cs
),
515 "disabling cancellation");
519 static void atfork_parent(struct atfork_state
*as
)
522 if (sigprocmask(SIG_SETMASK
, &as
->old
, NULL
))
523 die_errno("sigprocmask");
525 CHECK_BUG(pthread_setcancelstate(as
->cs
, NULL
),
526 "re-enabling cancellation");
527 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &as
->old
, NULL
),
528 "restoring signal mask");
531 #endif /* GIT_WINDOWS_NATIVE */
533 static inline void set_cloexec(int fd
)
535 int flags
= fcntl(fd
, F_GETFD
);
537 fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
540 static int wait_or_whine(pid_t pid
, const char *argv0
, int in_signal
)
542 int status
, code
= -1;
544 int failed_errno
= 0;
546 while ((waiting
= waitpid(pid
, &status
, 0)) < 0 && errno
== EINTR
)
550 failed_errno
= errno
;
552 error_errno("waitpid for %s failed", argv0
);
553 } else if (waiting
!= pid
) {
555 error("waitpid is confused (%s)", argv0
);
556 } else if (WIFSIGNALED(status
)) {
557 code
= WTERMSIG(status
);
558 if (!in_signal
&& code
!= SIGINT
&& code
!= SIGQUIT
&& code
!= SIGPIPE
)
559 error("%s died of signal %d", argv0
, code
);
561 * This return value is chosen so that code & 0xff
562 * mimics the exit code that a POSIX shell would report for
563 * a program that died from this signal.
566 } else if (WIFEXITED(status
)) {
567 code
= WEXITSTATUS(status
);
570 error("waitpid is confused (%s)", argv0
);
574 clear_child_for_cleanup(pid
);
576 errno
= failed_errno
;
580 static void trace_add_env(struct strbuf
*dst
, const char *const *deltaenv
)
582 struct string_list envs
= STRING_LIST_INIT_DUP
;
583 const char *const *e
;
585 int printed_unset
= 0;
587 /* Last one wins, see run-command.c:prep_childenv() for context */
588 for (e
= deltaenv
; e
&& *e
; e
++) {
589 struct strbuf key
= STRBUF_INIT
;
590 char *equals
= strchr(*e
, '=');
593 strbuf_add(&key
, *e
, equals
- *e
);
594 string_list_insert(&envs
, key
.buf
)->util
= equals
+ 1;
596 string_list_insert(&envs
, *e
)->util
= NULL
;
598 strbuf_release(&key
);
601 /* "unset X Y...;" */
602 for (i
= 0; i
< envs
.nr
; i
++) {
603 const char *var
= envs
.items
[i
].string
;
604 const char *val
= envs
.items
[i
].util
;
606 if (val
|| !getenv(var
))
609 if (!printed_unset
) {
610 strbuf_addstr(dst
, " unset");
613 strbuf_addf(dst
, " %s", var
);
616 strbuf_addch(dst
, ';');
618 /* ... followed by "A=B C=D ..." */
619 for (i
= 0; i
< envs
.nr
; i
++) {
620 const char *var
= envs
.items
[i
].string
;
621 const char *val
= envs
.items
[i
].util
;
627 oldval
= getenv(var
);
628 if (oldval
&& !strcmp(val
, oldval
))
631 strbuf_addf(dst
, " %s=", var
);
632 sq_quote_buf_pretty(dst
, val
);
634 string_list_clear(&envs
, 0);
637 static void trace_run_command(const struct child_process
*cp
)
639 struct strbuf buf
= STRBUF_INIT
;
641 if (!trace_want(&trace_default_key
))
644 strbuf_addstr(&buf
, "trace: run_command:");
646 strbuf_addstr(&buf
, " cd ");
647 sq_quote_buf_pretty(&buf
, cp
->dir
);
648 strbuf_addch(&buf
, ';');
650 trace_add_env(&buf
, cp
->env
.v
);
652 strbuf_addstr(&buf
, " git");
653 sq_quote_argv_pretty(&buf
, cp
->args
.v
);
655 trace_printf("%s", buf
.buf
);
656 strbuf_release(&buf
);
659 int start_command(struct child_process
*cmd
)
661 int need_in
, need_out
, need_err
;
662 int fdin
[2], fdout
[2], fderr
[2];
667 * In case of errors we must keep the promise to close FDs
668 * that have been passed in via ->in and ->out.
671 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
673 if (pipe(fdin
) < 0) {
674 failed_errno
= errno
;
677 str
= "standard input";
683 need_out
= !cmd
->no_stdout
684 && !cmd
->stdout_to_stderr
687 if (pipe(fdout
) < 0) {
688 failed_errno
= errno
;
693 str
= "standard output";
699 need_err
= !cmd
->no_stderr
&& cmd
->err
< 0;
701 if (pipe(fderr
) < 0) {
702 failed_errno
= errno
;
711 str
= "standard error";
713 error("cannot create %s pipe for %s: %s",
714 str
, cmd
->args
.v
[0], strerror(failed_errno
));
715 child_process_clear(cmd
);
716 errno
= failed_errno
;
722 trace2_child_start(cmd
);
723 trace_run_command(cmd
);
727 if (cmd
->close_object_store
)
728 close_object_store(the_repository
->objects
);
730 #ifndef GIT_WINDOWS_NATIVE
735 struct strvec argv
= STRVEC_INIT
;
736 struct child_err cerr
;
737 struct atfork_state as
;
739 if (prepare_cmd(&argv
, cmd
) < 0) {
740 failed_errno
= errno
;
742 if (!cmd
->silent_exec_failure
)
743 error_errno("cannot run %s", cmd
->args
.v
[0]);
747 if (pipe(notify_pipe
))
748 notify_pipe
[0] = notify_pipe
[1] = -1;
750 if (cmd
->no_stdin
|| cmd
->no_stdout
|| cmd
->no_stderr
) {
751 null_fd
= xopen("/dev/null", O_RDWR
| O_CLOEXEC
);
752 set_cloexec(null_fd
);
755 childenv
= prep_childenv(cmd
->env
.v
);
759 * NOTE: In order to prevent deadlocking when using threads special
760 * care should be taken with the function calls made in between the
761 * fork() and exec() calls. No calls should be made to functions which
762 * require acquiring a lock (e.g. malloc) as the lock could have been
763 * held by another thread at the time of forking, causing the lock to
764 * never be released in the child process. This means only
765 * Async-Signal-Safe functions are permitted in the child.
768 failed_errno
= errno
;
772 * Ensure the default die/error/warn routines do not get
773 * called, they can take stdio locks and malloc.
775 set_die_routine(child_die_fn
);
776 set_error_routine(child_error_fn
);
777 set_warn_routine(child_warn_fn
);
779 close(notify_pipe
[0]);
780 set_cloexec(notify_pipe
[1]);
781 child_notifier
= notify_pipe
[1];
784 child_dup2(null_fd
, 0);
786 child_dup2(fdin
[0], 0);
787 child_close_pair(fdin
);
788 } else if (cmd
->in
) {
789 child_dup2(cmd
->in
, 0);
790 child_close(cmd
->in
);
794 child_dup2(null_fd
, 2);
796 child_dup2(fderr
[1], 2);
797 child_close_pair(fderr
);
798 } else if (cmd
->err
> 1) {
799 child_dup2(cmd
->err
, 2);
800 child_close(cmd
->err
);
804 child_dup2(null_fd
, 1);
805 else if (cmd
->stdout_to_stderr
)
808 child_dup2(fdout
[1], 1);
809 child_close_pair(fdout
);
810 } else if (cmd
->out
> 1) {
811 child_dup2(cmd
->out
, 1);
812 child_close(cmd
->out
);
815 if (cmd
->dir
&& chdir(cmd
->dir
))
816 child_die(CHILD_ERR_CHDIR
);
819 * restore default signal handlers here, in case
820 * we catch a signal right before execve below
822 for (sig
= 1; sig
< NSIG
; sig
++) {
823 /* ignored signals get reset to SIG_DFL on execve */
824 if (signal(sig
, SIG_DFL
) == SIG_IGN
)
825 signal(sig
, SIG_IGN
);
828 if (sigprocmask(SIG_SETMASK
, &as
.old
, NULL
) != 0)
829 child_die(CHILD_ERR_SIGPROCMASK
);
832 * Attempt to exec using the command and arguments starting at
833 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
834 * be used in the event exec failed with ENOEXEC at which point
835 * we will try to interpret the command using 'sh'.
837 execve(argv
.v
[1], (char *const *) argv
.v
+ 1,
838 (char *const *) childenv
);
839 if (errno
== ENOEXEC
)
840 execve(argv
.v
[0], (char *const *) argv
.v
,
841 (char *const *) childenv
);
843 if (errno
== ENOENT
) {
844 if (cmd
->silent_exec_failure
)
845 child_die(CHILD_ERR_SILENT
);
846 child_die(CHILD_ERR_ENOENT
);
848 child_die(CHILD_ERR_ERRNO
);
853 error_errno("cannot fork() for %s", cmd
->args
.v
[0]);
854 else if (cmd
->clean_on_exit
)
855 mark_child_for_cleanup(cmd
->pid
, cmd
);
858 * Wait for child's exec. If the exec succeeds (or if fork()
859 * failed), EOF is seen immediately by the parent. Otherwise, the
860 * child process sends a child_err struct.
861 * Note that use of this infrastructure is completely advisory,
862 * therefore, we keep error checks minimal.
864 close(notify_pipe
[1]);
865 if (xread(notify_pipe
[0], &cerr
, sizeof(cerr
)) == sizeof(cerr
)) {
867 * At this point we know that fork() succeeded, but exec()
868 * failed. Errors have been reported to our stderr.
870 wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
871 child_err_spew(cmd
, &cerr
);
872 failed_errno
= errno
;
875 close(notify_pipe
[0]);
886 int fhin
= 0, fhout
= 1, fherr
= 2;
887 const char **sargv
= cmd
->args
.v
;
888 struct strvec nargv
= STRVEC_INIT
;
891 fhin
= open("/dev/null", O_RDWR
);
898 fherr
= open("/dev/null", O_RDWR
);
900 fherr
= dup(fderr
[1]);
901 else if (cmd
->err
> 2)
902 fherr
= dup(cmd
->err
);
905 fhout
= open("/dev/null", O_RDWR
);
906 else if (cmd
->stdout_to_stderr
)
909 fhout
= dup(fdout
[1]);
910 else if (cmd
->out
> 1)
911 fhout
= dup(cmd
->out
);
914 cmd
->args
.v
= prepare_git_cmd(&nargv
, sargv
);
915 else if (cmd
->use_shell
)
916 cmd
->args
.v
= prepare_shell_cmd(&nargv
, sargv
);
918 cmd
->pid
= mingw_spawnvpe(cmd
->args
.v
[0], cmd
->args
.v
,
920 cmd
->dir
, fhin
, fhout
, fherr
);
921 failed_errno
= errno
;
922 if (cmd
->pid
< 0 && (!cmd
->silent_exec_failure
|| errno
!= ENOENT
))
923 error_errno("cannot spawn %s", cmd
->args
.v
[0]);
924 if (cmd
->clean_on_exit
&& cmd
->pid
>= 0)
925 mark_child_for_cleanup(cmd
->pid
, cmd
);
927 strvec_clear(&nargv
);
939 trace2_child_exit(cmd
, -1);
953 child_process_clear(cmd
);
954 errno
= failed_errno
;
976 int finish_command(struct child_process
*cmd
)
978 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
979 trace2_child_exit(cmd
, ret
);
980 child_process_clear(cmd
);
981 invalidate_lstat_cache();
985 int finish_command_in_signal(struct child_process
*cmd
)
987 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 1);
989 trace2_child_exit(cmd
, ret
);
994 int run_command(struct child_process
*cmd
)
998 if (cmd
->out
< 0 || cmd
->err
< 0)
999 BUG("run_command with a pipe can cause deadlock");
1001 code
= start_command(cmd
);
1004 return finish_command(cmd
);
1007 int run_command_v_opt(const char **argv
, int opt
)
1009 return run_command_v_opt_cd_env(argv
, opt
, NULL
, NULL
);
1012 int run_command_v_opt_tr2(const char **argv
, int opt
, const char *tr2_class
)
1014 return run_command_v_opt_cd_env_tr2(argv
, opt
, NULL
, NULL
, tr2_class
);
1017 int run_command_v_opt_cd_env(const char **argv
, int opt
, const char *dir
, const char *const *env
)
1019 return run_command_v_opt_cd_env_tr2(argv
, opt
, dir
, env
, NULL
);
1022 int run_command_v_opt_cd_env_tr2(const char **argv
, int opt
, const char *dir
,
1023 const char *const *env
, const char *tr2_class
)
1025 struct child_process cmd
= CHILD_PROCESS_INIT
;
1026 strvec_pushv(&cmd
.args
, argv
);
1027 cmd
.no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
1028 cmd
.git_cmd
= opt
& RUN_GIT_CMD
? 1 : 0;
1029 cmd
.stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
1030 cmd
.silent_exec_failure
= opt
& RUN_SILENT_EXEC_FAILURE
? 1 : 0;
1031 cmd
.use_shell
= opt
& RUN_USING_SHELL
? 1 : 0;
1032 cmd
.clean_on_exit
= opt
& RUN_CLEAN_ON_EXIT
? 1 : 0;
1033 cmd
.wait_after_clean
= opt
& RUN_WAIT_AFTER_CLEAN
? 1 : 0;
1034 cmd
.close_object_store
= opt
& RUN_CLOSE_OBJECT_STORE
? 1 : 0;
1037 strvec_pushv(&cmd
.env
, (const char **)env
);
1038 cmd
.trace2_child_class
= tr2_class
;
1039 return run_command(&cmd
);
1043 static pthread_t main_thread
;
1044 static int main_thread_set
;
1045 static pthread_key_t async_key
;
1046 static pthread_key_t async_die_counter
;
1048 static void *run_thread(void *data
)
1050 struct async
*async
= data
;
1053 if (async
->isolate_sigpipe
) {
1056 sigaddset(&mask
, SIGPIPE
);
1057 if (pthread_sigmask(SIG_BLOCK
, &mask
, NULL
) < 0) {
1058 ret
= error("unable to block SIGPIPE in async thread");
1063 pthread_setspecific(async_key
, async
);
1064 ret
= async
->proc(async
->proc_in
, async
->proc_out
, async
->data
);
1068 static NORETURN
void die_async(const char *err
, va_list params
)
1070 report_fn die_message_fn
= get_die_message_routine();
1072 die_message_fn(err
, params
);
1075 struct async
*async
= pthread_getspecific(async_key
);
1076 if (async
->proc_in
>= 0)
1077 close(async
->proc_in
);
1078 if (async
->proc_out
>= 0)
1079 close(async
->proc_out
);
1080 pthread_exit((void *)128);
1086 static int async_die_is_recursing(void)
1088 void *ret
= pthread_getspecific(async_die_counter
);
1089 pthread_setspecific(async_die_counter
, &async_die_counter
); /* set to any non-NULL valid pointer */
1095 if (!main_thread_set
)
1096 return 0; /* no asyncs started yet */
1097 return !pthread_equal(main_thread
, pthread_self());
1100 static void NORETURN
async_exit(int code
)
1102 pthread_exit((void *)(intptr_t)code
);
1108 void (**handlers
)(void);
1113 static int git_atexit_installed
;
1115 static void git_atexit_dispatch(void)
1119 for (i
=git_atexit_hdlrs
.nr
; i
; i
--)
1120 git_atexit_hdlrs
.handlers
[i
-1]();
1123 static void git_atexit_clear(void)
1125 free(git_atexit_hdlrs
.handlers
);
1126 memset(&git_atexit_hdlrs
, 0, sizeof(git_atexit_hdlrs
));
1127 git_atexit_installed
= 0;
1131 int git_atexit(void (*handler
)(void))
1133 ALLOC_GROW(git_atexit_hdlrs
.handlers
, git_atexit_hdlrs
.nr
+ 1, git_atexit_hdlrs
.alloc
);
1134 git_atexit_hdlrs
.handlers
[git_atexit_hdlrs
.nr
++] = handler
;
1135 if (!git_atexit_installed
) {
1136 if (atexit(&git_atexit_dispatch
))
1138 git_atexit_installed
= 1;
1142 #define atexit git_atexit
1144 static int process_is_async
;
1147 return process_is_async
;
1150 static void NORETURN
async_exit(int code
)
1157 void check_pipe(int err
)
1163 signal(SIGPIPE
, SIG_DFL
);
1165 /* Should never happen, but just in case... */
1170 int start_async(struct async
*async
)
1172 int need_in
, need_out
;
1173 int fdin
[2], fdout
[2];
1174 int proc_in
, proc_out
;
1176 need_in
= async
->in
< 0;
1178 if (pipe(fdin
) < 0) {
1181 return error_errno("cannot create pipe");
1183 async
->in
= fdin
[1];
1186 need_out
= async
->out
< 0;
1188 if (pipe(fdout
) < 0) {
1193 return error_errno("cannot create pipe");
1195 async
->out
= fdout
[0];
1201 proc_in
= async
->in
;
1206 proc_out
= fdout
[1];
1207 else if (async
->out
)
1208 proc_out
= async
->out
;
1213 /* Flush stdio before fork() to avoid cloning buffers */
1216 async
->pid
= fork();
1217 if (async
->pid
< 0) {
1218 error_errno("fork (async) failed");
1227 process_is_async
= 1;
1228 exit(!!async
->proc(proc_in
, proc_out
, async
->data
));
1231 mark_child_for_cleanup(async
->pid
, NULL
);
1240 else if (async
->out
)
1243 if (!main_thread_set
) {
1245 * We assume that the first time that start_async is called
1246 * it is from the main thread.
1248 main_thread_set
= 1;
1249 main_thread
= pthread_self();
1250 pthread_key_create(&async_key
, NULL
);
1251 pthread_key_create(&async_die_counter
, NULL
);
1252 set_die_routine(die_async
);
1253 set_die_is_recursing_routine(async_die_is_recursing
);
1257 set_cloexec(proc_in
);
1259 set_cloexec(proc_out
);
1260 async
->proc_in
= proc_in
;
1261 async
->proc_out
= proc_out
;
1263 int err
= pthread_create(&async
->tid
, NULL
, run_thread
, async
);
1265 error(_("cannot create async thread: %s"), strerror(err
));
1280 else if (async
->out
)
1285 int finish_async(struct async
*async
)
1288 int ret
= wait_or_whine(async
->pid
, "child process", 0);
1290 invalidate_lstat_cache();
1294 void *ret
= (void *)(intptr_t)(-1);
1296 if (pthread_join(async
->tid
, &ret
))
1297 error("pthread_join failed");
1298 invalidate_lstat_cache();
1299 return (int)(intptr_t)ret
;
1304 int async_with_fork(void)
1314 /* initialized by caller */
1316 int type
; /* POLLOUT or POLLIN */
1328 /* returned by pump_io */
1329 int error
; /* 0 for success, otherwise errno */
1335 static int pump_io_round(struct io_pump
*slots
, int nr
, struct pollfd
*pfd
)
1340 for (i
= 0; i
< nr
; i
++) {
1341 struct io_pump
*io
= &slots
[i
];
1344 pfd
[pollsize
].fd
= io
->fd
;
1345 pfd
[pollsize
].events
= io
->type
;
1346 io
->pfd
= &pfd
[pollsize
++];
1352 if (poll(pfd
, pollsize
, -1) < 0) {
1355 die_errno("poll failed");
1358 for (i
= 0; i
< nr
; i
++) {
1359 struct io_pump
*io
= &slots
[i
];
1364 if (!(io
->pfd
->revents
& (POLLOUT
|POLLIN
|POLLHUP
|POLLERR
|POLLNVAL
)))
1367 if (io
->type
== POLLOUT
) {
1371 * Don't use xwrite() here. It loops forever on EAGAIN,
1372 * and we're in our own poll() loop here.
1374 * Note that we lose xwrite()'s handling of MAX_IO_SIZE
1375 * and EINTR, so we have to implement those ourselves.
1377 len
= write(io
->fd
, io
->u
.out
.buf
,
1378 io
->u
.out
.len
<= MAX_IO_SIZE
?
1379 io
->u
.out
.len
: MAX_IO_SIZE
);
1381 if (errno
!= EINTR
&& errno
!= EAGAIN
&&
1388 io
->u
.out
.buf
+= len
;
1389 io
->u
.out
.len
-= len
;
1390 if (!io
->u
.out
.len
) {
1397 if (io
->type
== POLLIN
) {
1398 ssize_t len
= strbuf_read_once(io
->u
.in
.buf
,
1399 io
->fd
, io
->u
.in
.hint
);
1412 static int pump_io(struct io_pump
*slots
, int nr
)
1417 for (i
= 0; i
< nr
; i
++)
1420 ALLOC_ARRAY(pfd
, nr
);
1421 while (pump_io_round(slots
, nr
, pfd
))
1425 /* There may be multiple errno values, so just pick the first. */
1426 for (i
= 0; i
< nr
; i
++) {
1427 if (slots
[i
].error
) {
1428 errno
= slots
[i
].error
;
1436 int pipe_command(struct child_process
*cmd
,
1437 const char *in
, size_t in_len
,
1438 struct strbuf
*out
, size_t out_hint
,
1439 struct strbuf
*err
, size_t err_hint
)
1441 struct io_pump io
[3];
1451 if (start_command(cmd
) < 0)
1455 if (enable_pipe_nonblock(cmd
->in
) < 0) {
1456 error_errno("unable to make pipe non-blocking");
1464 io
[nr
].fd
= cmd
->in
;
1465 io
[nr
].type
= POLLOUT
;
1466 io
[nr
].u
.out
.buf
= in
;
1467 io
[nr
].u
.out
.len
= in_len
;
1471 io
[nr
].fd
= cmd
->out
;
1472 io
[nr
].type
= POLLIN
;
1473 io
[nr
].u
.in
.buf
= out
;
1474 io
[nr
].u
.in
.hint
= out_hint
;
1478 io
[nr
].fd
= cmd
->err
;
1479 io
[nr
].type
= POLLIN
;
1480 io
[nr
].u
.in
.buf
= err
;
1481 io
[nr
].u
.in
.hint
= err_hint
;
1485 if (pump_io(io
, nr
) < 0) {
1486 finish_command(cmd
); /* throw away exit code */
1490 return finish_command(cmd
);
1496 GIT_CP_WAIT_CLEANUP
,
1499 struct parallel_processes
{
1500 size_t nr_processes
;
1503 enum child_state state
;
1504 struct child_process process
;
1509 * The struct pollfd is logically part of *children,
1510 * but the system call expects it as its own array.
1514 unsigned shutdown
: 1;
1516 size_t output_owner
;
1517 struct strbuf buffered_output
; /* of finished children */
1520 struct parallel_processes_for_signal
{
1521 const struct run_process_parallel_opts
*opts
;
1522 const struct parallel_processes
*pp
;
1525 static void kill_children(const struct parallel_processes
*pp
,
1526 const struct run_process_parallel_opts
*opts
,
1529 for (size_t i
= 0; i
< opts
->processes
; i
++)
1530 if (pp
->children
[i
].state
== GIT_CP_WORKING
)
1531 kill(pp
->children
[i
].process
.pid
, signo
);
1534 static void kill_children_signal(const struct parallel_processes_for_signal
*pp_sig
,
1537 kill_children(pp_sig
->pp
, pp_sig
->opts
, signo
);
1540 static struct parallel_processes_for_signal
*pp_for_signal
;
1542 static void handle_children_on_signal(int signo
)
1544 kill_children_signal(pp_for_signal
, signo
);
1545 sigchain_pop(signo
);
1549 static void pp_init(struct parallel_processes
*pp
,
1550 const struct run_process_parallel_opts
*opts
,
1551 struct parallel_processes_for_signal
*pp_sig
)
1553 const size_t n
= opts
->processes
;
1556 BUG("you must provide a non-zero number of processes!");
1558 trace_printf("run_processes_parallel: preparing to run up to %"PRIuMAX
" tasks",
1561 if (!opts
->get_next_task
)
1562 BUG("you need to specify a get_next_task function");
1564 CALLOC_ARRAY(pp
->children
, n
);
1566 CALLOC_ARRAY(pp
->pfd
, n
);
1568 for (size_t i
= 0; i
< n
; i
++) {
1569 strbuf_init(&pp
->children
[i
].err
, 0);
1570 child_process_init(&pp
->children
[i
].process
);
1572 pp
->pfd
[i
].events
= POLLIN
| POLLHUP
;
1578 pp_sig
->opts
= opts
;
1579 pp_for_signal
= pp_sig
;
1580 sigchain_push_common(handle_children_on_signal
);
1583 static void pp_cleanup(struct parallel_processes
*pp
,
1584 const struct run_process_parallel_opts
*opts
)
1586 trace_printf("run_processes_parallel: done");
1587 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1588 strbuf_release(&pp
->children
[i
].err
);
1589 child_process_clear(&pp
->children
[i
].process
);
1596 * When get_next_task added messages to the buffer in its last
1597 * iteration, the buffered output is non empty.
1599 strbuf_write(&pp
->buffered_output
, stderr
);
1600 strbuf_release(&pp
->buffered_output
);
1602 sigchain_pop_common();
1606 * 0 if a new task was started.
1607 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1608 * problem with starting a new command)
1609 * <0 no new job was started, user wishes to shutdown early. Use negative code
1610 * to signal the children.
1612 static int pp_start_one(struct parallel_processes
*pp
,
1613 const struct run_process_parallel_opts
*opts
)
1618 for (i
= 0; i
< opts
->processes
; i
++)
1619 if (pp
->children
[i
].state
== GIT_CP_FREE
)
1621 if (i
== opts
->processes
)
1622 BUG("bookkeeping is hard");
1624 code
= opts
->get_next_task(&pp
->children
[i
].process
,
1625 opts
->ungroup
? NULL
: &pp
->children
[i
].err
,
1627 &pp
->children
[i
].data
);
1629 if (!opts
->ungroup
) {
1630 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1631 strbuf_reset(&pp
->children
[i
].err
);
1635 if (!opts
->ungroup
) {
1636 pp
->children
[i
].process
.err
= -1;
1637 pp
->children
[i
].process
.stdout_to_stderr
= 1;
1639 pp
->children
[i
].process
.no_stdin
= 1;
1641 if (start_command(&pp
->children
[i
].process
)) {
1642 if (opts
->start_failure
)
1643 code
= opts
->start_failure(opts
->ungroup
? NULL
:
1644 &pp
->children
[i
].err
,
1646 pp
->children
[i
].data
);
1650 if (!opts
->ungroup
) {
1651 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1652 strbuf_reset(&pp
->children
[i
].err
);
1660 pp
->children
[i
].state
= GIT_CP_WORKING
;
1662 pp
->pfd
[i
].fd
= pp
->children
[i
].process
.err
;
1666 static void pp_buffer_stderr(struct parallel_processes
*pp
,
1667 const struct run_process_parallel_opts
*opts
,
1672 while ((i
= poll(pp
->pfd
, opts
->processes
, output_timeout
) < 0)) {
1675 pp_cleanup(pp
, opts
);
1679 /* Buffer output from all pipes. */
1680 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1681 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1682 pp
->pfd
[i
].revents
& (POLLIN
| POLLHUP
)) {
1683 int n
= strbuf_read_once(&pp
->children
[i
].err
,
1684 pp
->children
[i
].process
.err
, 0);
1686 close(pp
->children
[i
].process
.err
);
1687 pp
->children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1689 if (errno
!= EAGAIN
)
1695 static void pp_output(const struct parallel_processes
*pp
)
1697 size_t i
= pp
->output_owner
;
1699 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1700 pp
->children
[i
].err
.len
) {
1701 strbuf_write(&pp
->children
[i
].err
, stderr
);
1702 strbuf_reset(&pp
->children
[i
].err
);
1706 static int pp_collect_finished(struct parallel_processes
*pp
,
1707 const struct run_process_parallel_opts
*opts
)
1713 while (pp
->nr_processes
> 0) {
1714 for (i
= 0; i
< opts
->processes
; i
++)
1715 if (pp
->children
[i
].state
== GIT_CP_WAIT_CLEANUP
)
1717 if (i
== opts
->processes
)
1720 code
= finish_command(&pp
->children
[i
].process
);
1722 if (opts
->task_finished
)
1723 code
= opts
->task_finished(code
, opts
->ungroup
? NULL
:
1724 &pp
->children
[i
].err
, opts
->data
,
1725 pp
->children
[i
].data
);
1735 pp
->children
[i
].state
= GIT_CP_FREE
;
1738 child_process_init(&pp
->children
[i
].process
);
1740 if (opts
->ungroup
) {
1741 ; /* no strbuf_*() work to do here */
1742 } else if (i
!= pp
->output_owner
) {
1743 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1744 strbuf_reset(&pp
->children
[i
].err
);
1746 const size_t n
= opts
->processes
;
1748 strbuf_write(&pp
->children
[i
].err
, stderr
);
1749 strbuf_reset(&pp
->children
[i
].err
);
1751 /* Output all other finished child processes */
1752 strbuf_write(&pp
->buffered_output
, stderr
);
1753 strbuf_reset(&pp
->buffered_output
);
1756 * Pick next process to output live.
1758 * For now we pick it randomly by doing a round
1759 * robin. Later we may want to pick the one with
1760 * the most output or the longest or shortest
1761 * running process time.
1763 for (i
= 0; i
< n
; i
++)
1764 if (pp
->children
[(pp
->output_owner
+ i
) % n
].state
== GIT_CP_WORKING
)
1766 pp
->output_owner
= (pp
->output_owner
+ i
) % n
;
1772 void run_processes_parallel(const struct run_process_parallel_opts
*opts
)
1775 int output_timeout
= 100;
1777 struct parallel_processes_for_signal pp_sig
;
1778 struct parallel_processes pp
= {
1779 .buffered_output
= STRBUF_INIT
,
1782 const char *tr2_category
= opts
->tr2_category
;
1783 const char *tr2_label
= opts
->tr2_label
;
1784 const int do_trace2
= tr2_category
&& tr2_label
;
1787 trace2_region_enter_printf(tr2_category
, tr2_label
, NULL
,
1788 "max:%d", opts
->processes
);
1790 pp_init(&pp
, opts
, &pp_sig
);
1793 i
< spawn_cap
&& !pp
.shutdown
&&
1794 pp
.nr_processes
< opts
->processes
;
1796 code
= pp_start_one(&pp
, opts
);
1801 kill_children(&pp
, opts
, -code
);
1805 if (!pp
.nr_processes
)
1807 if (opts
->ungroup
) {
1808 for (size_t i
= 0; i
< opts
->processes
; i
++)
1809 pp
.children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1811 pp_buffer_stderr(&pp
, opts
, output_timeout
);
1814 code
= pp_collect_finished(&pp
, opts
);
1818 kill_children(&pp
, opts
,-code
);
1822 pp_cleanup(&pp
, opts
);
1825 trace2_region_leave(tr2_category
, tr2_label
, NULL
);
1828 int run_auto_maintenance(int quiet
)
1831 struct child_process maint
= CHILD_PROCESS_INIT
;
1833 if (!git_config_get_bool("maintenance.auto", &enabled
) &&
1838 maint
.close_object_store
= 1;
1839 strvec_pushl(&maint
.args
, "maintenance", "run", "--auto", NULL
);
1840 strvec_push(&maint
.args
, quiet
? "--quiet" : "--no-quiet");
1842 return run_command(&maint
);
1845 void prepare_other_repo_env(struct strvec
*env
, const char *new_git_dir
)
1847 const char * const *var
;
1849 for (var
= local_repo_env
; *var
; var
++) {
1850 if (strcmp(*var
, CONFIG_DATA_ENVIRONMENT
) &&
1851 strcmp(*var
, CONFIG_COUNT_ENVIRONMENT
))
1852 strvec_push(env
, *var
);
1854 strvec_pushf(env
, "%s=%s", GIT_DIR_ENVIRONMENT
, new_git_dir
);
1857 enum start_bg_result
start_bg_command(struct child_process
*cmd
,
1858 start_bg_wait_cb
*wait_cb
,
1860 unsigned int timeout_sec
)
1862 enum start_bg_result sbgr
= SBGR_ERROR
;
1869 * We do not allow clean-on-exit because the child process
1870 * should persist in the background and possibly/probably
1871 * after this process exits. So we don't want to kill the
1872 * child during our atexit routine.
1874 if (cmd
->clean_on_exit
)
1875 BUG("start_bg_command() does not allow non-zero clean_on_exit");
1877 if (!cmd
->trace2_child_class
)
1878 cmd
->trace2_child_class
= "background";
1880 ret
= start_command(cmd
);
1883 * We assume that if `start_command()` fails, we
1884 * either get a complete `trace2_child_start() /
1885 * trace2_child_exit()` pair or it fails before the
1886 * `trace2_child_start()` is emitted, so we do not
1887 * need to worry about it here.
1889 * We also assume that `start_command()` does not add
1890 * us to the cleanup list. And that it calls
1891 * calls `child_process_clear()`.
1898 time_limit
+= timeout_sec
;
1901 pid_seen
= waitpid(cmd
->pid
, &wait_status
, WNOHANG
);
1905 * The child is currently running. Ask the callback
1906 * if the child is ready to do work or whether we
1907 * should keep waiting for it to boot up.
1909 ret
= (*wait_cb
)(cmd
, cb_data
);
1912 * The child is running and "ready".
1914 trace2_child_ready(cmd
, "ready");
1917 } else if (ret
> 0) {
1919 * The callback said to give it more time to boot up
1920 * (subject to our timeout limit).
1925 if (now
< time_limit
)
1929 * Our timeout has expired. We don't try to
1930 * kill the child, but rather let it continue
1931 * (hopefully) trying to startup.
1933 trace2_child_ready(cmd
, "timeout");
1934 sbgr
= SBGR_TIMEOUT
;
1938 * The cb gave up on this child. It is still running,
1939 * but our cb got an error trying to probe it.
1941 trace2_child_ready(cmd
, "error");
1942 sbgr
= SBGR_CB_ERROR
;
1947 else if (pid_seen
== cmd
->pid
) {
1948 int child_code
= -1;
1951 * The child started, but exited or was terminated
1952 * before becoming "ready".
1954 * We try to match the behavior of `wait_or_whine()`
1955 * WRT the handling of WIFSIGNALED() and WIFEXITED()
1956 * and convert the child's status to a return code for
1957 * tracing purposes and emit the `trace2_child_exit()`
1960 * We do not want the wait_or_whine() error message
1961 * because we will be called by client-side library
1964 if (WIFEXITED(wait_status
))
1965 child_code
= WEXITSTATUS(wait_status
);
1966 else if (WIFSIGNALED(wait_status
))
1967 child_code
= WTERMSIG(wait_status
) + 128;
1968 trace2_child_exit(cmd
, child_code
);
1974 else if (pid_seen
< 0 && errno
== EINTR
)
1977 trace2_child_exit(cmd
, -1);
1981 child_process_clear(cmd
);
1982 invalidate_lstat_cache();