2 #include "run-command.h"
5 #include "argv-array.h"
6 #include "thread-utils.h"
9 void child_process_init(struct child_process *child)
11 memset(child, 0, sizeof(*child));
12 argv_array_init(&child->args);
13 argv_array_init(&child->env_array);
16 void child_process_clear(struct child_process *child)
18 argv_array_clear(&child->args);
19 argv_array_clear(&child->env_array);
22 struct child_to_clean {
24 struct child_process *process;
25 struct child_to_clean *next;
27 static struct child_to_clean *children_to_clean;
28 static int installed_child_cleanup_handler;
30 static void cleanup_children(int sig, int in_signal)
32 struct child_to_clean *children_to_wait_for = NULL;
34 while (children_to_clean) {
35 struct child_to_clean *p = children_to_clean;
36 children_to_clean = p->next;
38 if (p->process && !in_signal) {
39 struct child_process *process = p->process;
40 if (process->clean_on_exit_handler) {
42 "trace: run_command: running exit handler for pid %"
43 PRIuMAX, (uintmax_t)p->pid
45 process->clean_on_exit_handler(process);
51 if (p->process && p->process->wait_after_clean) {
52 p->next = children_to_wait_for;
53 children_to_wait_for = p;
60 while (children_to_wait_for) {
61 struct child_to_clean *p = children_to_wait_for;
62 children_to_wait_for = p->next;
64 while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
65 ; /* spin waiting for process exit or error */
72 static void cleanup_children_on_signal(int sig)
74 cleanup_children(sig, 1);
79 static void cleanup_children_on_exit(void)
81 cleanup_children(SIGTERM, 0);
84 static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
86 struct child_to_clean *p = xmalloc(sizeof(*p));
89 p->next = children_to_clean;
90 children_to_clean = p;
92 if (!installed_child_cleanup_handler) {
93 atexit(cleanup_children_on_exit);
94 sigchain_push_common(cleanup_children_on_signal);
95 installed_child_cleanup_handler = 1;
99 static void clear_child_for_cleanup(pid_t pid)
101 struct child_to_clean **pp;
103 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
104 struct child_to_clean *clean_me = *pp;
106 if (clean_me->pid == pid) {
107 *pp = clean_me->next;
114 static inline void close_pair(int fd[2])
120 int is_executable(const char *name)
124 if (stat(name, &st) || /* stat, not lstat */
125 !S_ISREG(st.st_mode))
128 #if defined(GIT_WINDOWS_NATIVE)
130 * On Windows there is no executable bit. The file extension
131 * indicates whether it can be run as an executable, and Git
132 * has special-handling to detect scripts and launch them
133 * through the indicated script interpreter. We test for the
134 * file extension first because virus scanners may make
135 * it quite expensive to open many files.
137 if (ends_with(name, ".exe"))
142 * Now that we know it does not have an executable extension,
143 * peek into the file instead.
147 int fd = open(name, O_RDONLY);
148 st.st_mode &= ~S_IXUSR;
150 n = read(fd, buf, 2);
152 /* look for a she-bang */
153 if (!strcmp(buf, "#!"))
154 st.st_mode |= S_IXUSR;
159 return st.st_mode & S_IXUSR;
162 static char *locate_in_PATH(const char *file)
164 const char *p = getenv("PATH");
165 struct strbuf buf = STRBUF_INIT;
171 const char *end = strchrnul(p, ':');
175 /* POSIX specifies an empty entry as the current directory. */
177 strbuf_add(&buf, p, end - p);
178 strbuf_addch(&buf, '/');
180 strbuf_addstr(&buf, file);
182 if (!access(buf.buf, F_OK))
183 return strbuf_detach(&buf, NULL);
190 strbuf_release(&buf);
194 static int exists_in_PATH(const char *file)
196 char *r = locate_in_PATH(file);
201 int sane_execvp(const char *file, char * const argv[])
203 if (!execvp(file, argv))
204 return 0; /* cannot happen ;-) */
207 * When a command can't be found because one of the directories
208 * listed in $PATH is unsearchable, execvp reports EACCES, but
209 * careful usability testing (read: analysis of occasional bug
210 * reports) reveals that "No such file or directory" is more
213 * We avoid commands with "/", because execvp will not do $PATH
214 * lookups in that case.
216 * The reassignment of EACCES to errno looks like a no-op below,
217 * but we need to protect against exists_in_PATH overwriting errno.
219 if (errno == EACCES && !strchr(file, '/'))
220 errno = exists_in_PATH(file) ? EACCES : ENOENT;
221 else if (errno == ENOTDIR && !strchr(file, '/'))
226 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
229 die("BUG: shell command is empty");
231 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
232 #ifndef GIT_WINDOWS_NATIVE
233 argv_array_push(out, SHELL_PATH);
235 argv_array_push(out, "sh");
237 argv_array_push(out, "-c");
240 * If we have no extra arguments, we do not even need to
241 * bother with the "$@" magic.
244 argv_array_push(out, argv[0]);
246 argv_array_pushf(out, "%s \"$@\"", argv[0]);
249 argv_array_pushv(out, argv);
253 #ifndef GIT_WINDOWS_NATIVE
254 static int child_notifier = -1;
260 CHILD_ERR_SIGPROCMASK,
267 enum child_errcode err;
268 int syserr; /* errno */
271 static void child_die(enum child_errcode err)
273 struct child_err buf;
278 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
279 xwrite(child_notifier, &buf, sizeof(buf));
283 static void child_dup2(int fd, int to)
285 if (dup2(fd, to) < 0)
286 child_die(CHILD_ERR_DUP2);
289 static void child_close(int fd)
292 child_die(CHILD_ERR_CLOSE);
295 static void child_close_pair(int fd[2])
302 * parent will make it look like the child spewed a fatal error and died
303 * this is needed to prevent changes to t0061.
305 static void fake_fatal(const char *err, va_list params)
307 vreportf("fatal: ", err, params);
310 static void child_error_fn(const char *err, va_list params)
312 const char msg[] = "error() should not be called in child\n";
313 xwrite(2, msg, sizeof(msg) - 1);
316 static void child_warn_fn(const char *err, va_list params)
318 const char msg[] = "warn() should not be called in child\n";
319 xwrite(2, msg, sizeof(msg) - 1);
322 static void NORETURN child_die_fn(const char *err, va_list params)
324 const char msg[] = "die() should not be called in child\n";
325 xwrite(2, msg, sizeof(msg) - 1);
329 /* this runs in the parent process */
330 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
332 static void (*old_errfn)(const char *err, va_list params);
334 old_errfn = get_error_routine();
335 set_error_routine(fake_fatal);
336 errno = cerr->syserr;
339 case CHILD_ERR_CHDIR:
340 error_errno("exec '%s': cd to '%s' failed",
341 cmd->argv[0], cmd->dir);
344 error_errno("dup2() in child failed");
346 case CHILD_ERR_CLOSE:
347 error_errno("close() in child failed");
349 case CHILD_ERR_SIGPROCMASK:
350 error_errno("sigprocmask failed restoring signals");
352 case CHILD_ERR_ENOENT:
353 error_errno("cannot run %s", cmd->argv[0]);
355 case CHILD_ERR_SILENT:
357 case CHILD_ERR_ERRNO:
358 error_errno("cannot exec '%s'", cmd->argv[0]);
361 set_error_routine(old_errfn);
364 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
367 die("BUG: command is empty");
370 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
371 * attempt to interpret the command with 'sh'.
373 argv_array_push(out, SHELL_PATH);
376 argv_array_push(out, "git");
377 argv_array_pushv(out, cmd->argv);
378 } else if (cmd->use_shell) {
379 prepare_shell_cmd(out, cmd->argv);
381 argv_array_pushv(out, cmd->argv);
385 * If there are no '/' characters in the command then perform a path
386 * lookup and use the resolved path as the command to exec. If there
387 * are no '/' characters or if the command wasn't found in the path,
388 * have exec attempt to invoke the command directly.
390 if (!strchr(out->argv[1], '/')) {
391 char *program = locate_in_PATH(out->argv[1]);
393 free((char *)out->argv[1]);
394 out->argv[1] = program;
399 static char **prep_childenv(const char *const *deltaenv)
401 extern char **environ;
403 struct string_list env = STRING_LIST_INIT_DUP;
404 struct strbuf key = STRBUF_INIT;
405 const char *const *p;
408 /* Construct a sorted string list consisting of the current environ */
409 for (p = (const char *const *) environ; p && *p; p++) {
410 const char *equals = strchr(*p, '=');
414 strbuf_add(&key, *p, equals - *p);
415 string_list_append(&env, key.buf)->util = (void *) *p;
417 string_list_append(&env, *p)->util = (void *) *p;
420 string_list_sort(&env);
422 /* Merge in 'deltaenv' with the current environ */
423 for (p = deltaenv; p && *p; p++) {
424 const char *equals = strchr(*p, '=');
427 /* ('key=value'), insert or replace entry */
429 strbuf_add(&key, *p, equals - *p);
430 string_list_insert(&env, key.buf)->util = (void *) *p;
432 /* otherwise ('key') remove existing entry */
433 string_list_remove(&env, *p, 0);
437 /* Create an array of 'char *' to be used as the childenv */
438 childenv = xmalloc((env.nr + 1) * sizeof(char *));
439 for (i = 0; i < env.nr; i++)
440 childenv[i] = env.items[i].util;
441 childenv[env.nr] = NULL;
443 string_list_clear(&env, 0);
444 strbuf_release(&key);
448 struct atfork_state {
456 static void bug_die(int err, const char *msg)
460 die_errno("BUG: %s", msg);
465 static void atfork_prepare(struct atfork_state *as)
469 if (sigfillset(&all))
470 die_errno("sigfillset");
472 if (sigprocmask(SIG_SETMASK, &all, &as->old))
473 die_errno("sigprocmask");
475 bug_die(pthread_sigmask(SIG_SETMASK, &all, &as->old),
476 "blocking all signals");
477 bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
478 "disabling cancellation");
482 static void atfork_parent(struct atfork_state *as)
485 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
486 die_errno("sigprocmask");
488 bug_die(pthread_setcancelstate(as->cs, NULL),
489 "re-enabling cancellation");
490 bug_die(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
491 "restoring signal mask");
494 #endif /* GIT_WINDOWS_NATIVE */
496 static inline void set_cloexec(int fd)
498 int flags = fcntl(fd, F_GETFD);
500 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
503 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
505 int status, code = -1;
507 int failed_errno = 0;
509 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
515 failed_errno = errno;
516 error_errno("waitpid for %s failed", argv0);
517 } else if (waiting != pid) {
518 error("waitpid is confused (%s)", argv0);
519 } else if (WIFSIGNALED(status)) {
520 code = WTERMSIG(status);
521 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
522 error("%s died of signal %d", argv0, code);
524 * This return value is chosen so that code & 0xff
525 * mimics the exit code that a POSIX shell would report for
526 * a program that died from this signal.
529 } else if (WIFEXITED(status)) {
530 code = WEXITSTATUS(status);
532 error("waitpid is confused (%s)", argv0);
535 clear_child_for_cleanup(pid);
537 errno = failed_errno;
541 int start_command(struct child_process *cmd)
543 int need_in, need_out, need_err;
544 int fdin[2], fdout[2], fderr[2];
549 cmd->argv = cmd->args.argv;
551 cmd->env = cmd->env_array.argv;
554 * In case of errors we must keep the promise to close FDs
555 * that have been passed in via ->in and ->out.
558 need_in = !cmd->no_stdin && cmd->in < 0;
560 if (pipe(fdin) < 0) {
561 failed_errno = errno;
564 str = "standard input";
570 need_out = !cmd->no_stdout
571 && !cmd->stdout_to_stderr
574 if (pipe(fdout) < 0) {
575 failed_errno = errno;
580 str = "standard output";
586 need_err = !cmd->no_stderr && cmd->err < 0;
588 if (pipe(fderr) < 0) {
589 failed_errno = errno;
598 str = "standard error";
600 error("cannot create %s pipe for %s: %s",
601 str, cmd->argv[0], strerror(failed_errno));
602 child_process_clear(cmd);
603 errno = failed_errno;
609 trace_argv_printf(cmd->argv, "trace: run_command:");
612 #ifndef GIT_WINDOWS_NATIVE
617 struct argv_array argv = ARGV_ARRAY_INIT;
618 struct child_err cerr;
619 struct atfork_state as;
621 if (pipe(notify_pipe))
622 notify_pipe[0] = notify_pipe[1] = -1;
624 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
625 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
627 die_errno(_("open /dev/null failed"));
628 set_cloexec(null_fd);
631 prepare_cmd(&argv, cmd);
632 childenv = prep_childenv(cmd->env);
636 * NOTE: In order to prevent deadlocking when using threads special
637 * care should be taken with the function calls made in between the
638 * fork() and exec() calls. No calls should be made to functions which
639 * require acquiring a lock (e.g. malloc) as the lock could have been
640 * held by another thread at the time of forking, causing the lock to
641 * never be released in the child process. This means only
642 * Async-Signal-Safe functions are permitted in the child.
645 failed_errno = errno;
649 * Ensure the default die/error/warn routines do not get
650 * called, they can take stdio locks and malloc.
652 set_die_routine(child_die_fn);
653 set_error_routine(child_error_fn);
654 set_warn_routine(child_warn_fn);
656 close(notify_pipe[0]);
657 set_cloexec(notify_pipe[1]);
658 child_notifier = notify_pipe[1];
661 child_dup2(null_fd, 0);
663 child_dup2(fdin[0], 0);
664 child_close_pair(fdin);
665 } else if (cmd->in) {
666 child_dup2(cmd->in, 0);
667 child_close(cmd->in);
671 child_dup2(null_fd, 2);
673 child_dup2(fderr[1], 2);
674 child_close_pair(fderr);
675 } else if (cmd->err > 1) {
676 child_dup2(cmd->err, 2);
677 child_close(cmd->err);
681 child_dup2(null_fd, 1);
682 else if (cmd->stdout_to_stderr)
685 child_dup2(fdout[1], 1);
686 child_close_pair(fdout);
687 } else if (cmd->out > 1) {
688 child_dup2(cmd->out, 1);
689 child_close(cmd->out);
692 if (cmd->dir && chdir(cmd->dir))
693 child_die(CHILD_ERR_CHDIR);
696 * restore default signal handlers here, in case
697 * we catch a signal right before execve below
699 for (sig = 1; sig < NSIG; sig++) {
700 /* ignored signals get reset to SIG_DFL on execve */
701 if (signal(sig, SIG_DFL) == SIG_IGN)
702 signal(sig, SIG_IGN);
705 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
706 child_die(CHILD_ERR_SIGPROCMASK);
709 * Attempt to exec using the command and arguments starting at
710 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
711 * be used in the event exec failed with ENOEXEC at which point
712 * we will try to interpret the command using 'sh'.
714 execve(argv.argv[1], (char *const *) argv.argv + 1,
715 (char *const *) childenv);
716 if (errno == ENOEXEC)
717 execve(argv.argv[0], (char *const *) argv.argv,
718 (char *const *) childenv);
720 if (errno == ENOENT) {
721 if (cmd->silent_exec_failure)
722 child_die(CHILD_ERR_SILENT);
723 child_die(CHILD_ERR_ENOENT);
725 child_die(CHILD_ERR_ERRNO);
730 error_errno("cannot fork() for %s", cmd->argv[0]);
731 else if (cmd->clean_on_exit)
732 mark_child_for_cleanup(cmd->pid, cmd);
735 * Wait for child's exec. If the exec succeeds (or if fork()
736 * failed), EOF is seen immediately by the parent. Otherwise, the
737 * child process sends a child_err struct.
738 * Note that use of this infrastructure is completely advisory,
739 * therefore, we keep error checks minimal.
741 close(notify_pipe[1]);
742 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
744 * At this point we know that fork() succeeded, but exec()
745 * failed. Errors have been reported to our stderr.
747 wait_or_whine(cmd->pid, cmd->argv[0], 0);
748 child_err_spew(cmd, &cerr);
749 failed_errno = errno;
752 close(notify_pipe[0]);
756 argv_array_clear(&argv);
761 int fhin = 0, fhout = 1, fherr = 2;
762 const char **sargv = cmd->argv;
763 struct argv_array nargv = ARGV_ARRAY_INIT;
766 fhin = open("/dev/null", O_RDWR);
773 fherr = open("/dev/null", O_RDWR);
775 fherr = dup(fderr[1]);
776 else if (cmd->err > 2)
777 fherr = dup(cmd->err);
780 fhout = open("/dev/null", O_RDWR);
781 else if (cmd->stdout_to_stderr)
784 fhout = dup(fdout[1]);
785 else if (cmd->out > 1)
786 fhout = dup(cmd->out);
789 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
790 else if (cmd->use_shell)
791 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
793 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
794 cmd->dir, fhin, fhout, fherr);
795 failed_errno = errno;
796 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
797 error_errno("cannot spawn %s", cmd->argv[0]);
798 if (cmd->clean_on_exit && cmd->pid >= 0)
799 mark_child_for_cleanup(cmd->pid, cmd);
801 argv_array_clear(&nargv);
825 child_process_clear(cmd);
826 errno = failed_errno;
848 int finish_command(struct child_process *cmd)
850 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
851 child_process_clear(cmd);
855 int finish_command_in_signal(struct child_process *cmd)
857 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
861 int run_command(struct child_process *cmd)
865 if (cmd->out < 0 || cmd->err < 0)
866 die("BUG: run_command with a pipe can cause deadlock");
868 code = start_command(cmd);
871 return finish_command(cmd);
874 int run_command_v_opt(const char **argv, int opt)
876 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
879 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
881 struct child_process cmd = CHILD_PROCESS_INIT;
883 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
884 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
885 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
886 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
887 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
888 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
891 return run_command(&cmd);
895 static pthread_t main_thread;
896 static int main_thread_set;
897 static pthread_key_t async_key;
898 static pthread_key_t async_die_counter;
900 static void *run_thread(void *data)
902 struct async *async = data;
905 if (async->isolate_sigpipe) {
908 sigaddset(&mask, SIGPIPE);
909 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
910 ret = error("unable to block SIGPIPE in async thread");
915 pthread_setspecific(async_key, async);
916 ret = async->proc(async->proc_in, async->proc_out, async->data);
920 static NORETURN void die_async(const char *err, va_list params)
922 vreportf("fatal: ", err, params);
925 struct async *async = pthread_getspecific(async_key);
926 if (async->proc_in >= 0)
927 close(async->proc_in);
928 if (async->proc_out >= 0)
929 close(async->proc_out);
930 pthread_exit((void *)128);
936 static int async_die_is_recursing(void)
938 void *ret = pthread_getspecific(async_die_counter);
939 pthread_setspecific(async_die_counter, (void *)1);
945 if (!main_thread_set)
946 return 0; /* no asyncs started yet */
947 return !pthread_equal(main_thread, pthread_self());
950 static void NORETURN async_exit(int code)
952 pthread_exit((void *)(intptr_t)code);
958 void (**handlers)(void);
963 static int git_atexit_installed;
965 static void git_atexit_dispatch(void)
969 for (i=git_atexit_hdlrs.nr ; i ; i--)
970 git_atexit_hdlrs.handlers[i-1]();
973 static void git_atexit_clear(void)
975 free(git_atexit_hdlrs.handlers);
976 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
977 git_atexit_installed = 0;
981 int git_atexit(void (*handler)(void))
983 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
984 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
985 if (!git_atexit_installed) {
986 if (atexit(&git_atexit_dispatch))
988 git_atexit_installed = 1;
992 #define atexit git_atexit
994 static int process_is_async;
997 return process_is_async;
1000 static void NORETURN async_exit(int code)
1007 void check_pipe(int err)
1013 signal(SIGPIPE, SIG_DFL);
1015 /* Should never happen, but just in case... */
1020 int start_async(struct async *async)
1022 int need_in, need_out;
1023 int fdin[2], fdout[2];
1024 int proc_in, proc_out;
1026 need_in = async->in < 0;
1028 if (pipe(fdin) < 0) {
1031 return error_errno("cannot create pipe");
1033 async->in = fdin[1];
1036 need_out = async->out < 0;
1038 if (pipe(fdout) < 0) {
1043 return error_errno("cannot create pipe");
1045 async->out = fdout[0];
1051 proc_in = async->in;
1056 proc_out = fdout[1];
1057 else if (async->out)
1058 proc_out = async->out;
1063 /* Flush stdio before fork() to avoid cloning buffers */
1066 async->pid = fork();
1067 if (async->pid < 0) {
1068 error_errno("fork (async) failed");
1077 process_is_async = 1;
1078 exit(!!async->proc(proc_in, proc_out, async->data));
1081 mark_child_for_cleanup(async->pid, NULL);
1090 else if (async->out)
1093 if (!main_thread_set) {
1095 * We assume that the first time that start_async is called
1096 * it is from the main thread.
1098 main_thread_set = 1;
1099 main_thread = pthread_self();
1100 pthread_key_create(&async_key, NULL);
1101 pthread_key_create(&async_die_counter, NULL);
1102 set_die_routine(die_async);
1103 set_die_is_recursing_routine(async_die_is_recursing);
1107 set_cloexec(proc_in);
1109 set_cloexec(proc_out);
1110 async->proc_in = proc_in;
1111 async->proc_out = proc_out;
1113 int err = pthread_create(&async->tid, NULL, run_thread, async);
1115 error_errno("cannot create thread");
1130 else if (async->out)
1135 int finish_async(struct async *async)
1138 return wait_or_whine(async->pid, "child process", 0);
1140 void *ret = (void *)(intptr_t)(-1);
1142 if (pthread_join(async->tid, &ret))
1143 error("pthread_join failed");
1144 return (int)(intptr_t)ret;
1148 const char *find_hook(const char *name)
1150 static struct strbuf path = STRBUF_INIT;
1152 strbuf_reset(&path);
1153 strbuf_git_path(&path, "hooks/%s", name);
1154 if (access(path.buf, X_OK) < 0) {
1155 #ifdef STRIP_EXTENSION
1156 strbuf_addstr(&path, STRIP_EXTENSION);
1157 if (access(path.buf, X_OK) >= 0)
1165 int run_hook_ve(const char *const *env, const char *name, va_list args)
1167 struct child_process hook = CHILD_PROCESS_INIT;
1170 p = find_hook(name);
1174 argv_array_push(&hook.args, p);
1175 while ((p = va_arg(args, const char *)))
1176 argv_array_push(&hook.args, p);
1179 hook.stdout_to_stderr = 1;
1181 return run_command(&hook);
1184 int run_hook_le(const char *const *env, const char *name, ...)
1189 va_start(args, name);
1190 ret = run_hook_ve(env, name, args);
1197 /* initialized by caller */
1199 int type; /* POLLOUT or POLLIN */
1211 /* returned by pump_io */
1212 int error; /* 0 for success, otherwise errno */
1218 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1223 for (i = 0; i < nr; i++) {
1224 struct io_pump *io = &slots[i];
1227 pfd[pollsize].fd = io->fd;
1228 pfd[pollsize].events = io->type;
1229 io->pfd = &pfd[pollsize++];
1235 if (poll(pfd, pollsize, -1) < 0) {
1238 die_errno("poll failed");
1241 for (i = 0; i < nr; i++) {
1242 struct io_pump *io = &slots[i];
1247 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1250 if (io->type == POLLOUT) {
1251 ssize_t len = xwrite(io->fd,
1252 io->u.out.buf, io->u.out.len);
1258 io->u.out.buf += len;
1259 io->u.out.len -= len;
1260 if (!io->u.out.len) {
1267 if (io->type == POLLIN) {
1268 ssize_t len = strbuf_read_once(io->u.in.buf,
1269 io->fd, io->u.in.hint);
1282 static int pump_io(struct io_pump *slots, int nr)
1287 for (i = 0; i < nr; i++)
1290 ALLOC_ARRAY(pfd, nr);
1291 while (pump_io_round(slots, nr, pfd))
1295 /* There may be multiple errno values, so just pick the first. */
1296 for (i = 0; i < nr; i++) {
1297 if (slots[i].error) {
1298 errno = slots[i].error;
1306 int pipe_command(struct child_process *cmd,
1307 const char *in, size_t in_len,
1308 struct strbuf *out, size_t out_hint,
1309 struct strbuf *err, size_t err_hint)
1311 struct io_pump io[3];
1321 if (start_command(cmd) < 0)
1325 io[nr].fd = cmd->in;
1326 io[nr].type = POLLOUT;
1327 io[nr].u.out.buf = in;
1328 io[nr].u.out.len = in_len;
1332 io[nr].fd = cmd->out;
1333 io[nr].type = POLLIN;
1334 io[nr].u.in.buf = out;
1335 io[nr].u.in.hint = out_hint;
1339 io[nr].fd = cmd->err;
1340 io[nr].type = POLLIN;
1341 io[nr].u.in.buf = err;
1342 io[nr].u.in.hint = err_hint;
1346 if (pump_io(io, nr) < 0) {
1347 finish_command(cmd); /* throw away exit code */
1351 return finish_command(cmd);
1357 GIT_CP_WAIT_CLEANUP,
1360 struct parallel_processes {
1366 get_next_task_fn get_next_task;
1367 start_failure_fn start_failure;
1368 task_finished_fn task_finished;
1371 enum child_state state;
1372 struct child_process process;
1377 * The struct pollfd is logically part of *children,
1378 * but the system call expects it as its own array.
1382 unsigned shutdown : 1;
1385 struct strbuf buffered_output; /* of finished children */
1388 static int default_start_failure(struct strbuf *out,
1395 static int default_task_finished(int result,
1403 static void kill_children(struct parallel_processes *pp, int signo)
1405 int i, n = pp->max_processes;
1407 for (i = 0; i < n; i++)
1408 if (pp->children[i].state == GIT_CP_WORKING)
1409 kill(pp->children[i].process.pid, signo);
1412 static struct parallel_processes *pp_for_signal;
1414 static void handle_children_on_signal(int signo)
1416 kill_children(pp_for_signal, signo);
1417 sigchain_pop(signo);
1421 static void pp_init(struct parallel_processes *pp,
1423 get_next_task_fn get_next_task,
1424 start_failure_fn start_failure,
1425 task_finished_fn task_finished,
1433 pp->max_processes = n;
1435 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1439 die("BUG: you need to specify a get_next_task function");
1440 pp->get_next_task = get_next_task;
1442 pp->start_failure = start_failure ? start_failure : default_start_failure;
1443 pp->task_finished = task_finished ? task_finished : default_task_finished;
1445 pp->nr_processes = 0;
1446 pp->output_owner = 0;
1448 pp->children = xcalloc(n, sizeof(*pp->children));
1449 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1450 strbuf_init(&pp->buffered_output, 0);
1452 for (i = 0; i < n; i++) {
1453 strbuf_init(&pp->children[i].err, 0);
1454 child_process_init(&pp->children[i].process);
1455 pp->pfd[i].events = POLLIN | POLLHUP;
1460 sigchain_push_common(handle_children_on_signal);
1463 static void pp_cleanup(struct parallel_processes *pp)
1467 trace_printf("run_processes_parallel: done");
1468 for (i = 0; i < pp->max_processes; i++) {
1469 strbuf_release(&pp->children[i].err);
1470 child_process_clear(&pp->children[i].process);
1477 * When get_next_task added messages to the buffer in its last
1478 * iteration, the buffered output is non empty.
1480 strbuf_write(&pp->buffered_output, stderr);
1481 strbuf_release(&pp->buffered_output);
1483 sigchain_pop_common();
1487 * 0 if a new task was started.
1488 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1489 * problem with starting a new command)
1490 * <0 no new job was started, user wishes to shutdown early. Use negative code
1491 * to signal the children.
1493 static int pp_start_one(struct parallel_processes *pp)
1497 for (i = 0; i < pp->max_processes; i++)
1498 if (pp->children[i].state == GIT_CP_FREE)
1500 if (i == pp->max_processes)
1501 die("BUG: bookkeeping is hard");
1503 code = pp->get_next_task(&pp->children[i].process,
1504 &pp->children[i].err,
1506 &pp->children[i].data);
1508 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1509 strbuf_reset(&pp->children[i].err);
1512 pp->children[i].process.err = -1;
1513 pp->children[i].process.stdout_to_stderr = 1;
1514 pp->children[i].process.no_stdin = 1;
1516 if (start_command(&pp->children[i].process)) {
1517 code = pp->start_failure(&pp->children[i].err,
1519 &pp->children[i].data);
1520 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1521 strbuf_reset(&pp->children[i].err);
1528 pp->children[i].state = GIT_CP_WORKING;
1529 pp->pfd[i].fd = pp->children[i].process.err;
1533 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1537 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1544 /* Buffer output from all pipes. */
1545 for (i = 0; i < pp->max_processes; i++) {
1546 if (pp->children[i].state == GIT_CP_WORKING &&
1547 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1548 int n = strbuf_read_once(&pp->children[i].err,
1549 pp->children[i].process.err, 0);
1551 close(pp->children[i].process.err);
1552 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1554 if (errno != EAGAIN)
1560 static void pp_output(struct parallel_processes *pp)
1562 int i = pp->output_owner;
1563 if (pp->children[i].state == GIT_CP_WORKING &&
1564 pp->children[i].err.len) {
1565 strbuf_write(&pp->children[i].err, stderr);
1566 strbuf_reset(&pp->children[i].err);
1570 static int pp_collect_finished(struct parallel_processes *pp)
1573 int n = pp->max_processes;
1576 while (pp->nr_processes > 0) {
1577 for (i = 0; i < pp->max_processes; i++)
1578 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1580 if (i == pp->max_processes)
1583 code = finish_command(&pp->children[i].process);
1585 code = pp->task_finished(code,
1586 &pp->children[i].err, pp->data,
1587 &pp->children[i].data);
1595 pp->children[i].state = GIT_CP_FREE;
1597 child_process_init(&pp->children[i].process);
1599 if (i != pp->output_owner) {
1600 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1601 strbuf_reset(&pp->children[i].err);
1603 strbuf_write(&pp->children[i].err, stderr);
1604 strbuf_reset(&pp->children[i].err);
1606 /* Output all other finished child processes */
1607 strbuf_write(&pp->buffered_output, stderr);
1608 strbuf_reset(&pp->buffered_output);
1611 * Pick next process to output live.
1613 * For now we pick it randomly by doing a round
1614 * robin. Later we may want to pick the one with
1615 * the most output or the longest or shortest
1616 * running process time.
1618 for (i = 0; i < n; i++)
1619 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1621 pp->output_owner = (pp->output_owner + i) % n;
1627 int run_processes_parallel(int n,
1628 get_next_task_fn get_next_task,
1629 start_failure_fn start_failure,
1630 task_finished_fn task_finished,
1634 int output_timeout = 100;
1636 struct parallel_processes pp;
1638 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1641 i < spawn_cap && !pp.shutdown &&
1642 pp.nr_processes < pp.max_processes;
1644 code = pp_start_one(&pp);
1649 kill_children(&pp, -code);
1653 if (!pp.nr_processes)
1655 pp_buffer_stderr(&pp, output_timeout);
1657 code = pp_collect_finished(&pp);
1661 kill_children(&pp, -code);