2 #include "run-command.h"
3 #include "environment.h"
8 #include "thread-utils.h"
10 #include "string-list.h"
15 #include "compat/nonblock.h"
17 void child_process_init(struct child_process
*child
)
19 struct child_process blank
= CHILD_PROCESS_INIT
;
20 memcpy(child
, &blank
, sizeof(*child
));
23 void child_process_clear(struct child_process
*child
)
25 strvec_clear(&child
->args
);
26 strvec_clear(&child
->env
);
29 struct child_to_clean
{
31 struct child_process
*process
;
32 struct child_to_clean
*next
;
34 static struct child_to_clean
*children_to_clean
;
35 static int installed_child_cleanup_handler
;
37 static void cleanup_children(int sig
, int in_signal
)
39 struct child_to_clean
*children_to_wait_for
= NULL
;
41 while (children_to_clean
) {
42 struct child_to_clean
*p
= children_to_clean
;
43 children_to_clean
= p
->next
;
45 if (p
->process
&& !in_signal
) {
46 struct child_process
*process
= p
->process
;
47 if (process
->clean_on_exit_handler
) {
49 "trace: run_command: running exit handler for pid %"
50 PRIuMAX
, (uintmax_t)p
->pid
52 process
->clean_on_exit_handler(process
);
58 if (p
->process
&& p
->process
->wait_after_clean
) {
59 p
->next
= children_to_wait_for
;
60 children_to_wait_for
= p
;
67 while (children_to_wait_for
) {
68 struct child_to_clean
*p
= children_to_wait_for
;
69 children_to_wait_for
= p
->next
;
71 while (waitpid(p
->pid
, NULL
, 0) < 0 && errno
== EINTR
)
72 ; /* spin waiting for process exit or error */
79 static void cleanup_children_on_signal(int sig
)
81 cleanup_children(sig
, 1);
86 static void cleanup_children_on_exit(void)
88 cleanup_children(SIGTERM
, 0);
91 static void mark_child_for_cleanup(pid_t pid
, struct child_process
*process
)
93 struct child_to_clean
*p
= xmalloc(sizeof(*p
));
96 p
->next
= children_to_clean
;
97 children_to_clean
= p
;
99 if (!installed_child_cleanup_handler
) {
100 atexit(cleanup_children_on_exit
);
101 sigchain_push_common(cleanup_children_on_signal
);
102 installed_child_cleanup_handler
= 1;
106 static void clear_child_for_cleanup(pid_t pid
)
108 struct child_to_clean
**pp
;
110 for (pp
= &children_to_clean
; *pp
; pp
= &(*pp
)->next
) {
111 struct child_to_clean
*clean_me
= *pp
;
113 if (clean_me
->pid
== pid
) {
114 *pp
= clean_me
->next
;
121 static inline void close_pair(int fd
[2])
127 int is_executable(const char *name
)
131 if (stat(name
, &st
) || /* stat, not lstat */
132 !S_ISREG(st
.st_mode
))
135 #if defined(GIT_WINDOWS_NATIVE)
137 * On Windows there is no executable bit. The file extension
138 * indicates whether it can be run as an executable, and Git
139 * has special-handling to detect scripts and launch them
140 * through the indicated script interpreter. We test for the
141 * file extension first because virus scanners may make
142 * it quite expensive to open many files.
144 if (ends_with(name
, ".exe"))
149 * Now that we know it does not have an executable extension,
150 * peek into the file instead.
154 int fd
= open(name
, O_RDONLY
);
155 st
.st_mode
&= ~S_IXUSR
;
157 n
= read(fd
, buf
, 2);
159 /* look for a she-bang */
160 if (!strcmp(buf
, "#!"))
161 st
.st_mode
|= S_IXUSR
;
166 return st
.st_mode
& S_IXUSR
;
170 * Search $PATH for a command. This emulates the path search that
171 * execvp would perform, without actually executing the command so it
172 * can be used before fork() to prepare to run a command using
173 * execve() or after execvp() to diagnose why it failed.
175 * The caller should ensure that file contains no directory
178 * Returns the path to the command, as found in $PATH or NULL if the
179 * command could not be found. The caller inherits ownership of the memory
180 * used to store the resultant path.
182 * This should not be used on Windows, where the $PATH search rules
183 * are more complicated (e.g., a search for "foo" should find
186 static char *locate_in_PATH(const char *file
)
188 const char *p
= getenv("PATH");
189 struct strbuf buf
= STRBUF_INIT
;
195 const char *end
= strchrnul(p
, ':');
199 /* POSIX specifies an empty entry as the current directory. */
201 strbuf_add(&buf
, p
, end
- p
);
202 strbuf_addch(&buf
, '/');
204 strbuf_addstr(&buf
, file
);
206 if (is_executable(buf
.buf
))
207 return strbuf_detach(&buf
, NULL
);
214 strbuf_release(&buf
);
218 int exists_in_PATH(const char *command
)
220 char *r
= locate_in_PATH(command
);
221 int found
= r
!= NULL
;
226 int sane_execvp(const char *file
, char * const argv
[])
228 #ifndef GIT_WINDOWS_NATIVE
230 * execvp() doesn't return, so we all we can do is tell trace2
231 * what we are about to do and let it leave a hint in the log
232 * (unless of course the execvp() fails).
234 * we skip this for Windows because the compat layer already
235 * has to emulate the execvp() call anyway.
237 int exec_id
= trace2_exec(file
, (const char **)argv
);
240 if (!execvp(file
, argv
))
241 return 0; /* cannot happen ;-) */
243 #ifndef GIT_WINDOWS_NATIVE
246 trace2_exec_result(exec_id
, ec
);
252 * When a command can't be found because one of the directories
253 * listed in $PATH is unsearchable, execvp reports EACCES, but
254 * careful usability testing (read: analysis of occasional bug
255 * reports) reveals that "No such file or directory" is more
258 * We avoid commands with "/", because execvp will not do $PATH
259 * lookups in that case.
261 * The reassignment of EACCES to errno looks like a no-op below,
262 * but we need to protect against exists_in_PATH overwriting errno.
264 if (errno
== EACCES
&& !strchr(file
, '/'))
265 errno
= exists_in_PATH(file
) ? EACCES
: ENOENT
;
266 else if (errno
== ENOTDIR
&& !strchr(file
, '/'))
271 static const char **prepare_shell_cmd(struct strvec
*out
, const char **argv
)
274 BUG("shell command is empty");
276 if (strcspn(argv
[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv
[0])) {
277 #ifndef GIT_WINDOWS_NATIVE
278 strvec_push(out
, SHELL_PATH
);
280 strvec_push(out
, "sh");
282 strvec_push(out
, "-c");
285 * If we have no extra arguments, we do not even need to
286 * bother with the "$@" magic.
289 strvec_push(out
, argv
[0]);
291 strvec_pushf(out
, "%s \"$@\"", argv
[0]);
294 strvec_pushv(out
, argv
);
298 #ifndef GIT_WINDOWS_NATIVE
299 static int child_notifier
= -1;
305 CHILD_ERR_SIGPROCMASK
,
312 enum child_errcode err
;
313 int syserr
; /* errno */
316 static void child_die(enum child_errcode err
)
318 struct child_err buf
;
323 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
324 xwrite(child_notifier
, &buf
, sizeof(buf
));
328 static void child_dup2(int fd
, int to
)
330 if (dup2(fd
, to
) < 0)
331 child_die(CHILD_ERR_DUP2
);
334 static void child_close(int fd
)
337 child_die(CHILD_ERR_CLOSE
);
340 static void child_close_pair(int fd
[2])
346 static void child_error_fn(const char *err UNUSED
, va_list params UNUSED
)
348 const char msg
[] = "error() should not be called in child\n";
349 xwrite(2, msg
, sizeof(msg
) - 1);
352 static void child_warn_fn(const char *err UNUSED
, va_list params UNUSED
)
354 const char msg
[] = "warn() should not be called in child\n";
355 xwrite(2, msg
, sizeof(msg
) - 1);
358 static void NORETURN
child_die_fn(const char *err UNUSED
, va_list params UNUSED
)
360 const char msg
[] = "die() should not be called in child\n";
361 xwrite(2, msg
, sizeof(msg
) - 1);
365 /* this runs in the parent process */
366 static void child_err_spew(struct child_process
*cmd
, struct child_err
*cerr
)
368 static void (*old_errfn
)(const char *err
, va_list params
);
369 report_fn die_message_routine
= get_die_message_routine();
371 old_errfn
= get_error_routine();
372 set_error_routine(die_message_routine
);
373 errno
= cerr
->syserr
;
376 case CHILD_ERR_CHDIR
:
377 error_errno("exec '%s': cd to '%s' failed",
378 cmd
->args
.v
[0], cmd
->dir
);
381 error_errno("dup2() in child failed");
383 case CHILD_ERR_CLOSE
:
384 error_errno("close() in child failed");
386 case CHILD_ERR_SIGPROCMASK
:
387 error_errno("sigprocmask failed restoring signals");
389 case CHILD_ERR_ENOENT
:
390 error_errno("cannot run %s", cmd
->args
.v
[0]);
392 case CHILD_ERR_SILENT
:
394 case CHILD_ERR_ERRNO
:
395 error_errno("cannot exec '%s'", cmd
->args
.v
[0]);
398 set_error_routine(old_errfn
);
401 static int prepare_cmd(struct strvec
*out
, const struct child_process
*cmd
)
404 BUG("command is empty");
407 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
408 * attempt to interpret the command with 'sh'.
410 strvec_push(out
, SHELL_PATH
);
413 prepare_git_cmd(out
, cmd
->args
.v
);
414 } else if (cmd
->use_shell
) {
415 prepare_shell_cmd(out
, cmd
->args
.v
);
417 strvec_pushv(out
, cmd
->args
.v
);
421 * If there are no dir separator characters in the command then perform
422 * a path lookup and use the resolved path as the command to exec. If
423 * there are dir separator characters, we have exec attempt to invoke
424 * the command directly.
426 if (!has_dir_sep(out
->v
[1])) {
427 char *program
= locate_in_PATH(out
->v
[1]);
429 free((char *)out
->v
[1]);
441 static char **prep_childenv(const char *const *deltaenv
)
443 extern char **environ
;
445 struct string_list env
= STRING_LIST_INIT_DUP
;
446 struct strbuf key
= STRBUF_INIT
;
447 const char *const *p
;
450 /* Construct a sorted string list consisting of the current environ */
451 for (p
= (const char *const *) environ
; p
&& *p
; p
++) {
452 const char *equals
= strchr(*p
, '=');
456 strbuf_add(&key
, *p
, equals
- *p
);
457 string_list_append(&env
, key
.buf
)->util
= (void *) *p
;
459 string_list_append(&env
, *p
)->util
= (void *) *p
;
462 string_list_sort(&env
);
464 /* Merge in 'deltaenv' with the current environ */
465 for (p
= deltaenv
; p
&& *p
; p
++) {
466 const char *equals
= strchr(*p
, '=');
469 /* ('key=value'), insert or replace entry */
471 strbuf_add(&key
, *p
, equals
- *p
);
472 string_list_insert(&env
, key
.buf
)->util
= (void *) *p
;
474 /* otherwise ('key') remove existing entry */
475 string_list_remove(&env
, *p
, 0);
479 /* Create an array of 'char *' to be used as the childenv */
480 ALLOC_ARRAY(childenv
, env
.nr
+ 1);
481 for (i
= 0; i
< env
.nr
; i
++)
482 childenv
[i
] = env
.items
[i
].util
;
483 childenv
[env
.nr
] = NULL
;
485 string_list_clear(&env
, 0);
486 strbuf_release(&key
);
490 struct atfork_state
{
497 #define CHECK_BUG(err, msg) \
501 BUG("%s: %s", msg, strerror(e)); \
504 static void atfork_prepare(struct atfork_state
*as
)
508 if (sigfillset(&all
))
509 die_errno("sigfillset");
511 if (sigprocmask(SIG_SETMASK
, &all
, &as
->old
))
512 die_errno("sigprocmask");
514 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &all
, &as
->old
),
515 "blocking all signals");
516 CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &as
->cs
),
517 "disabling cancellation");
521 static void atfork_parent(struct atfork_state
*as
)
524 if (sigprocmask(SIG_SETMASK
, &as
->old
, NULL
))
525 die_errno("sigprocmask");
527 CHECK_BUG(pthread_setcancelstate(as
->cs
, NULL
),
528 "re-enabling cancellation");
529 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &as
->old
, NULL
),
530 "restoring signal mask");
533 #endif /* GIT_WINDOWS_NATIVE */
535 static inline void set_cloexec(int fd
)
537 int flags
= fcntl(fd
, F_GETFD
);
539 fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
542 static int wait_or_whine(pid_t pid
, const char *argv0
, int in_signal
)
544 int status
, code
= -1;
546 int failed_errno
= 0;
548 while ((waiting
= waitpid(pid
, &status
, 0)) < 0 && errno
== EINTR
)
552 failed_errno
= errno
;
554 error_errno("waitpid for %s failed", argv0
);
555 } else if (waiting
!= pid
) {
557 error("waitpid is confused (%s)", argv0
);
558 } else if (WIFSIGNALED(status
)) {
559 code
= WTERMSIG(status
);
560 if (!in_signal
&& code
!= SIGINT
&& code
!= SIGQUIT
&& code
!= SIGPIPE
)
561 error("%s died of signal %d", argv0
, code
);
563 * This return value is chosen so that code & 0xff
564 * mimics the exit code that a POSIX shell would report for
565 * a program that died from this signal.
568 } else if (WIFEXITED(status
)) {
569 code
= WEXITSTATUS(status
);
572 error("waitpid is confused (%s)", argv0
);
576 clear_child_for_cleanup(pid
);
578 errno
= failed_errno
;
582 static void trace_add_env(struct strbuf
*dst
, const char *const *deltaenv
)
584 struct string_list envs
= STRING_LIST_INIT_DUP
;
585 const char *const *e
;
587 int printed_unset
= 0;
589 /* Last one wins, see run-command.c:prep_childenv() for context */
590 for (e
= deltaenv
; e
&& *e
; e
++) {
591 struct strbuf key
= STRBUF_INIT
;
592 char *equals
= strchr(*e
, '=');
595 strbuf_add(&key
, *e
, equals
- *e
);
596 string_list_insert(&envs
, key
.buf
)->util
= equals
+ 1;
598 string_list_insert(&envs
, *e
)->util
= NULL
;
600 strbuf_release(&key
);
603 /* "unset X Y...;" */
604 for (i
= 0; i
< envs
.nr
; i
++) {
605 const char *var
= envs
.items
[i
].string
;
606 const char *val
= envs
.items
[i
].util
;
608 if (val
|| !getenv(var
))
611 if (!printed_unset
) {
612 strbuf_addstr(dst
, " unset");
615 strbuf_addf(dst
, " %s", var
);
618 strbuf_addch(dst
, ';');
620 /* ... followed by "A=B C=D ..." */
621 for (i
= 0; i
< envs
.nr
; i
++) {
622 const char *var
= envs
.items
[i
].string
;
623 const char *val
= envs
.items
[i
].util
;
629 oldval
= getenv(var
);
630 if (oldval
&& !strcmp(val
, oldval
))
633 strbuf_addf(dst
, " %s=", var
);
634 sq_quote_buf_pretty(dst
, val
);
636 string_list_clear(&envs
, 0);
639 static void trace_run_command(const struct child_process
*cp
)
641 struct strbuf buf
= STRBUF_INIT
;
643 if (!trace_want(&trace_default_key
))
646 strbuf_addstr(&buf
, "trace: run_command:");
648 strbuf_addstr(&buf
, " cd ");
649 sq_quote_buf_pretty(&buf
, cp
->dir
);
650 strbuf_addch(&buf
, ';');
652 trace_add_env(&buf
, cp
->env
.v
);
654 strbuf_addstr(&buf
, " git");
655 sq_quote_argv_pretty(&buf
, cp
->args
.v
);
657 trace_printf("%s", buf
.buf
);
658 strbuf_release(&buf
);
661 int start_command(struct child_process
*cmd
)
663 int need_in
, need_out
, need_err
;
664 int fdin
[2], fdout
[2], fderr
[2];
669 * In case of errors we must keep the promise to close FDs
670 * that have been passed in via ->in and ->out.
673 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
675 if (pipe(fdin
) < 0) {
676 failed_errno
= errno
;
679 str
= "standard input";
685 need_out
= !cmd
->no_stdout
686 && !cmd
->stdout_to_stderr
689 if (pipe(fdout
) < 0) {
690 failed_errno
= errno
;
695 str
= "standard output";
701 need_err
= !cmd
->no_stderr
&& cmd
->err
< 0;
703 if (pipe(fderr
) < 0) {
704 failed_errno
= errno
;
713 str
= "standard error";
715 error("cannot create %s pipe for %s: %s",
716 str
, cmd
->args
.v
[0], strerror(failed_errno
));
717 child_process_clear(cmd
);
718 errno
= failed_errno
;
724 trace2_child_start(cmd
);
725 trace_run_command(cmd
);
729 if (cmd
->close_object_store
)
730 close_object_store(the_repository
->objects
);
732 #ifndef GIT_WINDOWS_NATIVE
737 struct strvec argv
= STRVEC_INIT
;
738 struct child_err cerr
;
739 struct atfork_state as
;
741 if (prepare_cmd(&argv
, cmd
) < 0) {
742 failed_errno
= errno
;
744 if (!cmd
->silent_exec_failure
)
745 error_errno("cannot run %s", cmd
->args
.v
[0]);
749 if (pipe(notify_pipe
))
750 notify_pipe
[0] = notify_pipe
[1] = -1;
752 if (cmd
->no_stdin
|| cmd
->no_stdout
|| cmd
->no_stderr
) {
753 null_fd
= xopen("/dev/null", O_RDWR
| O_CLOEXEC
);
754 set_cloexec(null_fd
);
757 childenv
= prep_childenv(cmd
->env
.v
);
761 * NOTE: In order to prevent deadlocking when using threads special
762 * care should be taken with the function calls made in between the
763 * fork() and exec() calls. No calls should be made to functions which
764 * require acquiring a lock (e.g. malloc) as the lock could have been
765 * held by another thread at the time of forking, causing the lock to
766 * never be released in the child process. This means only
767 * Async-Signal-Safe functions are permitted in the child.
770 failed_errno
= errno
;
774 * Ensure the default die/error/warn routines do not get
775 * called, they can take stdio locks and malloc.
777 set_die_routine(child_die_fn
);
778 set_error_routine(child_error_fn
);
779 set_warn_routine(child_warn_fn
);
781 close(notify_pipe
[0]);
782 set_cloexec(notify_pipe
[1]);
783 child_notifier
= notify_pipe
[1];
786 child_dup2(null_fd
, 0);
788 child_dup2(fdin
[0], 0);
789 child_close_pair(fdin
);
790 } else if (cmd
->in
) {
791 child_dup2(cmd
->in
, 0);
792 child_close(cmd
->in
);
796 child_dup2(null_fd
, 2);
798 child_dup2(fderr
[1], 2);
799 child_close_pair(fderr
);
800 } else if (cmd
->err
> 1) {
801 child_dup2(cmd
->err
, 2);
802 child_close(cmd
->err
);
806 child_dup2(null_fd
, 1);
807 else if (cmd
->stdout_to_stderr
)
810 child_dup2(fdout
[1], 1);
811 child_close_pair(fdout
);
812 } else if (cmd
->out
> 1) {
813 child_dup2(cmd
->out
, 1);
814 child_close(cmd
->out
);
817 if (cmd
->dir
&& chdir(cmd
->dir
))
818 child_die(CHILD_ERR_CHDIR
);
821 * restore default signal handlers here, in case
822 * we catch a signal right before execve below
824 for (sig
= 1; sig
< NSIG
; sig
++) {
825 /* ignored signals get reset to SIG_DFL on execve */
826 if (signal(sig
, SIG_DFL
) == SIG_IGN
)
827 signal(sig
, SIG_IGN
);
830 if (sigprocmask(SIG_SETMASK
, &as
.old
, NULL
) != 0)
831 child_die(CHILD_ERR_SIGPROCMASK
);
834 * Attempt to exec using the command and arguments starting at
835 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
836 * be used in the event exec failed with ENOEXEC at which point
837 * we will try to interpret the command using 'sh'.
839 execve(argv
.v
[1], (char *const *) argv
.v
+ 1,
840 (char *const *) childenv
);
841 if (errno
== ENOEXEC
)
842 execve(argv
.v
[0], (char *const *) argv
.v
,
843 (char *const *) childenv
);
845 if (errno
== ENOENT
) {
846 if (cmd
->silent_exec_failure
)
847 child_die(CHILD_ERR_SILENT
);
848 child_die(CHILD_ERR_ENOENT
);
850 child_die(CHILD_ERR_ERRNO
);
855 error_errno("cannot fork() for %s", cmd
->args
.v
[0]);
856 else if (cmd
->clean_on_exit
)
857 mark_child_for_cleanup(cmd
->pid
, cmd
);
860 * Wait for child's exec. If the exec succeeds (or if fork()
861 * failed), EOF is seen immediately by the parent. Otherwise, the
862 * child process sends a child_err struct.
863 * Note that use of this infrastructure is completely advisory,
864 * therefore, we keep error checks minimal.
866 close(notify_pipe
[1]);
867 if (xread(notify_pipe
[0], &cerr
, sizeof(cerr
)) == sizeof(cerr
)) {
869 * At this point we know that fork() succeeded, but exec()
870 * failed. Errors have been reported to our stderr.
872 wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
873 child_err_spew(cmd
, &cerr
);
874 failed_errno
= errno
;
877 close(notify_pipe
[0]);
888 int fhin
= 0, fhout
= 1, fherr
= 2;
889 const char **sargv
= cmd
->args
.v
;
890 struct strvec nargv
= STRVEC_INIT
;
893 fhin
= open("/dev/null", O_RDWR
);
900 fherr
= open("/dev/null", O_RDWR
);
902 fherr
= dup(fderr
[1]);
903 else if (cmd
->err
> 2)
904 fherr
= dup(cmd
->err
);
907 fhout
= open("/dev/null", O_RDWR
);
908 else if (cmd
->stdout_to_stderr
)
911 fhout
= dup(fdout
[1]);
912 else if (cmd
->out
> 1)
913 fhout
= dup(cmd
->out
);
916 cmd
->args
.v
= prepare_git_cmd(&nargv
, sargv
);
917 else if (cmd
->use_shell
)
918 cmd
->args
.v
= prepare_shell_cmd(&nargv
, sargv
);
920 cmd
->pid
= mingw_spawnvpe(cmd
->args
.v
[0], cmd
->args
.v
,
922 cmd
->dir
, fhin
, fhout
, fherr
);
923 failed_errno
= errno
;
924 if (cmd
->pid
< 0 && (!cmd
->silent_exec_failure
|| errno
!= ENOENT
))
925 error_errno("cannot spawn %s", cmd
->args
.v
[0]);
926 if (cmd
->clean_on_exit
&& cmd
->pid
>= 0)
927 mark_child_for_cleanup(cmd
->pid
, cmd
);
929 strvec_clear(&nargv
);
941 trace2_child_exit(cmd
, -1);
955 child_process_clear(cmd
);
956 errno
= failed_errno
;
978 int finish_command(struct child_process
*cmd
)
980 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
981 trace2_child_exit(cmd
, ret
);
982 child_process_clear(cmd
);
983 invalidate_lstat_cache();
987 int finish_command_in_signal(struct child_process
*cmd
)
989 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 1);
991 trace2_child_exit(cmd
, ret
);
996 int run_command(struct child_process
*cmd
)
1000 if (cmd
->out
< 0 || cmd
->err
< 0)
1001 BUG("run_command with a pipe can cause deadlock");
1003 code
= start_command(cmd
);
1006 return finish_command(cmd
);
1010 static pthread_t main_thread
;
1011 static int main_thread_set
;
1012 static pthread_key_t async_key
;
1013 static pthread_key_t async_die_counter
;
1015 static void *run_thread(void *data
)
1017 struct async
*async
= data
;
1020 if (async
->isolate_sigpipe
) {
1023 sigaddset(&mask
, SIGPIPE
);
1024 if (pthread_sigmask(SIG_BLOCK
, &mask
, NULL
)) {
1025 ret
= error("unable to block SIGPIPE in async thread");
1030 pthread_setspecific(async_key
, async
);
1031 ret
= async
->proc(async
->proc_in
, async
->proc_out
, async
->data
);
1035 static NORETURN
void die_async(const char *err
, va_list params
)
1037 report_fn die_message_fn
= get_die_message_routine();
1039 die_message_fn(err
, params
);
1042 struct async
*async
= pthread_getspecific(async_key
);
1043 if (async
->proc_in
>= 0)
1044 close(async
->proc_in
);
1045 if (async
->proc_out
>= 0)
1046 close(async
->proc_out
);
1047 pthread_exit((void *)128);
1053 static int async_die_is_recursing(void)
1055 void *ret
= pthread_getspecific(async_die_counter
);
1056 pthread_setspecific(async_die_counter
, &async_die_counter
); /* set to any non-NULL valid pointer */
1062 if (!main_thread_set
)
1063 return 0; /* no asyncs started yet */
1064 return !pthread_equal(main_thread
, pthread_self());
1067 static void NORETURN
async_exit(int code
)
1069 pthread_exit((void *)(intptr_t)code
);
1075 void (**handlers
)(void);
1080 static int git_atexit_installed
;
1082 static void git_atexit_dispatch(void)
1086 for (i
=git_atexit_hdlrs
.nr
; i
; i
--)
1087 git_atexit_hdlrs
.handlers
[i
-1]();
1090 static void git_atexit_clear(void)
1092 free(git_atexit_hdlrs
.handlers
);
1093 memset(&git_atexit_hdlrs
, 0, sizeof(git_atexit_hdlrs
));
1094 git_atexit_installed
= 0;
1098 int git_atexit(void (*handler
)(void))
1100 ALLOC_GROW(git_atexit_hdlrs
.handlers
, git_atexit_hdlrs
.nr
+ 1, git_atexit_hdlrs
.alloc
);
1101 git_atexit_hdlrs
.handlers
[git_atexit_hdlrs
.nr
++] = handler
;
1102 if (!git_atexit_installed
) {
1103 if (atexit(&git_atexit_dispatch
))
1105 git_atexit_installed
= 1;
1109 #define atexit git_atexit
1111 static int process_is_async
;
1114 return process_is_async
;
1117 static void NORETURN
async_exit(int code
)
1124 void check_pipe(int err
)
1130 signal(SIGPIPE
, SIG_DFL
);
1132 /* Should never happen, but just in case... */
1137 int start_async(struct async
*async
)
1139 int need_in
, need_out
;
1140 int fdin
[2], fdout
[2];
1141 int proc_in
, proc_out
;
1143 need_in
= async
->in
< 0;
1145 if (pipe(fdin
) < 0) {
1148 return error_errno("cannot create pipe");
1150 async
->in
= fdin
[1];
1153 need_out
= async
->out
< 0;
1155 if (pipe(fdout
) < 0) {
1160 return error_errno("cannot create pipe");
1162 async
->out
= fdout
[0];
1168 proc_in
= async
->in
;
1173 proc_out
= fdout
[1];
1174 else if (async
->out
)
1175 proc_out
= async
->out
;
1180 /* Flush stdio before fork() to avoid cloning buffers */
1183 async
->pid
= fork();
1184 if (async
->pid
< 0) {
1185 error_errno("fork (async) failed");
1194 process_is_async
= 1;
1195 exit(!!async
->proc(proc_in
, proc_out
, async
->data
));
1198 mark_child_for_cleanup(async
->pid
, NULL
);
1207 else if (async
->out
)
1210 if (!main_thread_set
) {
1212 * We assume that the first time that start_async is called
1213 * it is from the main thread.
1215 main_thread_set
= 1;
1216 main_thread
= pthread_self();
1217 pthread_key_create(&async_key
, NULL
);
1218 pthread_key_create(&async_die_counter
, NULL
);
1219 set_die_routine(die_async
);
1220 set_die_is_recursing_routine(async_die_is_recursing
);
1224 set_cloexec(proc_in
);
1226 set_cloexec(proc_out
);
1227 async
->proc_in
= proc_in
;
1228 async
->proc_out
= proc_out
;
1230 int err
= pthread_create(&async
->tid
, NULL
, run_thread
, async
);
1232 error(_("cannot create async thread: %s"), strerror(err
));
1247 else if (async
->out
)
1252 int finish_async(struct async
*async
)
1255 int ret
= wait_or_whine(async
->pid
, "child process", 0);
1257 invalidate_lstat_cache();
1261 void *ret
= (void *)(intptr_t)(-1);
1263 if (pthread_join(async
->tid
, &ret
))
1264 error("pthread_join failed");
1265 invalidate_lstat_cache();
1266 return (int)(intptr_t)ret
;
1271 int async_with_fork(void)
1281 /* initialized by caller */
1283 int type
; /* POLLOUT or POLLIN */
1295 /* returned by pump_io */
1296 int error
; /* 0 for success, otherwise errno */
1302 static int pump_io_round(struct io_pump
*slots
, int nr
, struct pollfd
*pfd
)
1307 for (i
= 0; i
< nr
; i
++) {
1308 struct io_pump
*io
= &slots
[i
];
1311 pfd
[pollsize
].fd
= io
->fd
;
1312 pfd
[pollsize
].events
= io
->type
;
1313 io
->pfd
= &pfd
[pollsize
++];
1319 if (poll(pfd
, pollsize
, -1) < 0) {
1322 die_errno("poll failed");
1325 for (i
= 0; i
< nr
; i
++) {
1326 struct io_pump
*io
= &slots
[i
];
1331 if (!(io
->pfd
->revents
& (POLLOUT
|POLLIN
|POLLHUP
|POLLERR
|POLLNVAL
)))
1334 if (io
->type
== POLLOUT
) {
1338 * Don't use xwrite() here. It loops forever on EAGAIN,
1339 * and we're in our own poll() loop here.
1341 * Note that we lose xwrite()'s handling of MAX_IO_SIZE
1342 * and EINTR, so we have to implement those ourselves.
1344 len
= write(io
->fd
, io
->u
.out
.buf
,
1345 io
->u
.out
.len
<= MAX_IO_SIZE
?
1346 io
->u
.out
.len
: MAX_IO_SIZE
);
1348 if (errno
!= EINTR
&& errno
!= EAGAIN
&&
1355 io
->u
.out
.buf
+= len
;
1356 io
->u
.out
.len
-= len
;
1357 if (!io
->u
.out
.len
) {
1364 if (io
->type
== POLLIN
) {
1365 ssize_t len
= strbuf_read_once(io
->u
.in
.buf
,
1366 io
->fd
, io
->u
.in
.hint
);
1379 static int pump_io(struct io_pump
*slots
, int nr
)
1384 for (i
= 0; i
< nr
; i
++)
1387 ALLOC_ARRAY(pfd
, nr
);
1388 while (pump_io_round(slots
, nr
, pfd
))
1392 /* There may be multiple errno values, so just pick the first. */
1393 for (i
= 0; i
< nr
; i
++) {
1394 if (slots
[i
].error
) {
1395 errno
= slots
[i
].error
;
1403 int pipe_command(struct child_process
*cmd
,
1404 const char *in
, size_t in_len
,
1405 struct strbuf
*out
, size_t out_hint
,
1406 struct strbuf
*err
, size_t err_hint
)
1408 struct io_pump io
[3];
1418 if (start_command(cmd
) < 0)
1422 if (enable_pipe_nonblock(cmd
->in
) < 0) {
1423 error_errno("unable to make pipe non-blocking");
1431 io
[nr
].fd
= cmd
->in
;
1432 io
[nr
].type
= POLLOUT
;
1433 io
[nr
].u
.out
.buf
= in
;
1434 io
[nr
].u
.out
.len
= in_len
;
1438 io
[nr
].fd
= cmd
->out
;
1439 io
[nr
].type
= POLLIN
;
1440 io
[nr
].u
.in
.buf
= out
;
1441 io
[nr
].u
.in
.hint
= out_hint
;
1445 io
[nr
].fd
= cmd
->err
;
1446 io
[nr
].type
= POLLIN
;
1447 io
[nr
].u
.in
.buf
= err
;
1448 io
[nr
].u
.in
.hint
= err_hint
;
1452 if (pump_io(io
, nr
) < 0) {
1453 finish_command(cmd
); /* throw away exit code */
1457 return finish_command(cmd
);
1463 GIT_CP_WAIT_CLEANUP
,
1466 struct parallel_processes
{
1467 size_t nr_processes
;
1470 enum child_state state
;
1471 struct child_process process
;
1476 * The struct pollfd is logically part of *children,
1477 * but the system call expects it as its own array.
1481 unsigned shutdown
: 1;
1483 size_t output_owner
;
1484 struct strbuf buffered_output
; /* of finished children */
1487 struct parallel_processes_for_signal
{
1488 const struct run_process_parallel_opts
*opts
;
1489 const struct parallel_processes
*pp
;
1492 static void kill_children(const struct parallel_processes
*pp
,
1493 const struct run_process_parallel_opts
*opts
,
1496 for (size_t i
= 0; i
< opts
->processes
; i
++)
1497 if (pp
->children
[i
].state
== GIT_CP_WORKING
)
1498 kill(pp
->children
[i
].process
.pid
, signo
);
1501 static void kill_children_signal(const struct parallel_processes_for_signal
*pp_sig
,
1504 kill_children(pp_sig
->pp
, pp_sig
->opts
, signo
);
1507 static struct parallel_processes_for_signal
*pp_for_signal
;
1509 static void handle_children_on_signal(int signo
)
1511 kill_children_signal(pp_for_signal
, signo
);
1512 sigchain_pop(signo
);
1516 static void pp_init(struct parallel_processes
*pp
,
1517 const struct run_process_parallel_opts
*opts
,
1518 struct parallel_processes_for_signal
*pp_sig
)
1520 const size_t n
= opts
->processes
;
1523 BUG("you must provide a non-zero number of processes!");
1525 trace_printf("run_processes_parallel: preparing to run up to %"PRIuMAX
" tasks",
1528 if (!opts
->get_next_task
)
1529 BUG("you need to specify a get_next_task function");
1531 CALLOC_ARRAY(pp
->children
, n
);
1533 CALLOC_ARRAY(pp
->pfd
, n
);
1535 for (size_t i
= 0; i
< n
; i
++) {
1536 strbuf_init(&pp
->children
[i
].err
, 0);
1537 child_process_init(&pp
->children
[i
].process
);
1539 pp
->pfd
[i
].events
= POLLIN
| POLLHUP
;
1545 pp_sig
->opts
= opts
;
1546 pp_for_signal
= pp_sig
;
1547 sigchain_push_common(handle_children_on_signal
);
1550 static void pp_cleanup(struct parallel_processes
*pp
,
1551 const struct run_process_parallel_opts
*opts
)
1553 trace_printf("run_processes_parallel: done");
1554 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1555 strbuf_release(&pp
->children
[i
].err
);
1556 child_process_clear(&pp
->children
[i
].process
);
1563 * When get_next_task added messages to the buffer in its last
1564 * iteration, the buffered output is non empty.
1566 strbuf_write(&pp
->buffered_output
, stderr
);
1567 strbuf_release(&pp
->buffered_output
);
1569 sigchain_pop_common();
1573 * 0 if a new task was started.
1574 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1575 * problem with starting a new command)
1576 * <0 no new job was started, user wishes to shutdown early. Use negative code
1577 * to signal the children.
1579 static int pp_start_one(struct parallel_processes
*pp
,
1580 const struct run_process_parallel_opts
*opts
)
1585 for (i
= 0; i
< opts
->processes
; i
++)
1586 if (pp
->children
[i
].state
== GIT_CP_FREE
)
1588 if (i
== opts
->processes
)
1589 BUG("bookkeeping is hard");
1592 * By default, do not inherit stdin from the parent process - otherwise,
1593 * all children would share stdin! Users may overwrite this to provide
1594 * something to the child's stdin by having their 'get_next_task'
1595 * callback assign 0 to .no_stdin and an appropriate integer to .in.
1597 pp
->children
[i
].process
.no_stdin
= 1;
1599 code
= opts
->get_next_task(&pp
->children
[i
].process
,
1600 opts
->ungroup
? NULL
: &pp
->children
[i
].err
,
1602 &pp
->children
[i
].data
);
1604 if (!opts
->ungroup
) {
1605 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1606 strbuf_reset(&pp
->children
[i
].err
);
1610 if (!opts
->ungroup
) {
1611 pp
->children
[i
].process
.err
= -1;
1612 pp
->children
[i
].process
.stdout_to_stderr
= 1;
1615 if (start_command(&pp
->children
[i
].process
)) {
1616 if (opts
->start_failure
)
1617 code
= opts
->start_failure(opts
->ungroup
? NULL
:
1618 &pp
->children
[i
].err
,
1620 pp
->children
[i
].data
);
1624 if (!opts
->ungroup
) {
1625 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1626 strbuf_reset(&pp
->children
[i
].err
);
1634 pp
->children
[i
].state
= GIT_CP_WORKING
;
1636 pp
->pfd
[i
].fd
= pp
->children
[i
].process
.err
;
1640 static void pp_buffer_stderr(struct parallel_processes
*pp
,
1641 const struct run_process_parallel_opts
*opts
,
1644 while (poll(pp
->pfd
, opts
->processes
, output_timeout
) < 0) {
1647 pp_cleanup(pp
, opts
);
1651 /* Buffer output from all pipes. */
1652 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1653 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1654 pp
->pfd
[i
].revents
& (POLLIN
| POLLHUP
)) {
1655 int n
= strbuf_read_once(&pp
->children
[i
].err
,
1656 pp
->children
[i
].process
.err
, 0);
1658 close(pp
->children
[i
].process
.err
);
1659 pp
->children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1661 if (errno
!= EAGAIN
)
1667 static void pp_output(const struct parallel_processes
*pp
)
1669 size_t i
= pp
->output_owner
;
1671 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1672 pp
->children
[i
].err
.len
) {
1673 strbuf_write(&pp
->children
[i
].err
, stderr
);
1674 strbuf_reset(&pp
->children
[i
].err
);
1678 static int pp_collect_finished(struct parallel_processes
*pp
,
1679 const struct run_process_parallel_opts
*opts
)
1685 while (pp
->nr_processes
> 0) {
1686 for (i
= 0; i
< opts
->processes
; i
++)
1687 if (pp
->children
[i
].state
== GIT_CP_WAIT_CLEANUP
)
1689 if (i
== opts
->processes
)
1692 code
= finish_command(&pp
->children
[i
].process
);
1694 if (opts
->task_finished
)
1695 code
= opts
->task_finished(code
, opts
->ungroup
? NULL
:
1696 &pp
->children
[i
].err
, opts
->data
,
1697 pp
->children
[i
].data
);
1707 pp
->children
[i
].state
= GIT_CP_FREE
;
1710 child_process_init(&pp
->children
[i
].process
);
1712 if (opts
->ungroup
) {
1713 ; /* no strbuf_*() work to do here */
1714 } else if (i
!= pp
->output_owner
) {
1715 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1716 strbuf_reset(&pp
->children
[i
].err
);
1718 const size_t n
= opts
->processes
;
1720 strbuf_write(&pp
->children
[i
].err
, stderr
);
1721 strbuf_reset(&pp
->children
[i
].err
);
1723 /* Output all other finished child processes */
1724 strbuf_write(&pp
->buffered_output
, stderr
);
1725 strbuf_reset(&pp
->buffered_output
);
1728 * Pick next process to output live.
1730 * For now we pick it randomly by doing a round
1731 * robin. Later we may want to pick the one with
1732 * the most output or the longest or shortest
1733 * running process time.
1735 for (i
= 0; i
< n
; i
++)
1736 if (pp
->children
[(pp
->output_owner
+ i
) % n
].state
== GIT_CP_WORKING
)
1738 pp
->output_owner
= (pp
->output_owner
+ i
) % n
;
1744 void run_processes_parallel(const struct run_process_parallel_opts
*opts
)
1747 int output_timeout
= 100;
1749 struct parallel_processes_for_signal pp_sig
;
1750 struct parallel_processes pp
= {
1751 .buffered_output
= STRBUF_INIT
,
1754 const char *tr2_category
= opts
->tr2_category
;
1755 const char *tr2_label
= opts
->tr2_label
;
1756 const int do_trace2
= tr2_category
&& tr2_label
;
1759 trace2_region_enter_printf(tr2_category
, tr2_label
, NULL
,
1760 "max:%d", opts
->processes
);
1762 pp_init(&pp
, opts
, &pp_sig
);
1765 i
< spawn_cap
&& !pp
.shutdown
&&
1766 pp
.nr_processes
< opts
->processes
;
1768 code
= pp_start_one(&pp
, opts
);
1773 kill_children(&pp
, opts
, -code
);
1777 if (!pp
.nr_processes
)
1779 if (opts
->ungroup
) {
1780 for (size_t i
= 0; i
< opts
->processes
; i
++)
1781 pp
.children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1783 pp_buffer_stderr(&pp
, opts
, output_timeout
);
1786 code
= pp_collect_finished(&pp
, opts
);
1790 kill_children(&pp
, opts
,-code
);
1794 pp_cleanup(&pp
, opts
);
1797 trace2_region_leave(tr2_category
, tr2_label
, NULL
);
1800 int run_auto_maintenance(int quiet
)
1803 struct child_process maint
= CHILD_PROCESS_INIT
;
1805 if (!git_config_get_bool("maintenance.auto", &enabled
) &&
1810 maint
.close_object_store
= 1;
1811 strvec_pushl(&maint
.args
, "maintenance", "run", "--auto", NULL
);
1812 strvec_push(&maint
.args
, quiet
? "--quiet" : "--no-quiet");
1814 return run_command(&maint
);
1817 void prepare_other_repo_env(struct strvec
*env
, const char *new_git_dir
)
1819 const char * const *var
;
1821 for (var
= local_repo_env
; *var
; var
++) {
1822 if (strcmp(*var
, CONFIG_DATA_ENVIRONMENT
) &&
1823 strcmp(*var
, CONFIG_COUNT_ENVIRONMENT
))
1824 strvec_push(env
, *var
);
1826 strvec_pushf(env
, "%s=%s", GIT_DIR_ENVIRONMENT
, new_git_dir
);
1829 enum start_bg_result
start_bg_command(struct child_process
*cmd
,
1830 start_bg_wait_cb
*wait_cb
,
1832 unsigned int timeout_sec
)
1834 enum start_bg_result sbgr
= SBGR_ERROR
;
1841 * We do not allow clean-on-exit because the child process
1842 * should persist in the background and possibly/probably
1843 * after this process exits. So we don't want to kill the
1844 * child during our atexit routine.
1846 if (cmd
->clean_on_exit
)
1847 BUG("start_bg_command() does not allow non-zero clean_on_exit");
1849 if (!cmd
->trace2_child_class
)
1850 cmd
->trace2_child_class
= "background";
1852 ret
= start_command(cmd
);
1855 * We assume that if `start_command()` fails, we
1856 * either get a complete `trace2_child_start() /
1857 * trace2_child_exit()` pair or it fails before the
1858 * `trace2_child_start()` is emitted, so we do not
1859 * need to worry about it here.
1861 * We also assume that `start_command()` does not add
1862 * us to the cleanup list. And that it calls
1863 * `child_process_clear()`.
1870 time_limit
+= timeout_sec
;
1873 pid_seen
= waitpid(cmd
->pid
, &wait_status
, WNOHANG
);
1877 * The child is currently running. Ask the callback
1878 * if the child is ready to do work or whether we
1879 * should keep waiting for it to boot up.
1881 ret
= (*wait_cb
)(cmd
, cb_data
);
1884 * The child is running and "ready".
1886 trace2_child_ready(cmd
, "ready");
1889 } else if (ret
> 0) {
1891 * The callback said to give it more time to boot up
1892 * (subject to our timeout limit).
1897 if (now
< time_limit
)
1901 * Our timeout has expired. We don't try to
1902 * kill the child, but rather let it continue
1903 * (hopefully) trying to startup.
1905 trace2_child_ready(cmd
, "timeout");
1906 sbgr
= SBGR_TIMEOUT
;
1910 * The cb gave up on this child. It is still running,
1911 * but our cb got an error trying to probe it.
1913 trace2_child_ready(cmd
, "error");
1914 sbgr
= SBGR_CB_ERROR
;
1919 else if (pid_seen
== cmd
->pid
) {
1920 int child_code
= -1;
1923 * The child started, but exited or was terminated
1924 * before becoming "ready".
1926 * We try to match the behavior of `wait_or_whine()`
1927 * WRT the handling of WIFSIGNALED() and WIFEXITED()
1928 * and convert the child's status to a return code for
1929 * tracing purposes and emit the `trace2_child_exit()`
1932 * We do not want the wait_or_whine() error message
1933 * because we will be called by client-side library
1936 if (WIFEXITED(wait_status
))
1937 child_code
= WEXITSTATUS(wait_status
);
1938 else if (WIFSIGNALED(wait_status
))
1939 child_code
= WTERMSIG(wait_status
) + 128;
1940 trace2_child_exit(cmd
, child_code
);
1946 else if (pid_seen
< 0 && errno
== EINTR
)
1949 trace2_child_exit(cmd
, -1);
1953 child_process_clear(cmd
);
1954 invalidate_lstat_cache();