gitfaq: add documentation on proxies
[git.git] / run-command.c
blobd9f80fabe6e77f7fce219ed575e607d02aacb224
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "run-command.h"
5 #include "environment.h"
6 #include "exec-cmd.h"
7 #include "gettext.h"
8 #include "sigchain.h"
9 #include "strvec.h"
10 #include "symlinks.h"
11 #include "thread-utils.h"
12 #include "strbuf.h"
13 #include "string-list.h"
14 #include "trace.h"
15 #include "trace2.h"
16 #include "quote.h"
17 #include "config.h"
18 #include "packfile.h"
19 #include "compat/nonblock.h"
21 void child_process_init(struct child_process *child)
23 struct child_process blank = CHILD_PROCESS_INIT;
24 memcpy(child, &blank, sizeof(*child));
27 void child_process_clear(struct child_process *child)
29 strvec_clear(&child->args);
30 strvec_clear(&child->env);
33 struct child_to_clean {
34 pid_t pid;
35 struct child_process *process;
36 struct child_to_clean *next;
38 static struct child_to_clean *children_to_clean;
39 static int installed_child_cleanup_handler;
41 static void cleanup_children(int sig, int in_signal)
43 struct child_to_clean *children_to_wait_for = NULL;
45 while (children_to_clean) {
46 struct child_to_clean *p = children_to_clean;
47 children_to_clean = p->next;
49 if (p->process && !in_signal) {
50 struct child_process *process = p->process;
51 if (process->clean_on_exit_handler) {
52 trace_printf(
53 "trace: run_command: running exit handler for pid %"
54 PRIuMAX, (uintmax_t)p->pid
56 process->clean_on_exit_handler(process);
60 kill(p->pid, sig);
62 if (p->process && p->process->wait_after_clean) {
63 p->next = children_to_wait_for;
64 children_to_wait_for = p;
65 } else {
66 if (!in_signal)
67 free(p);
71 while (children_to_wait_for) {
72 struct child_to_clean *p = children_to_wait_for;
73 children_to_wait_for = p->next;
75 while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
76 ; /* spin waiting for process exit or error */
78 if (!in_signal)
79 free(p);
83 static void cleanup_children_on_signal(int sig)
85 cleanup_children(sig, 1);
86 sigchain_pop(sig);
87 raise(sig);
90 static void cleanup_children_on_exit(void)
92 cleanup_children(SIGTERM, 0);
95 static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
97 struct child_to_clean *p = xmalloc(sizeof(*p));
98 p->pid = pid;
99 p->process = process;
100 p->next = children_to_clean;
101 children_to_clean = p;
103 if (!installed_child_cleanup_handler) {
104 atexit(cleanup_children_on_exit);
105 sigchain_push_common(cleanup_children_on_signal);
106 installed_child_cleanup_handler = 1;
110 static void clear_child_for_cleanup(pid_t pid)
112 struct child_to_clean **pp;
114 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
115 struct child_to_clean *clean_me = *pp;
117 if (clean_me->pid == pid) {
118 *pp = clean_me->next;
119 free(clean_me);
120 return;
125 static inline void close_pair(int fd[2])
127 close(fd[0]);
128 close(fd[1]);
131 int is_executable(const char *name)
133 struct stat st;
135 if (stat(name, &st) || /* stat, not lstat */
136 !S_ISREG(st.st_mode))
137 return 0;
139 #if defined(GIT_WINDOWS_NATIVE)
141 * On Windows there is no executable bit. The file extension
142 * indicates whether it can be run as an executable, and Git
143 * has special-handling to detect scripts and launch them
144 * through the indicated script interpreter. We test for the
145 * file extension first because virus scanners may make
146 * it quite expensive to open many files.
148 if (ends_with(name, ".exe"))
149 return S_IXUSR;
153 * Now that we know it does not have an executable extension,
154 * peek into the file instead.
156 char buf[3] = { 0 };
157 int n;
158 int fd = open(name, O_RDONLY);
159 st.st_mode &= ~S_IXUSR;
160 if (fd >= 0) {
161 n = read(fd, buf, 2);
162 if (n == 2)
163 /* look for a she-bang */
164 if (!strcmp(buf, "#!"))
165 st.st_mode |= S_IXUSR;
166 close(fd);
169 #endif
170 return st.st_mode & S_IXUSR;
173 #ifndef locate_in_PATH
175 * Search $PATH for a command. This emulates the path search that
176 * execvp would perform, without actually executing the command so it
177 * can be used before fork() to prepare to run a command using
178 * execve() or after execvp() to diagnose why it failed.
180 * The caller should ensure that file contains no directory
181 * separators.
183 * Returns the path to the command, as found in $PATH or NULL if the
184 * command could not be found. The caller inherits ownership of the memory
185 * used to store the resultant path.
187 * This should not be used on Windows, where the $PATH search rules
188 * are more complicated (e.g., a search for "foo" should find
189 * "foo.exe").
191 static char *locate_in_PATH(const char *file)
193 const char *p = getenv("PATH");
194 struct strbuf buf = STRBUF_INIT;
196 if (!p || !*p)
197 return NULL;
199 while (1) {
200 const char *end = strchrnul(p, ':');
202 strbuf_reset(&buf);
204 /* POSIX specifies an empty entry as the current directory. */
205 if (end != p) {
206 strbuf_add(&buf, p, end - p);
207 strbuf_addch(&buf, '/');
209 strbuf_addstr(&buf, file);
211 if (is_executable(buf.buf))
212 return strbuf_detach(&buf, NULL);
214 if (!*end)
215 break;
216 p = end + 1;
219 strbuf_release(&buf);
220 return NULL;
222 #endif
224 int exists_in_PATH(const char *command)
226 char *r = locate_in_PATH(command);
227 int found = r != NULL;
228 free(r);
229 return found;
232 int sane_execvp(const char *file, char * const argv[])
234 #ifndef GIT_WINDOWS_NATIVE
236 * execvp() doesn't return, so we all we can do is tell trace2
237 * what we are about to do and let it leave a hint in the log
238 * (unless of course the execvp() fails).
240 * we skip this for Windows because the compat layer already
241 * has to emulate the execvp() call anyway.
243 int exec_id = trace2_exec(file, (const char **)argv);
244 #endif
246 if (!execvp(file, argv))
247 return 0; /* cannot happen ;-) */
249 #ifndef GIT_WINDOWS_NATIVE
251 int ec = errno;
252 trace2_exec_result(exec_id, ec);
253 errno = ec;
255 #endif
258 * When a command can't be found because one of the directories
259 * listed in $PATH is unsearchable, execvp reports EACCES, but
260 * careful usability testing (read: analysis of occasional bug
261 * reports) reveals that "No such file or directory" is more
262 * intuitive.
264 * We avoid commands with "/", because execvp will not do $PATH
265 * lookups in that case.
267 * The reassignment of EACCES to errno looks like a no-op below,
268 * but we need to protect against exists_in_PATH overwriting errno.
270 if (errno == EACCES && !strchr(file, '/'))
271 errno = exists_in_PATH(file) ? EACCES : ENOENT;
272 else if (errno == ENOTDIR && !strchr(file, '/'))
273 errno = ENOENT;
274 return -1;
277 static const char **prepare_shell_cmd(struct strvec *out, const char **argv)
279 if (!argv[0])
280 BUG("shell command is empty");
282 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
283 #ifndef GIT_WINDOWS_NATIVE
284 strvec_push(out, SHELL_PATH);
285 #else
286 strvec_push(out, "sh");
287 #endif
288 strvec_push(out, "-c");
291 * If we have no extra arguments, we do not even need to
292 * bother with the "$@" magic.
294 if (!argv[1])
295 strvec_push(out, argv[0]);
296 else
297 strvec_pushf(out, "%s \"$@\"", argv[0]);
300 strvec_pushv(out, argv);
301 return out->v;
304 #ifndef GIT_WINDOWS_NATIVE
305 static int child_notifier = -1;
307 enum child_errcode {
308 CHILD_ERR_CHDIR,
309 CHILD_ERR_DUP2,
310 CHILD_ERR_CLOSE,
311 CHILD_ERR_SIGPROCMASK,
312 CHILD_ERR_SILENT,
313 CHILD_ERR_ERRNO
316 struct child_err {
317 enum child_errcode err;
318 int syserr; /* errno */
321 static void child_die(enum child_errcode err)
323 struct child_err buf;
325 buf.err = err;
326 buf.syserr = errno;
328 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
329 xwrite(child_notifier, &buf, sizeof(buf));
330 _exit(1);
333 static void child_dup2(int fd, int to)
335 if (dup2(fd, to) < 0)
336 child_die(CHILD_ERR_DUP2);
339 static void child_close(int fd)
341 if (close(fd))
342 child_die(CHILD_ERR_CLOSE);
345 static void child_close_pair(int fd[2])
347 child_close(fd[0]);
348 child_close(fd[1]);
351 static void child_error_fn(const char *err UNUSED, va_list params UNUSED)
353 const char msg[] = "error() should not be called in child\n";
354 xwrite(2, msg, sizeof(msg) - 1);
357 static void child_warn_fn(const char *err UNUSED, va_list params UNUSED)
359 const char msg[] = "warn() should not be called in child\n";
360 xwrite(2, msg, sizeof(msg) - 1);
363 static void NORETURN child_die_fn(const char *err UNUSED, va_list params UNUSED)
365 const char msg[] = "die() should not be called in child\n";
366 xwrite(2, msg, sizeof(msg) - 1);
367 _exit(2);
370 /* this runs in the parent process */
371 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
373 static void (*old_errfn)(const char *err, va_list params);
374 report_fn die_message_routine = get_die_message_routine();
376 old_errfn = get_error_routine();
377 set_error_routine(die_message_routine);
378 errno = cerr->syserr;
380 switch (cerr->err) {
381 case CHILD_ERR_CHDIR:
382 error_errno("exec '%s': cd to '%s' failed",
383 cmd->args.v[0], cmd->dir);
384 break;
385 case CHILD_ERR_DUP2:
386 error_errno("dup2() in child failed");
387 break;
388 case CHILD_ERR_CLOSE:
389 error_errno("close() in child failed");
390 break;
391 case CHILD_ERR_SIGPROCMASK:
392 error_errno("sigprocmask failed restoring signals");
393 break;
394 case CHILD_ERR_SILENT:
395 break;
396 case CHILD_ERR_ERRNO:
397 error_errno("cannot exec '%s'", cmd->args.v[0]);
398 break;
400 set_error_routine(old_errfn);
403 static int prepare_cmd(struct strvec *out, const struct child_process *cmd)
405 if (!cmd->args.v[0])
406 BUG("command is empty");
409 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
410 * attempt to interpret the command with 'sh'.
412 strvec_push(out, SHELL_PATH);
414 if (cmd->git_cmd) {
415 prepare_git_cmd(out, cmd->args.v);
416 } else if (cmd->use_shell) {
417 prepare_shell_cmd(out, cmd->args.v);
418 } else {
419 strvec_pushv(out, cmd->args.v);
423 * If there are no dir separator characters in the command then perform
424 * a path lookup and use the resolved path as the command to exec. If
425 * there are dir separator characters, we have exec attempt to invoke
426 * the command directly.
428 if (!has_dir_sep(out->v[1])) {
429 char *program = locate_in_PATH(out->v[1]);
430 if (program) {
431 free((char *)out->v[1]);
432 out->v[1] = program;
433 } else {
434 strvec_clear(out);
435 errno = ENOENT;
436 return -1;
440 return 0;
443 static char **prep_childenv(const char *const *deltaenv)
445 extern char **environ;
446 char **childenv;
447 struct string_list env = STRING_LIST_INIT_DUP;
448 struct strbuf key = STRBUF_INIT;
449 const char *const *p;
450 int i;
452 /* Construct a sorted string list consisting of the current environ */
453 for (p = (const char *const *) environ; p && *p; p++) {
454 const char *equals = strchr(*p, '=');
456 if (equals) {
457 strbuf_reset(&key);
458 strbuf_add(&key, *p, equals - *p);
459 string_list_append(&env, key.buf)->util = (void *) *p;
460 } else {
461 string_list_append(&env, *p)->util = (void *) *p;
464 string_list_sort(&env);
466 /* Merge in 'deltaenv' with the current environ */
467 for (p = deltaenv; p && *p; p++) {
468 const char *equals = strchr(*p, '=');
470 if (equals) {
471 /* ('key=value'), insert or replace entry */
472 strbuf_reset(&key);
473 strbuf_add(&key, *p, equals - *p);
474 string_list_insert(&env, key.buf)->util = (void *) *p;
475 } else {
476 /* otherwise ('key') remove existing entry */
477 string_list_remove(&env, *p, 0);
481 /* Create an array of 'char *' to be used as the childenv */
482 ALLOC_ARRAY(childenv, env.nr + 1);
483 for (i = 0; i < env.nr; i++)
484 childenv[i] = env.items[i].util;
485 childenv[env.nr] = NULL;
487 string_list_clear(&env, 0);
488 strbuf_release(&key);
489 return childenv;
492 struct atfork_state {
493 #ifndef NO_PTHREADS
494 int cs;
495 #endif
496 sigset_t old;
499 #define CHECK_BUG(err, msg) \
500 do { \
501 int e = (err); \
502 if (e) \
503 BUG("%s: %s", msg, strerror(e)); \
504 } while(0)
506 static void atfork_prepare(struct atfork_state *as)
508 sigset_t all;
510 if (sigfillset(&all))
511 die_errno("sigfillset");
512 #ifdef NO_PTHREADS
513 if (sigprocmask(SIG_SETMASK, &all, &as->old))
514 die_errno("sigprocmask");
515 #else
516 CHECK_BUG(pthread_sigmask(SIG_SETMASK, &all, &as->old),
517 "blocking all signals");
518 CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
519 "disabling cancellation");
520 #endif
523 static void atfork_parent(struct atfork_state *as)
525 #ifdef NO_PTHREADS
526 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
527 die_errno("sigprocmask");
528 #else
529 CHECK_BUG(pthread_setcancelstate(as->cs, NULL),
530 "re-enabling cancellation");
531 CHECK_BUG(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
532 "restoring signal mask");
533 #endif
535 #endif /* GIT_WINDOWS_NATIVE */
537 static inline void set_cloexec(int fd)
539 int flags = fcntl(fd, F_GETFD);
540 if (flags >= 0)
541 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
544 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
546 int status, code = -1;
547 pid_t waiting;
548 int failed_errno = 0;
550 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
551 ; /* nothing */
553 if (waiting < 0) {
554 failed_errno = errno;
555 if (!in_signal)
556 error_errno("waitpid for %s failed", argv0);
557 } else if (waiting != pid) {
558 if (!in_signal)
559 error("waitpid is confused (%s)", argv0);
560 } else if (WIFSIGNALED(status)) {
561 code = WTERMSIG(status);
562 if (!in_signal && code != SIGINT && code != SIGQUIT && code != SIGPIPE)
563 error("%s died of signal %d", argv0, code);
565 * This return value is chosen so that code & 0xff
566 * mimics the exit code that a POSIX shell would report for
567 * a program that died from this signal.
569 code += 128;
570 } else if (WIFEXITED(status)) {
571 code = WEXITSTATUS(status);
572 } else {
573 if (!in_signal)
574 error("waitpid is confused (%s)", argv0);
577 if (!in_signal)
578 clear_child_for_cleanup(pid);
580 errno = failed_errno;
581 return code;
584 static void trace_add_env(struct strbuf *dst, const char *const *deltaenv)
586 struct string_list envs = STRING_LIST_INIT_DUP;
587 const char *const *e;
588 int i;
589 int printed_unset = 0;
591 /* Last one wins, see run-command.c:prep_childenv() for context */
592 for (e = deltaenv; e && *e; e++) {
593 struct strbuf key = STRBUF_INIT;
594 char *equals = strchr(*e, '=');
596 if (equals) {
597 strbuf_add(&key, *e, equals - *e);
598 string_list_insert(&envs, key.buf)->util = equals + 1;
599 } else {
600 string_list_insert(&envs, *e)->util = NULL;
602 strbuf_release(&key);
605 /* "unset X Y...;" */
606 for (i = 0; i < envs.nr; i++) {
607 const char *var = envs.items[i].string;
608 const char *val = envs.items[i].util;
610 if (val || !getenv(var))
611 continue;
613 if (!printed_unset) {
614 strbuf_addstr(dst, " unset");
615 printed_unset = 1;
617 strbuf_addf(dst, " %s", var);
619 if (printed_unset)
620 strbuf_addch(dst, ';');
622 /* ... followed by "A=B C=D ..." */
623 for (i = 0; i < envs.nr; i++) {
624 const char *var = envs.items[i].string;
625 const char *val = envs.items[i].util;
626 const char *oldval;
628 if (!val)
629 continue;
631 oldval = getenv(var);
632 if (oldval && !strcmp(val, oldval))
633 continue;
635 strbuf_addf(dst, " %s=", var);
636 sq_quote_buf_pretty(dst, val);
638 string_list_clear(&envs, 0);
641 static void trace_run_command(const struct child_process *cp)
643 struct strbuf buf = STRBUF_INIT;
645 if (!trace_want(&trace_default_key))
646 return;
648 strbuf_addstr(&buf, "trace: run_command:");
649 if (cp->dir) {
650 strbuf_addstr(&buf, " cd ");
651 sq_quote_buf_pretty(&buf, cp->dir);
652 strbuf_addch(&buf, ';');
654 trace_add_env(&buf, cp->env.v);
655 if (cp->git_cmd)
656 strbuf_addstr(&buf, " git");
657 sq_quote_argv_pretty(&buf, cp->args.v);
659 trace_printf("%s", buf.buf);
660 strbuf_release(&buf);
663 int start_command(struct child_process *cmd)
665 int need_in, need_out, need_err;
666 int fdin[2], fdout[2], fderr[2];
667 int failed_errno;
668 const char *str;
671 * In case of errors we must keep the promise to close FDs
672 * that have been passed in via ->in and ->out.
675 need_in = !cmd->no_stdin && cmd->in < 0;
676 if (need_in) {
677 if (pipe(fdin) < 0) {
678 failed_errno = errno;
679 if (cmd->out > 0)
680 close(cmd->out);
681 str = "standard input";
682 goto fail_pipe;
684 cmd->in = fdin[1];
687 need_out = !cmd->no_stdout
688 && !cmd->stdout_to_stderr
689 && cmd->out < 0;
690 if (need_out) {
691 if (pipe(fdout) < 0) {
692 failed_errno = errno;
693 if (need_in)
694 close_pair(fdin);
695 else if (cmd->in)
696 close(cmd->in);
697 str = "standard output";
698 goto fail_pipe;
700 cmd->out = fdout[0];
703 need_err = !cmd->no_stderr && cmd->err < 0;
704 if (need_err) {
705 if (pipe(fderr) < 0) {
706 failed_errno = errno;
707 if (need_in)
708 close_pair(fdin);
709 else if (cmd->in)
710 close(cmd->in);
711 if (need_out)
712 close_pair(fdout);
713 else if (cmd->out)
714 close(cmd->out);
715 str = "standard error";
716 fail_pipe:
717 error("cannot create %s pipe for %s: %s",
718 str, cmd->args.v[0], strerror(failed_errno));
719 child_process_clear(cmd);
720 errno = failed_errno;
721 return -1;
723 cmd->err = fderr[0];
726 trace2_child_start(cmd);
727 trace_run_command(cmd);
729 fflush(NULL);
731 if (cmd->close_object_store)
732 close_object_store(the_repository->objects);
734 #ifndef GIT_WINDOWS_NATIVE
736 int notify_pipe[2];
737 int null_fd = -1;
738 char **childenv;
739 struct strvec argv = STRVEC_INIT;
740 struct child_err cerr;
741 struct atfork_state as;
743 if (prepare_cmd(&argv, cmd) < 0) {
744 failed_errno = errno;
745 cmd->pid = -1;
746 if (!cmd->silent_exec_failure)
747 error_errno("cannot run %s", cmd->args.v[0]);
748 goto end_of_spawn;
751 trace_argv_printf(&argv.v[1], "trace: start_command:");
753 if (pipe(notify_pipe))
754 notify_pipe[0] = notify_pipe[1] = -1;
756 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
757 null_fd = xopen("/dev/null", O_RDWR | O_CLOEXEC);
758 set_cloexec(null_fd);
761 childenv = prep_childenv(cmd->env.v);
762 atfork_prepare(&as);
765 * NOTE: In order to prevent deadlocking when using threads special
766 * care should be taken with the function calls made in between the
767 * fork() and exec() calls. No calls should be made to functions which
768 * require acquiring a lock (e.g. malloc) as the lock could have been
769 * held by another thread at the time of forking, causing the lock to
770 * never be released in the child process. This means only
771 * Async-Signal-Safe functions are permitted in the child.
773 cmd->pid = fork();
774 failed_errno = errno;
775 if (!cmd->pid) {
776 int sig;
778 * Ensure the default die/error/warn routines do not get
779 * called, they can take stdio locks and malloc.
781 set_die_routine(child_die_fn);
782 set_error_routine(child_error_fn);
783 set_warn_routine(child_warn_fn);
785 close(notify_pipe[0]);
786 set_cloexec(notify_pipe[1]);
787 child_notifier = notify_pipe[1];
789 if (cmd->no_stdin)
790 child_dup2(null_fd, 0);
791 else if (need_in) {
792 child_dup2(fdin[0], 0);
793 child_close_pair(fdin);
794 } else if (cmd->in) {
795 child_dup2(cmd->in, 0);
796 child_close(cmd->in);
799 if (cmd->no_stderr)
800 child_dup2(null_fd, 2);
801 else if (need_err) {
802 child_dup2(fderr[1], 2);
803 child_close_pair(fderr);
804 } else if (cmd->err > 1) {
805 child_dup2(cmd->err, 2);
806 child_close(cmd->err);
809 if (cmd->no_stdout)
810 child_dup2(null_fd, 1);
811 else if (cmd->stdout_to_stderr)
812 child_dup2(2, 1);
813 else if (need_out) {
814 child_dup2(fdout[1], 1);
815 child_close_pair(fdout);
816 } else if (cmd->out > 1) {
817 child_dup2(cmd->out, 1);
818 child_close(cmd->out);
821 if (cmd->dir && chdir(cmd->dir))
822 child_die(CHILD_ERR_CHDIR);
825 * restore default signal handlers here, in case
826 * we catch a signal right before execve below
828 for (sig = 1; sig < NSIG; sig++) {
829 /* ignored signals get reset to SIG_DFL on execve */
830 if (signal(sig, SIG_DFL) == SIG_IGN)
831 signal(sig, SIG_IGN);
834 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
835 child_die(CHILD_ERR_SIGPROCMASK);
838 * Attempt to exec using the command and arguments starting at
839 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
840 * be used in the event exec failed with ENOEXEC at which point
841 * we will try to interpret the command using 'sh'.
843 execve(argv.v[1], (char *const *) argv.v + 1,
844 (char *const *) childenv);
845 if (errno == ENOEXEC)
846 execve(argv.v[0], (char *const *) argv.v,
847 (char *const *) childenv);
849 if (cmd->silent_exec_failure && errno == ENOENT)
850 child_die(CHILD_ERR_SILENT);
851 child_die(CHILD_ERR_ERRNO);
853 atfork_parent(&as);
854 if (cmd->pid < 0)
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;
875 cmd->pid = -1;
877 close(notify_pipe[0]);
879 if (null_fd >= 0)
880 close(null_fd);
881 strvec_clear(&argv);
882 free(childenv);
884 end_of_spawn:
886 #else
888 int fhin = 0, fhout = 1, fherr = 2;
889 const char **sargv = cmd->args.v;
890 struct strvec nargv = STRVEC_INIT;
892 if (cmd->no_stdin)
893 fhin = open("/dev/null", O_RDWR);
894 else if (need_in)
895 fhin = dup(fdin[0]);
896 else if (cmd->in)
897 fhin = dup(cmd->in);
899 if (cmd->no_stderr)
900 fherr = open("/dev/null", O_RDWR);
901 else if (need_err)
902 fherr = dup(fderr[1]);
903 else if (cmd->err > 2)
904 fherr = dup(cmd->err);
906 if (cmd->no_stdout)
907 fhout = open("/dev/null", O_RDWR);
908 else if (cmd->stdout_to_stderr)
909 fhout = dup(fherr);
910 else if (need_out)
911 fhout = dup(fdout[1]);
912 else if (cmd->out > 1)
913 fhout = dup(cmd->out);
915 if (cmd->git_cmd)
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 trace_argv_printf(cmd->args.v, "trace: start_command:");
921 cmd->pid = mingw_spawnvpe(cmd->args.v[0], cmd->args.v,
922 (char**) cmd->env.v,
923 cmd->dir, fhin, fhout, fherr);
924 failed_errno = errno;
925 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
926 error_errno("cannot spawn %s", cmd->args.v[0]);
927 if (cmd->clean_on_exit && cmd->pid >= 0)
928 mark_child_for_cleanup(cmd->pid, cmd);
930 strvec_clear(&nargv);
931 cmd->args.v = sargv;
932 if (fhin != 0)
933 close(fhin);
934 if (fhout != 1)
935 close(fhout);
936 if (fherr != 2)
937 close(fherr);
939 #endif
941 if (cmd->pid < 0) {
942 trace2_child_exit(cmd, -1);
944 if (need_in)
945 close_pair(fdin);
946 else if (cmd->in)
947 close(cmd->in);
948 if (need_out)
949 close_pair(fdout);
950 else if (cmd->out)
951 close(cmd->out);
952 if (need_err)
953 close_pair(fderr);
954 else if (cmd->err)
955 close(cmd->err);
956 child_process_clear(cmd);
957 errno = failed_errno;
958 return -1;
961 if (need_in)
962 close(fdin[0]);
963 else if (cmd->in)
964 close(cmd->in);
966 if (need_out)
967 close(fdout[1]);
968 else if (cmd->out)
969 close(cmd->out);
971 if (need_err)
972 close(fderr[1]);
973 else if (cmd->err)
974 close(cmd->err);
976 return 0;
979 int finish_command(struct child_process *cmd)
981 int ret = wait_or_whine(cmd->pid, cmd->args.v[0], 0);
982 trace2_child_exit(cmd, ret);
983 child_process_clear(cmd);
984 invalidate_lstat_cache();
985 return ret;
988 int finish_command_in_signal(struct child_process *cmd)
990 int ret = wait_or_whine(cmd->pid, cmd->args.v[0], 1);
991 if (ret != -1)
992 trace2_child_exit(cmd, ret);
993 return ret;
997 int run_command(struct child_process *cmd)
999 int code;
1001 if (cmd->out < 0 || cmd->err < 0)
1002 BUG("run_command with a pipe can cause deadlock");
1004 code = start_command(cmd);
1005 if (code)
1006 return code;
1007 return finish_command(cmd);
1010 #ifndef NO_PTHREADS
1011 static pthread_t main_thread;
1012 static int main_thread_set;
1013 static pthread_key_t async_key;
1014 static pthread_key_t async_die_counter;
1016 static void *run_thread(void *data)
1018 struct async *async = data;
1019 intptr_t ret;
1021 if (async->isolate_sigpipe) {
1022 sigset_t mask;
1023 sigemptyset(&mask);
1024 sigaddset(&mask, SIGPIPE);
1025 if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) {
1026 ret = error("unable to block SIGPIPE in async thread");
1027 return (void *)ret;
1031 pthread_setspecific(async_key, async);
1032 ret = async->proc(async->proc_in, async->proc_out, async->data);
1033 return (void *)ret;
1036 static NORETURN void die_async(const char *err, va_list params)
1038 report_fn die_message_fn = get_die_message_routine();
1040 die_message_fn(err, params);
1042 if (in_async()) {
1043 struct async *async = pthread_getspecific(async_key);
1044 if (async->proc_in >= 0)
1045 close(async->proc_in);
1046 if (async->proc_out >= 0)
1047 close(async->proc_out);
1048 pthread_exit((void *)128);
1051 exit(128);
1054 static int async_die_is_recursing(void)
1056 void *ret = pthread_getspecific(async_die_counter);
1057 pthread_setspecific(async_die_counter, &async_die_counter); /* set to any non-NULL valid pointer */
1058 return ret != NULL;
1061 int in_async(void)
1063 if (!main_thread_set)
1064 return 0; /* no asyncs started yet */
1065 return !pthread_equal(main_thread, pthread_self());
1068 static void NORETURN async_exit(int code)
1070 pthread_exit((void *)(intptr_t)code);
1073 #else
1075 static struct {
1076 void (**handlers)(void);
1077 size_t nr;
1078 size_t alloc;
1079 } git_atexit_hdlrs;
1081 static int git_atexit_installed;
1083 static void git_atexit_dispatch(void)
1085 size_t i;
1087 for (i=git_atexit_hdlrs.nr ; i ; i--)
1088 git_atexit_hdlrs.handlers[i-1]();
1091 static void git_atexit_clear(void)
1093 free(git_atexit_hdlrs.handlers);
1094 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
1095 git_atexit_installed = 0;
1098 #undef atexit
1099 int git_atexit(void (*handler)(void))
1101 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
1102 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
1103 if (!git_atexit_installed) {
1104 if (atexit(&git_atexit_dispatch))
1105 return -1;
1106 git_atexit_installed = 1;
1108 return 0;
1110 #define atexit git_atexit
1112 static int process_is_async;
1113 int in_async(void)
1115 return process_is_async;
1118 static void NORETURN async_exit(int code)
1120 exit(code);
1123 #endif
1125 void check_pipe(int err)
1127 if (err == EPIPE) {
1128 if (in_async())
1129 async_exit(141);
1131 signal(SIGPIPE, SIG_DFL);
1132 raise(SIGPIPE);
1133 /* Should never happen, but just in case... */
1134 exit(141);
1138 int start_async(struct async *async)
1140 int need_in, need_out;
1141 int fdin[2], fdout[2];
1142 int proc_in, proc_out;
1144 need_in = async->in < 0;
1145 if (need_in) {
1146 if (pipe(fdin) < 0) {
1147 if (async->out > 0)
1148 close(async->out);
1149 return error_errno("cannot create pipe");
1151 async->in = fdin[1];
1154 need_out = async->out < 0;
1155 if (need_out) {
1156 if (pipe(fdout) < 0) {
1157 if (need_in)
1158 close_pair(fdin);
1159 else if (async->in)
1160 close(async->in);
1161 return error_errno("cannot create pipe");
1163 async->out = fdout[0];
1166 if (need_in)
1167 proc_in = fdin[0];
1168 else if (async->in)
1169 proc_in = async->in;
1170 else
1171 proc_in = -1;
1173 if (need_out)
1174 proc_out = fdout[1];
1175 else if (async->out)
1176 proc_out = async->out;
1177 else
1178 proc_out = -1;
1180 #ifdef NO_PTHREADS
1181 /* Flush stdio before fork() to avoid cloning buffers */
1182 fflush(NULL);
1184 async->pid = fork();
1185 if (async->pid < 0) {
1186 error_errno("fork (async) failed");
1187 goto error;
1189 if (!async->pid) {
1190 if (need_in)
1191 close(fdin[1]);
1192 if (need_out)
1193 close(fdout[0]);
1194 git_atexit_clear();
1195 process_is_async = 1;
1196 exit(!!async->proc(proc_in, proc_out, async->data));
1199 mark_child_for_cleanup(async->pid, NULL);
1201 if (need_in)
1202 close(fdin[0]);
1203 else if (async->in)
1204 close(async->in);
1206 if (need_out)
1207 close(fdout[1]);
1208 else if (async->out)
1209 close(async->out);
1210 #else
1211 if (!main_thread_set) {
1213 * We assume that the first time that start_async is called
1214 * it is from the main thread.
1216 main_thread_set = 1;
1217 main_thread = pthread_self();
1218 pthread_key_create(&async_key, NULL);
1219 pthread_key_create(&async_die_counter, NULL);
1220 set_die_routine(die_async);
1221 set_die_is_recursing_routine(async_die_is_recursing);
1224 if (proc_in >= 0)
1225 set_cloexec(proc_in);
1226 if (proc_out >= 0)
1227 set_cloexec(proc_out);
1228 async->proc_in = proc_in;
1229 async->proc_out = proc_out;
1231 int err = pthread_create(&async->tid, NULL, run_thread, async);
1232 if (err) {
1233 error(_("cannot create async thread: %s"), strerror(err));
1234 goto error;
1237 #endif
1238 return 0;
1240 error:
1241 if (need_in)
1242 close_pair(fdin);
1243 else if (async->in)
1244 close(async->in);
1246 if (need_out)
1247 close_pair(fdout);
1248 else if (async->out)
1249 close(async->out);
1250 return -1;
1253 int finish_async(struct async *async)
1255 #ifdef NO_PTHREADS
1256 int ret = wait_or_whine(async->pid, "child process", 0);
1258 invalidate_lstat_cache();
1260 return ret;
1261 #else
1262 void *ret = (void *)(intptr_t)(-1);
1264 if (pthread_join(async->tid, &ret))
1265 error("pthread_join failed");
1266 invalidate_lstat_cache();
1267 return (int)(intptr_t)ret;
1269 #endif
1272 int async_with_fork(void)
1274 #ifdef NO_PTHREADS
1275 return 1;
1276 #else
1277 return 0;
1278 #endif
1281 struct io_pump {
1282 /* initialized by caller */
1283 int fd;
1284 int type; /* POLLOUT or POLLIN */
1285 union {
1286 struct {
1287 const char *buf;
1288 size_t len;
1289 } out;
1290 struct {
1291 struct strbuf *buf;
1292 size_t hint;
1293 } in;
1294 } u;
1296 /* returned by pump_io */
1297 int error; /* 0 for success, otherwise errno */
1299 /* internal use */
1300 struct pollfd *pfd;
1303 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1305 int pollsize = 0;
1306 int i;
1308 for (i = 0; i < nr; i++) {
1309 struct io_pump *io = &slots[i];
1310 if (io->fd < 0)
1311 continue;
1312 pfd[pollsize].fd = io->fd;
1313 pfd[pollsize].events = io->type;
1314 io->pfd = &pfd[pollsize++];
1317 if (!pollsize)
1318 return 0;
1320 if (poll(pfd, pollsize, -1) < 0) {
1321 if (errno == EINTR)
1322 return 1;
1323 die_errno("poll failed");
1326 for (i = 0; i < nr; i++) {
1327 struct io_pump *io = &slots[i];
1329 if (io->fd < 0)
1330 continue;
1332 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1333 continue;
1335 if (io->type == POLLOUT) {
1336 ssize_t len;
1339 * Don't use xwrite() here. It loops forever on EAGAIN,
1340 * and we're in our own poll() loop here.
1342 * Note that we lose xwrite()'s handling of MAX_IO_SIZE
1343 * and EINTR, so we have to implement those ourselves.
1345 len = write(io->fd, io->u.out.buf,
1346 io->u.out.len <= MAX_IO_SIZE ?
1347 io->u.out.len : MAX_IO_SIZE);
1348 if (len < 0) {
1349 if (errno != EINTR && errno != EAGAIN &&
1350 errno != ENOSPC) {
1351 io->error = errno;
1352 close(io->fd);
1353 io->fd = -1;
1355 } else {
1356 io->u.out.buf += len;
1357 io->u.out.len -= len;
1358 if (!io->u.out.len) {
1359 close(io->fd);
1360 io->fd = -1;
1365 if (io->type == POLLIN) {
1366 ssize_t len = strbuf_read_once(io->u.in.buf,
1367 io->fd, io->u.in.hint);
1368 if (len < 0)
1369 io->error = errno;
1370 if (len <= 0) {
1371 close(io->fd);
1372 io->fd = -1;
1377 return 1;
1380 static int pump_io(struct io_pump *slots, int nr)
1382 struct pollfd *pfd;
1383 int i;
1385 for (i = 0; i < nr; i++)
1386 slots[i].error = 0;
1388 ALLOC_ARRAY(pfd, nr);
1389 while (pump_io_round(slots, nr, pfd))
1390 ; /* nothing */
1391 free(pfd);
1393 /* There may be multiple errno values, so just pick the first. */
1394 for (i = 0; i < nr; i++) {
1395 if (slots[i].error) {
1396 errno = slots[i].error;
1397 return -1;
1400 return 0;
1404 int pipe_command(struct child_process *cmd,
1405 const char *in, size_t in_len,
1406 struct strbuf *out, size_t out_hint,
1407 struct strbuf *err, size_t err_hint)
1409 struct io_pump io[3];
1410 int nr = 0;
1412 if (in)
1413 cmd->in = -1;
1414 if (out)
1415 cmd->out = -1;
1416 if (err)
1417 cmd->err = -1;
1419 if (start_command(cmd) < 0)
1420 return -1;
1422 if (in) {
1423 if (enable_pipe_nonblock(cmd->in) < 0) {
1424 error_errno("unable to make pipe non-blocking");
1425 close(cmd->in);
1426 if (out)
1427 close(cmd->out);
1428 if (err)
1429 close(cmd->err);
1430 return -1;
1432 io[nr].fd = cmd->in;
1433 io[nr].type = POLLOUT;
1434 io[nr].u.out.buf = in;
1435 io[nr].u.out.len = in_len;
1436 nr++;
1438 if (out) {
1439 io[nr].fd = cmd->out;
1440 io[nr].type = POLLIN;
1441 io[nr].u.in.buf = out;
1442 io[nr].u.in.hint = out_hint;
1443 nr++;
1445 if (err) {
1446 io[nr].fd = cmd->err;
1447 io[nr].type = POLLIN;
1448 io[nr].u.in.buf = err;
1449 io[nr].u.in.hint = err_hint;
1450 nr++;
1453 if (pump_io(io, nr) < 0) {
1454 finish_command(cmd); /* throw away exit code */
1455 return -1;
1458 return finish_command(cmd);
1461 enum child_state {
1462 GIT_CP_FREE,
1463 GIT_CP_WORKING,
1464 GIT_CP_WAIT_CLEANUP,
1467 struct parallel_processes {
1468 size_t nr_processes;
1470 struct {
1471 enum child_state state;
1472 struct child_process process;
1473 struct strbuf err;
1474 void *data;
1475 } *children;
1477 * The struct pollfd is logically part of *children,
1478 * but the system call expects it as its own array.
1480 struct pollfd *pfd;
1482 unsigned shutdown : 1;
1484 size_t output_owner;
1485 struct strbuf buffered_output; /* of finished children */
1488 struct parallel_processes_for_signal {
1489 const struct run_process_parallel_opts *opts;
1490 const struct parallel_processes *pp;
1493 static void kill_children(const struct parallel_processes *pp,
1494 const struct run_process_parallel_opts *opts,
1495 int signo)
1497 for (size_t i = 0; i < opts->processes; i++)
1498 if (pp->children[i].state == GIT_CP_WORKING)
1499 kill(pp->children[i].process.pid, signo);
1502 static void kill_children_signal(const struct parallel_processes_for_signal *pp_sig,
1503 int signo)
1505 kill_children(pp_sig->pp, pp_sig->opts, signo);
1508 static struct parallel_processes_for_signal *pp_for_signal;
1510 static void handle_children_on_signal(int signo)
1512 kill_children_signal(pp_for_signal, signo);
1513 sigchain_pop(signo);
1514 raise(signo);
1517 static void pp_init(struct parallel_processes *pp,
1518 const struct run_process_parallel_opts *opts,
1519 struct parallel_processes_for_signal *pp_sig)
1521 const size_t n = opts->processes;
1523 if (!n)
1524 BUG("you must provide a non-zero number of processes!");
1526 trace_printf("run_processes_parallel: preparing to run up to %"PRIuMAX" tasks",
1527 (uintmax_t)n);
1529 if (!opts->get_next_task)
1530 BUG("you need to specify a get_next_task function");
1532 CALLOC_ARRAY(pp->children, n);
1533 if (!opts->ungroup)
1534 CALLOC_ARRAY(pp->pfd, n);
1536 for (size_t i = 0; i < n; i++) {
1537 strbuf_init(&pp->children[i].err, 0);
1538 child_process_init(&pp->children[i].process);
1539 if (pp->pfd) {
1540 pp->pfd[i].events = POLLIN | POLLHUP;
1541 pp->pfd[i].fd = -1;
1545 pp_sig->pp = pp;
1546 pp_sig->opts = opts;
1547 pp_for_signal = pp_sig;
1548 sigchain_push_common(handle_children_on_signal);
1551 static void pp_cleanup(struct parallel_processes *pp,
1552 const struct run_process_parallel_opts *opts)
1554 trace_printf("run_processes_parallel: done");
1555 for (size_t i = 0; i < opts->processes; i++) {
1556 strbuf_release(&pp->children[i].err);
1557 child_process_clear(&pp->children[i].process);
1560 free(pp->children);
1561 free(pp->pfd);
1564 * When get_next_task added messages to the buffer in its last
1565 * iteration, the buffered output is non empty.
1567 strbuf_write(&pp->buffered_output, stderr);
1568 strbuf_release(&pp->buffered_output);
1570 sigchain_pop_common();
1573 /* returns
1574 * 0 if a new task was started.
1575 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1576 * problem with starting a new command)
1577 * <0 no new job was started, user wishes to shutdown early. Use negative code
1578 * to signal the children.
1580 static int pp_start_one(struct parallel_processes *pp,
1581 const struct run_process_parallel_opts *opts)
1583 size_t i;
1584 int code;
1586 for (i = 0; i < opts->processes; i++)
1587 if (pp->children[i].state == GIT_CP_FREE)
1588 break;
1589 if (i == opts->processes)
1590 BUG("bookkeeping is hard");
1593 * By default, do not inherit stdin from the parent process - otherwise,
1594 * all children would share stdin! Users may overwrite this to provide
1595 * something to the child's stdin by having their 'get_next_task'
1596 * callback assign 0 to .no_stdin and an appropriate integer to .in.
1598 pp->children[i].process.no_stdin = 1;
1600 code = opts->get_next_task(&pp->children[i].process,
1601 opts->ungroup ? NULL : &pp->children[i].err,
1602 opts->data,
1603 &pp->children[i].data);
1604 if (!code) {
1605 if (!opts->ungroup) {
1606 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1607 strbuf_reset(&pp->children[i].err);
1609 return 1;
1611 if (!opts->ungroup) {
1612 pp->children[i].process.err = -1;
1613 pp->children[i].process.stdout_to_stderr = 1;
1616 if (start_command(&pp->children[i].process)) {
1617 if (opts->start_failure)
1618 code = opts->start_failure(opts->ungroup ? NULL :
1619 &pp->children[i].err,
1620 opts->data,
1621 pp->children[i].data);
1622 else
1623 code = 0;
1625 if (!opts->ungroup) {
1626 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1627 strbuf_reset(&pp->children[i].err);
1629 if (code)
1630 pp->shutdown = 1;
1631 return code;
1634 pp->nr_processes++;
1635 pp->children[i].state = GIT_CP_WORKING;
1636 if (pp->pfd)
1637 pp->pfd[i].fd = pp->children[i].process.err;
1638 return 0;
1641 static void pp_buffer_stderr(struct parallel_processes *pp,
1642 const struct run_process_parallel_opts *opts,
1643 int output_timeout)
1645 while (poll(pp->pfd, opts->processes, output_timeout) < 0) {
1646 if (errno == EINTR)
1647 continue;
1648 pp_cleanup(pp, opts);
1649 die_errno("poll");
1652 /* Buffer output from all pipes. */
1653 for (size_t i = 0; i < opts->processes; i++) {
1654 if (pp->children[i].state == GIT_CP_WORKING &&
1655 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1656 int n = strbuf_read_once(&pp->children[i].err,
1657 pp->children[i].process.err, 0);
1658 if (n == 0) {
1659 close(pp->children[i].process.err);
1660 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1661 } else if (n < 0)
1662 if (errno != EAGAIN)
1663 die_errno("read");
1668 static void pp_output(const struct parallel_processes *pp)
1670 size_t i = pp->output_owner;
1672 if (pp->children[i].state == GIT_CP_WORKING &&
1673 pp->children[i].err.len) {
1674 strbuf_write(&pp->children[i].err, stderr);
1675 strbuf_reset(&pp->children[i].err);
1679 static int pp_collect_finished(struct parallel_processes *pp,
1680 const struct run_process_parallel_opts *opts)
1682 int code;
1683 size_t i;
1684 int result = 0;
1686 while (pp->nr_processes > 0) {
1687 for (i = 0; i < opts->processes; i++)
1688 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1689 break;
1690 if (i == opts->processes)
1691 break;
1693 code = finish_command(&pp->children[i].process);
1695 if (opts->task_finished)
1696 code = opts->task_finished(code, opts->ungroup ? NULL :
1697 &pp->children[i].err, opts->data,
1698 pp->children[i].data);
1699 else
1700 code = 0;
1702 if (code)
1703 result = code;
1704 if (code < 0)
1705 break;
1707 pp->nr_processes--;
1708 pp->children[i].state = GIT_CP_FREE;
1709 if (pp->pfd)
1710 pp->pfd[i].fd = -1;
1711 child_process_init(&pp->children[i].process);
1713 if (opts->ungroup) {
1714 ; /* no strbuf_*() work to do here */
1715 } else if (i != pp->output_owner) {
1716 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1717 strbuf_reset(&pp->children[i].err);
1718 } else {
1719 const size_t n = opts->processes;
1721 strbuf_write(&pp->children[i].err, stderr);
1722 strbuf_reset(&pp->children[i].err);
1724 /* Output all other finished child processes */
1725 strbuf_write(&pp->buffered_output, stderr);
1726 strbuf_reset(&pp->buffered_output);
1729 * Pick next process to output live.
1730 * NEEDSWORK:
1731 * For now we pick it randomly by doing a round
1732 * robin. Later we may want to pick the one with
1733 * the most output or the longest or shortest
1734 * running process time.
1736 for (i = 0; i < n; i++)
1737 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1738 break;
1739 pp->output_owner = (pp->output_owner + i) % n;
1742 return result;
1745 void run_processes_parallel(const struct run_process_parallel_opts *opts)
1747 int i, code;
1748 int output_timeout = 100;
1749 int spawn_cap = 4;
1750 struct parallel_processes_for_signal pp_sig;
1751 struct parallel_processes pp = {
1752 .buffered_output = STRBUF_INIT,
1754 /* options */
1755 const char *tr2_category = opts->tr2_category;
1756 const char *tr2_label = opts->tr2_label;
1757 const int do_trace2 = tr2_category && tr2_label;
1759 if (do_trace2)
1760 trace2_region_enter_printf(tr2_category, tr2_label, NULL,
1761 "max:%"PRIuMAX,
1762 (uintmax_t)opts->processes);
1764 pp_init(&pp, opts, &pp_sig);
1765 while (1) {
1766 for (i = 0;
1767 i < spawn_cap && !pp.shutdown &&
1768 pp.nr_processes < opts->processes;
1769 i++) {
1770 code = pp_start_one(&pp, opts);
1771 if (!code)
1772 continue;
1773 if (code < 0) {
1774 pp.shutdown = 1;
1775 kill_children(&pp, opts, -code);
1777 break;
1779 if (!pp.nr_processes)
1780 break;
1781 if (opts->ungroup) {
1782 for (size_t i = 0; i < opts->processes; i++)
1783 pp.children[i].state = GIT_CP_WAIT_CLEANUP;
1784 } else {
1785 pp_buffer_stderr(&pp, opts, output_timeout);
1786 pp_output(&pp);
1788 code = pp_collect_finished(&pp, opts);
1789 if (code) {
1790 pp.shutdown = 1;
1791 if (code < 0)
1792 kill_children(&pp, opts,-code);
1796 pp_cleanup(&pp, opts);
1798 if (do_trace2)
1799 trace2_region_leave(tr2_category, tr2_label, NULL);
1802 int prepare_auto_maintenance(int quiet, struct child_process *maint)
1804 int enabled;
1806 if (!git_config_get_bool("maintenance.auto", &enabled) &&
1807 !enabled)
1808 return 0;
1810 maint->git_cmd = 1;
1811 maint->close_object_store = 1;
1812 strvec_pushl(&maint->args, "maintenance", "run", "--auto", NULL);
1813 strvec_push(&maint->args, quiet ? "--quiet" : "--no-quiet");
1815 return 1;
1818 int run_auto_maintenance(int quiet)
1820 struct child_process maint = CHILD_PROCESS_INIT;
1821 if (!prepare_auto_maintenance(quiet, &maint))
1822 return 0;
1823 return run_command(&maint);
1826 void prepare_other_repo_env(struct strvec *env, const char *new_git_dir)
1828 const char * const *var;
1830 for (var = local_repo_env; *var; var++) {
1831 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT) &&
1832 strcmp(*var, CONFIG_COUNT_ENVIRONMENT))
1833 strvec_push(env, *var);
1835 strvec_pushf(env, "%s=%s", GIT_DIR_ENVIRONMENT, new_git_dir);
1838 enum start_bg_result start_bg_command(struct child_process *cmd,
1839 start_bg_wait_cb *wait_cb,
1840 void *cb_data,
1841 unsigned int timeout_sec)
1843 enum start_bg_result sbgr = SBGR_ERROR;
1844 int ret;
1845 int wait_status;
1846 pid_t pid_seen;
1847 time_t time_limit;
1850 * We do not allow clean-on-exit because the child process
1851 * should persist in the background and possibly/probably
1852 * after this process exits. So we don't want to kill the
1853 * child during our atexit routine.
1855 if (cmd->clean_on_exit)
1856 BUG("start_bg_command() does not allow non-zero clean_on_exit");
1858 if (!cmd->trace2_child_class)
1859 cmd->trace2_child_class = "background";
1861 ret = start_command(cmd);
1862 if (ret) {
1864 * We assume that if `start_command()` fails, we
1865 * either get a complete `trace2_child_start() /
1866 * trace2_child_exit()` pair or it fails before the
1867 * `trace2_child_start()` is emitted, so we do not
1868 * need to worry about it here.
1870 * We also assume that `start_command()` does not add
1871 * us to the cleanup list. And that it calls
1872 * `child_process_clear()`.
1874 sbgr = SBGR_ERROR;
1875 goto done;
1878 time(&time_limit);
1879 time_limit += timeout_sec;
1881 wait:
1882 pid_seen = waitpid(cmd->pid, &wait_status, WNOHANG);
1884 if (!pid_seen) {
1886 * The child is currently running. Ask the callback
1887 * if the child is ready to do work or whether we
1888 * should keep waiting for it to boot up.
1890 ret = (*wait_cb)(cmd, cb_data);
1891 if (!ret) {
1893 * The child is running and "ready".
1895 trace2_child_ready(cmd, "ready");
1896 sbgr = SBGR_READY;
1897 goto done;
1898 } else if (ret > 0) {
1900 * The callback said to give it more time to boot up
1901 * (subject to our timeout limit).
1903 time_t now;
1905 time(&now);
1906 if (now < time_limit)
1907 goto wait;
1910 * Our timeout has expired. We don't try to
1911 * kill the child, but rather let it continue
1912 * (hopefully) trying to startup.
1914 trace2_child_ready(cmd, "timeout");
1915 sbgr = SBGR_TIMEOUT;
1916 goto done;
1917 } else {
1919 * The cb gave up on this child. It is still running,
1920 * but our cb got an error trying to probe it.
1922 trace2_child_ready(cmd, "error");
1923 sbgr = SBGR_CB_ERROR;
1924 goto done;
1928 else if (pid_seen == cmd->pid) {
1929 int child_code = -1;
1932 * The child started, but exited or was terminated
1933 * before becoming "ready".
1935 * We try to match the behavior of `wait_or_whine()`
1936 * WRT the handling of WIFSIGNALED() and WIFEXITED()
1937 * and convert the child's status to a return code for
1938 * tracing purposes and emit the `trace2_child_exit()`
1939 * event.
1941 * We do not want the wait_or_whine() error message
1942 * because we will be called by client-side library
1943 * routines.
1945 if (WIFEXITED(wait_status))
1946 child_code = WEXITSTATUS(wait_status);
1947 else if (WIFSIGNALED(wait_status))
1948 child_code = WTERMSIG(wait_status) + 128;
1949 trace2_child_exit(cmd, child_code);
1951 sbgr = SBGR_DIED;
1952 goto done;
1955 else if (pid_seen < 0 && errno == EINTR)
1956 goto wait;
1958 trace2_child_exit(cmd, -1);
1959 sbgr = SBGR_ERROR;
1961 done:
1962 child_process_clear(cmd);
1963 invalidate_lstat_cache();
1964 return sbgr;