2 #include "run-command.h"
3 #include "environment.h"
9 #include "thread-utils.h"
11 #include "string-list.h"
18 #include "compat/nonblock.h"
20 void child_process_init(struct child_process
*child
)
22 struct child_process blank
= CHILD_PROCESS_INIT
;
23 memcpy(child
, &blank
, sizeof(*child
));
26 void child_process_clear(struct child_process
*child
)
28 strvec_clear(&child
->args
);
29 strvec_clear(&child
->env
);
32 struct child_to_clean
{
34 struct child_process
*process
;
35 struct child_to_clean
*next
;
37 static struct child_to_clean
*children_to_clean
;
38 static int installed_child_cleanup_handler
;
40 static void cleanup_children(int sig
, int in_signal
)
42 struct child_to_clean
*children_to_wait_for
= NULL
;
44 while (children_to_clean
) {
45 struct child_to_clean
*p
= children_to_clean
;
46 children_to_clean
= p
->next
;
48 if (p
->process
&& !in_signal
) {
49 struct child_process
*process
= p
->process
;
50 if (process
->clean_on_exit_handler
) {
52 "trace: run_command: running exit handler for pid %"
53 PRIuMAX
, (uintmax_t)p
->pid
55 process
->clean_on_exit_handler(process
);
61 if (p
->process
&& p
->process
->wait_after_clean
) {
62 p
->next
= children_to_wait_for
;
63 children_to_wait_for
= p
;
70 while (children_to_wait_for
) {
71 struct child_to_clean
*p
= children_to_wait_for
;
72 children_to_wait_for
= p
->next
;
74 while (waitpid(p
->pid
, NULL
, 0) < 0 && errno
== EINTR
)
75 ; /* spin waiting for process exit or error */
82 static void cleanup_children_on_signal(int sig
)
84 cleanup_children(sig
, 1);
89 static void cleanup_children_on_exit(void)
91 cleanup_children(SIGTERM
, 0);
94 static void mark_child_for_cleanup(pid_t pid
, struct child_process
*process
)
96 struct child_to_clean
*p
= xmalloc(sizeof(*p
));
99 p
->next
= children_to_clean
;
100 children_to_clean
= p
;
102 if (!installed_child_cleanup_handler
) {
103 atexit(cleanup_children_on_exit
);
104 sigchain_push_common(cleanup_children_on_signal
);
105 installed_child_cleanup_handler
= 1;
109 static void clear_child_for_cleanup(pid_t pid
)
111 struct child_to_clean
**pp
;
113 for (pp
= &children_to_clean
; *pp
; pp
= &(*pp
)->next
) {
114 struct child_to_clean
*clean_me
= *pp
;
116 if (clean_me
->pid
== pid
) {
117 *pp
= clean_me
->next
;
124 static inline void close_pair(int fd
[2])
130 int is_executable(const char *name
)
134 if (stat(name
, &st
) || /* stat, not lstat */
135 !S_ISREG(st
.st_mode
))
138 #if defined(GIT_WINDOWS_NATIVE)
140 * On Windows there is no executable bit. The file extension
141 * indicates whether it can be run as an executable, and Git
142 * has special-handling to detect scripts and launch them
143 * through the indicated script interpreter. We test for the
144 * file extension first because virus scanners may make
145 * it quite expensive to open many files.
147 if (ends_with(name
, ".exe"))
152 * Now that we know it does not have an executable extension,
153 * peek into the file instead.
157 int fd
= open(name
, O_RDONLY
);
158 st
.st_mode
&= ~S_IXUSR
;
160 n
= read(fd
, buf
, 2);
162 /* look for a she-bang */
163 if (!strcmp(buf
, "#!"))
164 st
.st_mode
|= S_IXUSR
;
169 return st
.st_mode
& S_IXUSR
;
173 * Search $PATH for a command. This emulates the path search that
174 * execvp would perform, without actually executing the command so it
175 * can be used before fork() to prepare to run a command using
176 * execve() or after execvp() to diagnose why it failed.
178 * The caller should ensure that file contains no directory
181 * Returns the path to the command, as found in $PATH or NULL if the
182 * command could not be found. The caller inherits ownership of the memory
183 * used to store the resultant path.
185 * This should not be used on Windows, where the $PATH search rules
186 * are more complicated (e.g., a search for "foo" should find
189 static char *locate_in_PATH(const char *file
)
191 const char *p
= getenv("PATH");
192 struct strbuf buf
= STRBUF_INIT
;
198 const char *end
= strchrnul(p
, ':');
202 /* POSIX specifies an empty entry as the current directory. */
204 strbuf_add(&buf
, p
, end
- p
);
205 strbuf_addch(&buf
, '/');
207 strbuf_addstr(&buf
, file
);
209 if (is_executable(buf
.buf
))
210 return strbuf_detach(&buf
, NULL
);
217 strbuf_release(&buf
);
221 int exists_in_PATH(const char *command
)
223 char *r
= locate_in_PATH(command
);
224 int found
= r
!= NULL
;
229 int sane_execvp(const char *file
, char * const argv
[])
231 #ifndef GIT_WINDOWS_NATIVE
233 * execvp() doesn't return, so we all we can do is tell trace2
234 * what we are about to do and let it leave a hint in the log
235 * (unless of course the execvp() fails).
237 * we skip this for Windows because the compat layer already
238 * has to emulate the execvp() call anyway.
240 int exec_id
= trace2_exec(file
, (const char **)argv
);
243 if (!execvp(file
, argv
))
244 return 0; /* cannot happen ;-) */
246 #ifndef GIT_WINDOWS_NATIVE
249 trace2_exec_result(exec_id
, ec
);
255 * When a command can't be found because one of the directories
256 * listed in $PATH is unsearchable, execvp reports EACCES, but
257 * careful usability testing (read: analysis of occasional bug
258 * reports) reveals that "No such file or directory" is more
261 * We avoid commands with "/", because execvp will not do $PATH
262 * lookups in that case.
264 * The reassignment of EACCES to errno looks like a no-op below,
265 * but we need to protect against exists_in_PATH overwriting errno.
267 if (errno
== EACCES
&& !strchr(file
, '/'))
268 errno
= exists_in_PATH(file
) ? EACCES
: ENOENT
;
269 else if (errno
== ENOTDIR
&& !strchr(file
, '/'))
274 static const char **prepare_shell_cmd(struct strvec
*out
, const char **argv
)
277 BUG("shell command is empty");
279 if (strcspn(argv
[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv
[0])) {
280 #ifndef GIT_WINDOWS_NATIVE
281 strvec_push(out
, SHELL_PATH
);
283 strvec_push(out
, "sh");
285 strvec_push(out
, "-c");
288 * If we have no extra arguments, we do not even need to
289 * bother with the "$@" magic.
292 strvec_push(out
, argv
[0]);
294 strvec_pushf(out
, "%s \"$@\"", argv
[0]);
297 strvec_pushv(out
, argv
);
301 #ifndef GIT_WINDOWS_NATIVE
302 static int child_notifier
= -1;
308 CHILD_ERR_SIGPROCMASK
,
315 enum child_errcode err
;
316 int syserr
; /* errno */
319 static void child_die(enum child_errcode err
)
321 struct child_err buf
;
326 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
327 xwrite(child_notifier
, &buf
, sizeof(buf
));
331 static void child_dup2(int fd
, int to
)
333 if (dup2(fd
, to
) < 0)
334 child_die(CHILD_ERR_DUP2
);
337 static void child_close(int fd
)
340 child_die(CHILD_ERR_CLOSE
);
343 static void child_close_pair(int fd
[2])
349 static void child_error_fn(const char *err UNUSED
, va_list params UNUSED
)
351 const char msg
[] = "error() should not be called in child\n";
352 xwrite(2, msg
, sizeof(msg
) - 1);
355 static void child_warn_fn(const char *err UNUSED
, va_list params UNUSED
)
357 const char msg
[] = "warn() should not be called in child\n";
358 xwrite(2, msg
, sizeof(msg
) - 1);
361 static void NORETURN
child_die_fn(const char *err UNUSED
, va_list params UNUSED
)
363 const char msg
[] = "die() should not be called in child\n";
364 xwrite(2, msg
, sizeof(msg
) - 1);
368 /* this runs in the parent process */
369 static void child_err_spew(struct child_process
*cmd
, struct child_err
*cerr
)
371 static void (*old_errfn
)(const char *err
, va_list params
);
372 report_fn die_message_routine
= get_die_message_routine();
374 old_errfn
= get_error_routine();
375 set_error_routine(die_message_routine
);
376 errno
= cerr
->syserr
;
379 case CHILD_ERR_CHDIR
:
380 error_errno("exec '%s': cd to '%s' failed",
381 cmd
->args
.v
[0], cmd
->dir
);
384 error_errno("dup2() in child failed");
386 case CHILD_ERR_CLOSE
:
387 error_errno("close() in child failed");
389 case CHILD_ERR_SIGPROCMASK
:
390 error_errno("sigprocmask failed restoring signals");
392 case CHILD_ERR_ENOENT
:
393 error_errno("cannot run %s", cmd
->args
.v
[0]);
395 case CHILD_ERR_SILENT
:
397 case CHILD_ERR_ERRNO
:
398 error_errno("cannot exec '%s'", cmd
->args
.v
[0]);
401 set_error_routine(old_errfn
);
404 static int prepare_cmd(struct strvec
*out
, const struct child_process
*cmd
)
407 BUG("command is empty");
410 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
411 * attempt to interpret the command with 'sh'.
413 strvec_push(out
, SHELL_PATH
);
416 prepare_git_cmd(out
, cmd
->args
.v
);
417 } else if (cmd
->use_shell
) {
418 prepare_shell_cmd(out
, cmd
->args
.v
);
420 strvec_pushv(out
, cmd
->args
.v
);
424 * If there are no dir separator characters in the command then perform
425 * a path lookup and use the resolved path as the command to exec. If
426 * there are dir separator characters, we have exec attempt to invoke
427 * the command directly.
429 if (!has_dir_sep(out
->v
[1])) {
430 char *program
= locate_in_PATH(out
->v
[1]);
432 free((char *)out
->v
[1]);
444 static char **prep_childenv(const char *const *deltaenv
)
446 extern char **environ
;
448 struct string_list env
= STRING_LIST_INIT_DUP
;
449 struct strbuf key
= STRBUF_INIT
;
450 const char *const *p
;
453 /* Construct a sorted string list consisting of the current environ */
454 for (p
= (const char *const *) environ
; p
&& *p
; p
++) {
455 const char *equals
= strchr(*p
, '=');
459 strbuf_add(&key
, *p
, equals
- *p
);
460 string_list_append(&env
, key
.buf
)->util
= (void *) *p
;
462 string_list_append(&env
, *p
)->util
= (void *) *p
;
465 string_list_sort(&env
);
467 /* Merge in 'deltaenv' with the current environ */
468 for (p
= deltaenv
; p
&& *p
; p
++) {
469 const char *equals
= strchr(*p
, '=');
472 /* ('key=value'), insert or replace entry */
474 strbuf_add(&key
, *p
, equals
- *p
);
475 string_list_insert(&env
, key
.buf
)->util
= (void *) *p
;
477 /* otherwise ('key') remove existing entry */
478 string_list_remove(&env
, *p
, 0);
482 /* Create an array of 'char *' to be used as the childenv */
483 ALLOC_ARRAY(childenv
, env
.nr
+ 1);
484 for (i
= 0; i
< env
.nr
; i
++)
485 childenv
[i
] = env
.items
[i
].util
;
486 childenv
[env
.nr
] = NULL
;
488 string_list_clear(&env
, 0);
489 strbuf_release(&key
);
493 struct atfork_state
{
500 #define CHECK_BUG(err, msg) \
504 BUG("%s: %s", msg, strerror(e)); \
507 static void atfork_prepare(struct atfork_state
*as
)
511 if (sigfillset(&all
))
512 die_errno("sigfillset");
514 if (sigprocmask(SIG_SETMASK
, &all
, &as
->old
))
515 die_errno("sigprocmask");
517 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &all
, &as
->old
),
518 "blocking all signals");
519 CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &as
->cs
),
520 "disabling cancellation");
524 static void atfork_parent(struct atfork_state
*as
)
527 if (sigprocmask(SIG_SETMASK
, &as
->old
, NULL
))
528 die_errno("sigprocmask");
530 CHECK_BUG(pthread_setcancelstate(as
->cs
, NULL
),
531 "re-enabling cancellation");
532 CHECK_BUG(pthread_sigmask(SIG_SETMASK
, &as
->old
, NULL
),
533 "restoring signal mask");
536 #endif /* GIT_WINDOWS_NATIVE */
538 static inline void set_cloexec(int fd
)
540 int flags
= fcntl(fd
, F_GETFD
);
542 fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
545 static int wait_or_whine(pid_t pid
, const char *argv0
, int in_signal
)
547 int status
, code
= -1;
549 int failed_errno
= 0;
551 while ((waiting
= waitpid(pid
, &status
, 0)) < 0 && errno
== EINTR
)
555 failed_errno
= errno
;
557 error_errno("waitpid for %s failed", argv0
);
558 } else if (waiting
!= pid
) {
560 error("waitpid is confused (%s)", argv0
);
561 } else if (WIFSIGNALED(status
)) {
562 code
= WTERMSIG(status
);
563 if (!in_signal
&& code
!= SIGINT
&& code
!= SIGQUIT
&& code
!= SIGPIPE
)
564 error("%s died of signal %d", argv0
, code
);
566 * This return value is chosen so that code & 0xff
567 * mimics the exit code that a POSIX shell would report for
568 * a program that died from this signal.
571 } else if (WIFEXITED(status
)) {
572 code
= WEXITSTATUS(status
);
575 error("waitpid is confused (%s)", argv0
);
579 clear_child_for_cleanup(pid
);
581 errno
= failed_errno
;
585 static void trace_add_env(struct strbuf
*dst
, const char *const *deltaenv
)
587 struct string_list envs
= STRING_LIST_INIT_DUP
;
588 const char *const *e
;
590 int printed_unset
= 0;
592 /* Last one wins, see run-command.c:prep_childenv() for context */
593 for (e
= deltaenv
; e
&& *e
; e
++) {
594 struct strbuf key
= STRBUF_INIT
;
595 char *equals
= strchr(*e
, '=');
598 strbuf_add(&key
, *e
, equals
- *e
);
599 string_list_insert(&envs
, key
.buf
)->util
= equals
+ 1;
601 string_list_insert(&envs
, *e
)->util
= NULL
;
603 strbuf_release(&key
);
606 /* "unset X Y...;" */
607 for (i
= 0; i
< envs
.nr
; i
++) {
608 const char *var
= envs
.items
[i
].string
;
609 const char *val
= envs
.items
[i
].util
;
611 if (val
|| !getenv(var
))
614 if (!printed_unset
) {
615 strbuf_addstr(dst
, " unset");
618 strbuf_addf(dst
, " %s", var
);
621 strbuf_addch(dst
, ';');
623 /* ... followed by "A=B C=D ..." */
624 for (i
= 0; i
< envs
.nr
; i
++) {
625 const char *var
= envs
.items
[i
].string
;
626 const char *val
= envs
.items
[i
].util
;
632 oldval
= getenv(var
);
633 if (oldval
&& !strcmp(val
, oldval
))
636 strbuf_addf(dst
, " %s=", var
);
637 sq_quote_buf_pretty(dst
, val
);
639 string_list_clear(&envs
, 0);
642 static void trace_run_command(const struct child_process
*cp
)
644 struct strbuf buf
= STRBUF_INIT
;
646 if (!trace_want(&trace_default_key
))
649 strbuf_addstr(&buf
, "trace: run_command:");
651 strbuf_addstr(&buf
, " cd ");
652 sq_quote_buf_pretty(&buf
, cp
->dir
);
653 strbuf_addch(&buf
, ';');
655 trace_add_env(&buf
, cp
->env
.v
);
657 strbuf_addstr(&buf
, " git");
658 sq_quote_argv_pretty(&buf
, cp
->args
.v
);
660 trace_printf("%s", buf
.buf
);
661 strbuf_release(&buf
);
664 int start_command(struct child_process
*cmd
)
666 int need_in
, need_out
, need_err
;
667 int fdin
[2], fdout
[2], fderr
[2];
672 * In case of errors we must keep the promise to close FDs
673 * that have been passed in via ->in and ->out.
676 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
678 if (pipe(fdin
) < 0) {
679 failed_errno
= errno
;
682 str
= "standard input";
688 need_out
= !cmd
->no_stdout
689 && !cmd
->stdout_to_stderr
692 if (pipe(fdout
) < 0) {
693 failed_errno
= errno
;
698 str
= "standard output";
704 need_err
= !cmd
->no_stderr
&& cmd
->err
< 0;
706 if (pipe(fderr
) < 0) {
707 failed_errno
= errno
;
716 str
= "standard error";
718 error("cannot create %s pipe for %s: %s",
719 str
, cmd
->args
.v
[0], strerror(failed_errno
));
720 child_process_clear(cmd
);
721 errno
= failed_errno
;
727 trace2_child_start(cmd
);
728 trace_run_command(cmd
);
732 if (cmd
->close_object_store
)
733 close_object_store(the_repository
->objects
);
735 #ifndef GIT_WINDOWS_NATIVE
740 struct strvec argv
= STRVEC_INIT
;
741 struct child_err cerr
;
742 struct atfork_state as
;
744 if (prepare_cmd(&argv
, cmd
) < 0) {
745 failed_errno
= errno
;
747 if (!cmd
->silent_exec_failure
)
748 error_errno("cannot run %s", cmd
->args
.v
[0]);
752 if (pipe(notify_pipe
))
753 notify_pipe
[0] = notify_pipe
[1] = -1;
755 if (cmd
->no_stdin
|| cmd
->no_stdout
|| cmd
->no_stderr
) {
756 null_fd
= xopen("/dev/null", O_RDWR
| O_CLOEXEC
);
757 set_cloexec(null_fd
);
760 childenv
= prep_childenv(cmd
->env
.v
);
764 * NOTE: In order to prevent deadlocking when using threads special
765 * care should be taken with the function calls made in between the
766 * fork() and exec() calls. No calls should be made to functions which
767 * require acquiring a lock (e.g. malloc) as the lock could have been
768 * held by another thread at the time of forking, causing the lock to
769 * never be released in the child process. This means only
770 * Async-Signal-Safe functions are permitted in the child.
773 failed_errno
= errno
;
777 * Ensure the default die/error/warn routines do not get
778 * called, they can take stdio locks and malloc.
780 set_die_routine(child_die_fn
);
781 set_error_routine(child_error_fn
);
782 set_warn_routine(child_warn_fn
);
784 close(notify_pipe
[0]);
785 set_cloexec(notify_pipe
[1]);
786 child_notifier
= notify_pipe
[1];
789 child_dup2(null_fd
, 0);
791 child_dup2(fdin
[0], 0);
792 child_close_pair(fdin
);
793 } else if (cmd
->in
) {
794 child_dup2(cmd
->in
, 0);
795 child_close(cmd
->in
);
799 child_dup2(null_fd
, 2);
801 child_dup2(fderr
[1], 2);
802 child_close_pair(fderr
);
803 } else if (cmd
->err
> 1) {
804 child_dup2(cmd
->err
, 2);
805 child_close(cmd
->err
);
809 child_dup2(null_fd
, 1);
810 else if (cmd
->stdout_to_stderr
)
813 child_dup2(fdout
[1], 1);
814 child_close_pair(fdout
);
815 } else if (cmd
->out
> 1) {
816 child_dup2(cmd
->out
, 1);
817 child_close(cmd
->out
);
820 if (cmd
->dir
&& chdir(cmd
->dir
))
821 child_die(CHILD_ERR_CHDIR
);
824 * restore default signal handlers here, in case
825 * we catch a signal right before execve below
827 for (sig
= 1; sig
< NSIG
; sig
++) {
828 /* ignored signals get reset to SIG_DFL on execve */
829 if (signal(sig
, SIG_DFL
) == SIG_IGN
)
830 signal(sig
, SIG_IGN
);
833 if (sigprocmask(SIG_SETMASK
, &as
.old
, NULL
) != 0)
834 child_die(CHILD_ERR_SIGPROCMASK
);
837 * Attempt to exec using the command and arguments starting at
838 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
839 * be used in the event exec failed with ENOEXEC at which point
840 * we will try to interpret the command using 'sh'.
842 execve(argv
.v
[1], (char *const *) argv
.v
+ 1,
843 (char *const *) childenv
);
844 if (errno
== ENOEXEC
)
845 execve(argv
.v
[0], (char *const *) argv
.v
,
846 (char *const *) childenv
);
848 if (errno
== ENOENT
) {
849 if (cmd
->silent_exec_failure
)
850 child_die(CHILD_ERR_SILENT
);
851 child_die(CHILD_ERR_ENOENT
);
853 child_die(CHILD_ERR_ERRNO
);
858 error_errno("cannot fork() for %s", cmd
->args
.v
[0]);
859 else if (cmd
->clean_on_exit
)
860 mark_child_for_cleanup(cmd
->pid
, cmd
);
863 * Wait for child's exec. If the exec succeeds (or if fork()
864 * failed), EOF is seen immediately by the parent. Otherwise, the
865 * child process sends a child_err struct.
866 * Note that use of this infrastructure is completely advisory,
867 * therefore, we keep error checks minimal.
869 close(notify_pipe
[1]);
870 if (xread(notify_pipe
[0], &cerr
, sizeof(cerr
)) == sizeof(cerr
)) {
872 * At this point we know that fork() succeeded, but exec()
873 * failed. Errors have been reported to our stderr.
875 wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
876 child_err_spew(cmd
, &cerr
);
877 failed_errno
= errno
;
880 close(notify_pipe
[0]);
891 int fhin
= 0, fhout
= 1, fherr
= 2;
892 const char **sargv
= cmd
->args
.v
;
893 struct strvec nargv
= STRVEC_INIT
;
896 fhin
= open("/dev/null", O_RDWR
);
903 fherr
= open("/dev/null", O_RDWR
);
905 fherr
= dup(fderr
[1]);
906 else if (cmd
->err
> 2)
907 fherr
= dup(cmd
->err
);
910 fhout
= open("/dev/null", O_RDWR
);
911 else if (cmd
->stdout_to_stderr
)
914 fhout
= dup(fdout
[1]);
915 else if (cmd
->out
> 1)
916 fhout
= dup(cmd
->out
);
919 cmd
->args
.v
= prepare_git_cmd(&nargv
, sargv
);
920 else if (cmd
->use_shell
)
921 cmd
->args
.v
= prepare_shell_cmd(&nargv
, sargv
);
923 cmd
->pid
= mingw_spawnvpe(cmd
->args
.v
[0], cmd
->args
.v
,
925 cmd
->dir
, fhin
, fhout
, fherr
);
926 failed_errno
= errno
;
927 if (cmd
->pid
< 0 && (!cmd
->silent_exec_failure
|| errno
!= ENOENT
))
928 error_errno("cannot spawn %s", cmd
->args
.v
[0]);
929 if (cmd
->clean_on_exit
&& cmd
->pid
>= 0)
930 mark_child_for_cleanup(cmd
->pid
, cmd
);
932 strvec_clear(&nargv
);
944 trace2_child_exit(cmd
, -1);
958 child_process_clear(cmd
);
959 errno
= failed_errno
;
981 int finish_command(struct child_process
*cmd
)
983 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 0);
984 trace2_child_exit(cmd
, ret
);
985 child_process_clear(cmd
);
986 invalidate_lstat_cache();
990 int finish_command_in_signal(struct child_process
*cmd
)
992 int ret
= wait_or_whine(cmd
->pid
, cmd
->args
.v
[0], 1);
994 trace2_child_exit(cmd
, ret
);
999 int run_command(struct child_process
*cmd
)
1003 if (cmd
->out
< 0 || cmd
->err
< 0)
1004 BUG("run_command with a pipe can cause deadlock");
1006 code
= start_command(cmd
);
1009 return finish_command(cmd
);
1013 static pthread_t main_thread
;
1014 static int main_thread_set
;
1015 static pthread_key_t async_key
;
1016 static pthread_key_t async_die_counter
;
1018 static void *run_thread(void *data
)
1020 struct async
*async
= data
;
1023 if (async
->isolate_sigpipe
) {
1026 sigaddset(&mask
, SIGPIPE
);
1027 if (pthread_sigmask(SIG_BLOCK
, &mask
, NULL
)) {
1028 ret
= error("unable to block SIGPIPE in async thread");
1033 pthread_setspecific(async_key
, async
);
1034 ret
= async
->proc(async
->proc_in
, async
->proc_out
, async
->data
);
1038 static NORETURN
void die_async(const char *err
, va_list params
)
1040 report_fn die_message_fn
= get_die_message_routine();
1042 die_message_fn(err
, params
);
1045 struct async
*async
= pthread_getspecific(async_key
);
1046 if (async
->proc_in
>= 0)
1047 close(async
->proc_in
);
1048 if (async
->proc_out
>= 0)
1049 close(async
->proc_out
);
1050 pthread_exit((void *)128);
1056 static int async_die_is_recursing(void)
1058 void *ret
= pthread_getspecific(async_die_counter
);
1059 pthread_setspecific(async_die_counter
, &async_die_counter
); /* set to any non-NULL valid pointer */
1065 if (!main_thread_set
)
1066 return 0; /* no asyncs started yet */
1067 return !pthread_equal(main_thread
, pthread_self());
1070 static void NORETURN
async_exit(int code
)
1072 pthread_exit((void *)(intptr_t)code
);
1078 void (**handlers
)(void);
1083 static int git_atexit_installed
;
1085 static void git_atexit_dispatch(void)
1089 for (i
=git_atexit_hdlrs
.nr
; i
; i
--)
1090 git_atexit_hdlrs
.handlers
[i
-1]();
1093 static void git_atexit_clear(void)
1095 free(git_atexit_hdlrs
.handlers
);
1096 memset(&git_atexit_hdlrs
, 0, sizeof(git_atexit_hdlrs
));
1097 git_atexit_installed
= 0;
1101 int git_atexit(void (*handler
)(void))
1103 ALLOC_GROW(git_atexit_hdlrs
.handlers
, git_atexit_hdlrs
.nr
+ 1, git_atexit_hdlrs
.alloc
);
1104 git_atexit_hdlrs
.handlers
[git_atexit_hdlrs
.nr
++] = handler
;
1105 if (!git_atexit_installed
) {
1106 if (atexit(&git_atexit_dispatch
))
1108 git_atexit_installed
= 1;
1112 #define atexit git_atexit
1114 static int process_is_async
;
1117 return process_is_async
;
1120 static void NORETURN
async_exit(int code
)
1127 void check_pipe(int err
)
1133 signal(SIGPIPE
, SIG_DFL
);
1135 /* Should never happen, but just in case... */
1140 int start_async(struct async
*async
)
1142 int need_in
, need_out
;
1143 int fdin
[2], fdout
[2];
1144 int proc_in
, proc_out
;
1146 need_in
= async
->in
< 0;
1148 if (pipe(fdin
) < 0) {
1151 return error_errno("cannot create pipe");
1153 async
->in
= fdin
[1];
1156 need_out
= async
->out
< 0;
1158 if (pipe(fdout
) < 0) {
1163 return error_errno("cannot create pipe");
1165 async
->out
= fdout
[0];
1171 proc_in
= async
->in
;
1176 proc_out
= fdout
[1];
1177 else if (async
->out
)
1178 proc_out
= async
->out
;
1183 /* Flush stdio before fork() to avoid cloning buffers */
1186 async
->pid
= fork();
1187 if (async
->pid
< 0) {
1188 error_errno("fork (async) failed");
1197 process_is_async
= 1;
1198 exit(!!async
->proc(proc_in
, proc_out
, async
->data
));
1201 mark_child_for_cleanup(async
->pid
, NULL
);
1210 else if (async
->out
)
1213 if (!main_thread_set
) {
1215 * We assume that the first time that start_async is called
1216 * it is from the main thread.
1218 main_thread_set
= 1;
1219 main_thread
= pthread_self();
1220 pthread_key_create(&async_key
, NULL
);
1221 pthread_key_create(&async_die_counter
, NULL
);
1222 set_die_routine(die_async
);
1223 set_die_is_recursing_routine(async_die_is_recursing
);
1227 set_cloexec(proc_in
);
1229 set_cloexec(proc_out
);
1230 async
->proc_in
= proc_in
;
1231 async
->proc_out
= proc_out
;
1233 int err
= pthread_create(&async
->tid
, NULL
, run_thread
, async
);
1235 error(_("cannot create async thread: %s"), strerror(err
));
1250 else if (async
->out
)
1255 int finish_async(struct async
*async
)
1258 int ret
= wait_or_whine(async
->pid
, "child process", 0);
1260 invalidate_lstat_cache();
1264 void *ret
= (void *)(intptr_t)(-1);
1266 if (pthread_join(async
->tid
, &ret
))
1267 error("pthread_join failed");
1268 invalidate_lstat_cache();
1269 return (int)(intptr_t)ret
;
1274 int async_with_fork(void)
1284 /* initialized by caller */
1286 int type
; /* POLLOUT or POLLIN */
1298 /* returned by pump_io */
1299 int error
; /* 0 for success, otherwise errno */
1305 static int pump_io_round(struct io_pump
*slots
, int nr
, struct pollfd
*pfd
)
1310 for (i
= 0; i
< nr
; i
++) {
1311 struct io_pump
*io
= &slots
[i
];
1314 pfd
[pollsize
].fd
= io
->fd
;
1315 pfd
[pollsize
].events
= io
->type
;
1316 io
->pfd
= &pfd
[pollsize
++];
1322 if (poll(pfd
, pollsize
, -1) < 0) {
1325 die_errno("poll failed");
1328 for (i
= 0; i
< nr
; i
++) {
1329 struct io_pump
*io
= &slots
[i
];
1334 if (!(io
->pfd
->revents
& (POLLOUT
|POLLIN
|POLLHUP
|POLLERR
|POLLNVAL
)))
1337 if (io
->type
== POLLOUT
) {
1341 * Don't use xwrite() here. It loops forever on EAGAIN,
1342 * and we're in our own poll() loop here.
1344 * Note that we lose xwrite()'s handling of MAX_IO_SIZE
1345 * and EINTR, so we have to implement those ourselves.
1347 len
= write(io
->fd
, io
->u
.out
.buf
,
1348 io
->u
.out
.len
<= MAX_IO_SIZE
?
1349 io
->u
.out
.len
: MAX_IO_SIZE
);
1351 if (errno
!= EINTR
&& errno
!= EAGAIN
&&
1358 io
->u
.out
.buf
+= len
;
1359 io
->u
.out
.len
-= len
;
1360 if (!io
->u
.out
.len
) {
1367 if (io
->type
== POLLIN
) {
1368 ssize_t len
= strbuf_read_once(io
->u
.in
.buf
,
1369 io
->fd
, io
->u
.in
.hint
);
1382 static int pump_io(struct io_pump
*slots
, int nr
)
1387 for (i
= 0; i
< nr
; i
++)
1390 ALLOC_ARRAY(pfd
, nr
);
1391 while (pump_io_round(slots
, nr
, pfd
))
1395 /* There may be multiple errno values, so just pick the first. */
1396 for (i
= 0; i
< nr
; i
++) {
1397 if (slots
[i
].error
) {
1398 errno
= slots
[i
].error
;
1406 int pipe_command(struct child_process
*cmd
,
1407 const char *in
, size_t in_len
,
1408 struct strbuf
*out
, size_t out_hint
,
1409 struct strbuf
*err
, size_t err_hint
)
1411 struct io_pump io
[3];
1421 if (start_command(cmd
) < 0)
1425 if (enable_pipe_nonblock(cmd
->in
) < 0) {
1426 error_errno("unable to make pipe non-blocking");
1434 io
[nr
].fd
= cmd
->in
;
1435 io
[nr
].type
= POLLOUT
;
1436 io
[nr
].u
.out
.buf
= in
;
1437 io
[nr
].u
.out
.len
= in_len
;
1441 io
[nr
].fd
= cmd
->out
;
1442 io
[nr
].type
= POLLIN
;
1443 io
[nr
].u
.in
.buf
= out
;
1444 io
[nr
].u
.in
.hint
= out_hint
;
1448 io
[nr
].fd
= cmd
->err
;
1449 io
[nr
].type
= POLLIN
;
1450 io
[nr
].u
.in
.buf
= err
;
1451 io
[nr
].u
.in
.hint
= err_hint
;
1455 if (pump_io(io
, nr
) < 0) {
1456 finish_command(cmd
); /* throw away exit code */
1460 return finish_command(cmd
);
1466 GIT_CP_WAIT_CLEANUP
,
1469 struct parallel_processes
{
1470 size_t nr_processes
;
1473 enum child_state state
;
1474 struct child_process process
;
1479 * The struct pollfd is logically part of *children,
1480 * but the system call expects it as its own array.
1484 unsigned shutdown
: 1;
1486 size_t output_owner
;
1487 struct strbuf buffered_output
; /* of finished children */
1490 struct parallel_processes_for_signal
{
1491 const struct run_process_parallel_opts
*opts
;
1492 const struct parallel_processes
*pp
;
1495 static void kill_children(const struct parallel_processes
*pp
,
1496 const struct run_process_parallel_opts
*opts
,
1499 for (size_t i
= 0; i
< opts
->processes
; i
++)
1500 if (pp
->children
[i
].state
== GIT_CP_WORKING
)
1501 kill(pp
->children
[i
].process
.pid
, signo
);
1504 static void kill_children_signal(const struct parallel_processes_for_signal
*pp_sig
,
1507 kill_children(pp_sig
->pp
, pp_sig
->opts
, signo
);
1510 static struct parallel_processes_for_signal
*pp_for_signal
;
1512 static void handle_children_on_signal(int signo
)
1514 kill_children_signal(pp_for_signal
, signo
);
1515 sigchain_pop(signo
);
1519 static void pp_init(struct parallel_processes
*pp
,
1520 const struct run_process_parallel_opts
*opts
,
1521 struct parallel_processes_for_signal
*pp_sig
)
1523 const size_t n
= opts
->processes
;
1526 BUG("you must provide a non-zero number of processes!");
1528 trace_printf("run_processes_parallel: preparing to run up to %"PRIuMAX
" tasks",
1531 if (!opts
->get_next_task
)
1532 BUG("you need to specify a get_next_task function");
1534 CALLOC_ARRAY(pp
->children
, n
);
1536 CALLOC_ARRAY(pp
->pfd
, n
);
1538 for (size_t i
= 0; i
< n
; i
++) {
1539 strbuf_init(&pp
->children
[i
].err
, 0);
1540 child_process_init(&pp
->children
[i
].process
);
1542 pp
->pfd
[i
].events
= POLLIN
| POLLHUP
;
1548 pp_sig
->opts
= opts
;
1549 pp_for_signal
= pp_sig
;
1550 sigchain_push_common(handle_children_on_signal
);
1553 static void pp_cleanup(struct parallel_processes
*pp
,
1554 const struct run_process_parallel_opts
*opts
)
1556 trace_printf("run_processes_parallel: done");
1557 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1558 strbuf_release(&pp
->children
[i
].err
);
1559 child_process_clear(&pp
->children
[i
].process
);
1566 * When get_next_task added messages to the buffer in its last
1567 * iteration, the buffered output is non empty.
1569 strbuf_write(&pp
->buffered_output
, stderr
);
1570 strbuf_release(&pp
->buffered_output
);
1572 sigchain_pop_common();
1576 * 0 if a new task was started.
1577 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1578 * problem with starting a new command)
1579 * <0 no new job was started, user wishes to shutdown early. Use negative code
1580 * to signal the children.
1582 static int pp_start_one(struct parallel_processes
*pp
,
1583 const struct run_process_parallel_opts
*opts
)
1588 for (i
= 0; i
< opts
->processes
; i
++)
1589 if (pp
->children
[i
].state
== GIT_CP_FREE
)
1591 if (i
== opts
->processes
)
1592 BUG("bookkeeping is hard");
1595 * By default, do not inherit stdin from the parent process - otherwise,
1596 * all children would share stdin! Users may overwrite this to provide
1597 * something to the child's stdin by having their 'get_next_task'
1598 * callback assign 0 to .no_stdin and an appropriate integer to .in.
1600 pp
->children
[i
].process
.no_stdin
= 1;
1602 code
= opts
->get_next_task(&pp
->children
[i
].process
,
1603 opts
->ungroup
? NULL
: &pp
->children
[i
].err
,
1605 &pp
->children
[i
].data
);
1607 if (!opts
->ungroup
) {
1608 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1609 strbuf_reset(&pp
->children
[i
].err
);
1613 if (!opts
->ungroup
) {
1614 pp
->children
[i
].process
.err
= -1;
1615 pp
->children
[i
].process
.stdout_to_stderr
= 1;
1618 if (start_command(&pp
->children
[i
].process
)) {
1619 if (opts
->start_failure
)
1620 code
= opts
->start_failure(opts
->ungroup
? NULL
:
1621 &pp
->children
[i
].err
,
1623 pp
->children
[i
].data
);
1627 if (!opts
->ungroup
) {
1628 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1629 strbuf_reset(&pp
->children
[i
].err
);
1637 pp
->children
[i
].state
= GIT_CP_WORKING
;
1639 pp
->pfd
[i
].fd
= pp
->children
[i
].process
.err
;
1643 static void pp_buffer_stderr(struct parallel_processes
*pp
,
1644 const struct run_process_parallel_opts
*opts
,
1647 while (poll(pp
->pfd
, opts
->processes
, output_timeout
) < 0) {
1650 pp_cleanup(pp
, opts
);
1654 /* Buffer output from all pipes. */
1655 for (size_t i
= 0; i
< opts
->processes
; i
++) {
1656 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1657 pp
->pfd
[i
].revents
& (POLLIN
| POLLHUP
)) {
1658 int n
= strbuf_read_once(&pp
->children
[i
].err
,
1659 pp
->children
[i
].process
.err
, 0);
1661 close(pp
->children
[i
].process
.err
);
1662 pp
->children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1664 if (errno
!= EAGAIN
)
1670 static void pp_output(const struct parallel_processes
*pp
)
1672 size_t i
= pp
->output_owner
;
1674 if (pp
->children
[i
].state
== GIT_CP_WORKING
&&
1675 pp
->children
[i
].err
.len
) {
1676 strbuf_write(&pp
->children
[i
].err
, stderr
);
1677 strbuf_reset(&pp
->children
[i
].err
);
1681 static int pp_collect_finished(struct parallel_processes
*pp
,
1682 const struct run_process_parallel_opts
*opts
)
1688 while (pp
->nr_processes
> 0) {
1689 for (i
= 0; i
< opts
->processes
; i
++)
1690 if (pp
->children
[i
].state
== GIT_CP_WAIT_CLEANUP
)
1692 if (i
== opts
->processes
)
1695 code
= finish_command(&pp
->children
[i
].process
);
1697 if (opts
->task_finished
)
1698 code
= opts
->task_finished(code
, opts
->ungroup
? NULL
:
1699 &pp
->children
[i
].err
, opts
->data
,
1700 pp
->children
[i
].data
);
1710 pp
->children
[i
].state
= GIT_CP_FREE
;
1713 child_process_init(&pp
->children
[i
].process
);
1715 if (opts
->ungroup
) {
1716 ; /* no strbuf_*() work to do here */
1717 } else if (i
!= pp
->output_owner
) {
1718 strbuf_addbuf(&pp
->buffered_output
, &pp
->children
[i
].err
);
1719 strbuf_reset(&pp
->children
[i
].err
);
1721 const size_t n
= opts
->processes
;
1723 strbuf_write(&pp
->children
[i
].err
, stderr
);
1724 strbuf_reset(&pp
->children
[i
].err
);
1726 /* Output all other finished child processes */
1727 strbuf_write(&pp
->buffered_output
, stderr
);
1728 strbuf_reset(&pp
->buffered_output
);
1731 * Pick next process to output live.
1733 * For now we pick it randomly by doing a round
1734 * robin. Later we may want to pick the one with
1735 * the most output or the longest or shortest
1736 * running process time.
1738 for (i
= 0; i
< n
; i
++)
1739 if (pp
->children
[(pp
->output_owner
+ i
) % n
].state
== GIT_CP_WORKING
)
1741 pp
->output_owner
= (pp
->output_owner
+ i
) % n
;
1747 void run_processes_parallel(const struct run_process_parallel_opts
*opts
)
1750 int output_timeout
= 100;
1752 struct parallel_processes_for_signal pp_sig
;
1753 struct parallel_processes pp
= {
1754 .buffered_output
= STRBUF_INIT
,
1757 const char *tr2_category
= opts
->tr2_category
;
1758 const char *tr2_label
= opts
->tr2_label
;
1759 const int do_trace2
= tr2_category
&& tr2_label
;
1762 trace2_region_enter_printf(tr2_category
, tr2_label
, NULL
,
1763 "max:%d", opts
->processes
);
1765 pp_init(&pp
, opts
, &pp_sig
);
1768 i
< spawn_cap
&& !pp
.shutdown
&&
1769 pp
.nr_processes
< opts
->processes
;
1771 code
= pp_start_one(&pp
, opts
);
1776 kill_children(&pp
, opts
, -code
);
1780 if (!pp
.nr_processes
)
1782 if (opts
->ungroup
) {
1783 for (size_t i
= 0; i
< opts
->processes
; i
++)
1784 pp
.children
[i
].state
= GIT_CP_WAIT_CLEANUP
;
1786 pp_buffer_stderr(&pp
, opts
, output_timeout
);
1789 code
= pp_collect_finished(&pp
, opts
);
1793 kill_children(&pp
, opts
,-code
);
1797 pp_cleanup(&pp
, opts
);
1800 trace2_region_leave(tr2_category
, tr2_label
, NULL
);
1803 int run_auto_maintenance(int quiet
)
1806 struct child_process maint
= CHILD_PROCESS_INIT
;
1808 if (!git_config_get_bool("maintenance.auto", &enabled
) &&
1813 maint
.close_object_store
= 1;
1814 strvec_pushl(&maint
.args
, "maintenance", "run", "--auto", NULL
);
1815 strvec_push(&maint
.args
, quiet
? "--quiet" : "--no-quiet");
1817 return run_command(&maint
);
1820 void prepare_other_repo_env(struct strvec
*env
, const char *new_git_dir
)
1822 const char * const *var
;
1824 for (var
= local_repo_env
; *var
; var
++) {
1825 if (strcmp(*var
, CONFIG_DATA_ENVIRONMENT
) &&
1826 strcmp(*var
, CONFIG_COUNT_ENVIRONMENT
))
1827 strvec_push(env
, *var
);
1829 strvec_pushf(env
, "%s=%s", GIT_DIR_ENVIRONMENT
, new_git_dir
);
1832 enum start_bg_result
start_bg_command(struct child_process
*cmd
,
1833 start_bg_wait_cb
*wait_cb
,
1835 unsigned int timeout_sec
)
1837 enum start_bg_result sbgr
= SBGR_ERROR
;
1844 * We do not allow clean-on-exit because the child process
1845 * should persist in the background and possibly/probably
1846 * after this process exits. So we don't want to kill the
1847 * child during our atexit routine.
1849 if (cmd
->clean_on_exit
)
1850 BUG("start_bg_command() does not allow non-zero clean_on_exit");
1852 if (!cmd
->trace2_child_class
)
1853 cmd
->trace2_child_class
= "background";
1855 ret
= start_command(cmd
);
1858 * We assume that if `start_command()` fails, we
1859 * either get a complete `trace2_child_start() /
1860 * trace2_child_exit()` pair or it fails before the
1861 * `trace2_child_start()` is emitted, so we do not
1862 * need to worry about it here.
1864 * We also assume that `start_command()` does not add
1865 * us to the cleanup list. And that it calls
1866 * `child_process_clear()`.
1873 time_limit
+= timeout_sec
;
1876 pid_seen
= waitpid(cmd
->pid
, &wait_status
, WNOHANG
);
1880 * The child is currently running. Ask the callback
1881 * if the child is ready to do work or whether we
1882 * should keep waiting for it to boot up.
1884 ret
= (*wait_cb
)(cmd
, cb_data
);
1887 * The child is running and "ready".
1889 trace2_child_ready(cmd
, "ready");
1892 } else if (ret
> 0) {
1894 * The callback said to give it more time to boot up
1895 * (subject to our timeout limit).
1900 if (now
< time_limit
)
1904 * Our timeout has expired. We don't try to
1905 * kill the child, but rather let it continue
1906 * (hopefully) trying to startup.
1908 trace2_child_ready(cmd
, "timeout");
1909 sbgr
= SBGR_TIMEOUT
;
1913 * The cb gave up on this child. It is still running,
1914 * but our cb got an error trying to probe it.
1916 trace2_child_ready(cmd
, "error");
1917 sbgr
= SBGR_CB_ERROR
;
1922 else if (pid_seen
== cmd
->pid
) {
1923 int child_code
= -1;
1926 * The child started, but exited or was terminated
1927 * before becoming "ready".
1929 * We try to match the behavior of `wait_or_whine()`
1930 * WRT the handling of WIFSIGNALED() and WIFEXITED()
1931 * and convert the child's status to a return code for
1932 * tracing purposes and emit the `trace2_child_exit()`
1935 * We do not want the wait_or_whine() error message
1936 * because we will be called by client-side library
1939 if (WIFEXITED(wait_status
))
1940 child_code
= WEXITSTATUS(wait_status
);
1941 else if (WIFSIGNALED(wait_status
))
1942 child_code
= WTERMSIG(wait_status
) + 128;
1943 trace2_child_exit(cmd
, child_code
);
1949 else if (pid_seen
< 0 && errno
== EINTR
)
1952 trace2_child_exit(cmd
, -1);
1956 child_process_clear(cmd
);
1957 invalidate_lstat_cache();