usage.c + gc: add and use a die_message_errno()
[git/debian.git] / run-command.c
bloba790fe9799d668b847efa1899f780400be583e02
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec-cmd.h"
4 #include "sigchain.h"
5 #include "strvec.h"
6 #include "thread-utils.h"
7 #include "strbuf.h"
8 #include "string-list.h"
9 #include "quote.h"
10 #include "config.h"
11 #include "packfile.h"
12 #include "hook.h"
14 void child_process_init(struct child_process *child)
16 struct child_process blank = CHILD_PROCESS_INIT;
17 memcpy(child, &blank, sizeof(*child));
20 void child_process_clear(struct child_process *child)
22 strvec_clear(&child->args);
23 strvec_clear(&child->env_array);
26 struct child_to_clean {
27 pid_t pid;
28 struct child_process *process;
29 struct child_to_clean *next;
31 static struct child_to_clean *children_to_clean;
32 static int installed_child_cleanup_handler;
34 static void cleanup_children(int sig, int in_signal)
36 struct child_to_clean *children_to_wait_for = NULL;
38 while (children_to_clean) {
39 struct child_to_clean *p = children_to_clean;
40 children_to_clean = p->next;
42 if (p->process && !in_signal) {
43 struct child_process *process = p->process;
44 if (process->clean_on_exit_handler) {
45 trace_printf(
46 "trace: run_command: running exit handler for pid %"
47 PRIuMAX, (uintmax_t)p->pid
49 process->clean_on_exit_handler(process);
53 kill(p->pid, sig);
55 if (p->process && p->process->wait_after_clean) {
56 p->next = children_to_wait_for;
57 children_to_wait_for = p;
58 } else {
59 if (!in_signal)
60 free(p);
64 while (children_to_wait_for) {
65 struct child_to_clean *p = children_to_wait_for;
66 children_to_wait_for = p->next;
68 while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
69 ; /* spin waiting for process exit or error */
71 if (!in_signal)
72 free(p);
76 static void cleanup_children_on_signal(int sig)
78 cleanup_children(sig, 1);
79 sigchain_pop(sig);
80 raise(sig);
83 static void cleanup_children_on_exit(void)
85 cleanup_children(SIGTERM, 0);
88 static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
90 struct child_to_clean *p = xmalloc(sizeof(*p));
91 p->pid = pid;
92 p->process = process;
93 p->next = children_to_clean;
94 children_to_clean = p;
96 if (!installed_child_cleanup_handler) {
97 atexit(cleanup_children_on_exit);
98 sigchain_push_common(cleanup_children_on_signal);
99 installed_child_cleanup_handler = 1;
103 static void clear_child_for_cleanup(pid_t pid)
105 struct child_to_clean **pp;
107 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
108 struct child_to_clean *clean_me = *pp;
110 if (clean_me->pid == pid) {
111 *pp = clean_me->next;
112 free(clean_me);
113 return;
118 static inline void close_pair(int fd[2])
120 close(fd[0]);
121 close(fd[1]);
124 int is_executable(const char *name)
126 struct stat st;
128 if (stat(name, &st) || /* stat, not lstat */
129 !S_ISREG(st.st_mode))
130 return 0;
132 #if defined(GIT_WINDOWS_NATIVE)
134 * On Windows there is no executable bit. The file extension
135 * indicates whether it can be run as an executable, and Git
136 * has special-handling to detect scripts and launch them
137 * through the indicated script interpreter. We test for the
138 * file extension first because virus scanners may make
139 * it quite expensive to open many files.
141 if (ends_with(name, ".exe"))
142 return S_IXUSR;
146 * Now that we know it does not have an executable extension,
147 * peek into the file instead.
149 char buf[3] = { 0 };
150 int n;
151 int fd = open(name, O_RDONLY);
152 st.st_mode &= ~S_IXUSR;
153 if (fd >= 0) {
154 n = read(fd, buf, 2);
155 if (n == 2)
156 /* look for a she-bang */
157 if (!strcmp(buf, "#!"))
158 st.st_mode |= S_IXUSR;
159 close(fd);
162 #endif
163 return st.st_mode & S_IXUSR;
167 * Search $PATH for a command. This emulates the path search that
168 * execvp would perform, without actually executing the command so it
169 * can be used before fork() to prepare to run a command using
170 * execve() or after execvp() to diagnose why it failed.
172 * The caller should ensure that file contains no directory
173 * separators.
175 * Returns the path to the command, as found in $PATH or NULL if the
176 * command could not be found. The caller inherits ownership of the memory
177 * used to store the resultant path.
179 * This should not be used on Windows, where the $PATH search rules
180 * are more complicated (e.g., a search for "foo" should find
181 * "foo.exe").
183 static char *locate_in_PATH(const char *file)
185 const char *p = getenv("PATH");
186 struct strbuf buf = STRBUF_INIT;
188 if (!p || !*p)
189 return NULL;
191 while (1) {
192 const char *end = strchrnul(p, ':');
194 strbuf_reset(&buf);
196 /* POSIX specifies an empty entry as the current directory. */
197 if (end != p) {
198 strbuf_add(&buf, p, end - p);
199 strbuf_addch(&buf, '/');
201 strbuf_addstr(&buf, file);
203 if (is_executable(buf.buf))
204 return strbuf_detach(&buf, NULL);
206 if (!*end)
207 break;
208 p = end + 1;
211 strbuf_release(&buf);
212 return NULL;
215 int exists_in_PATH(const char *command)
217 char *r = locate_in_PATH(command);
218 int found = r != NULL;
219 free(r);
220 return found;
223 int sane_execvp(const char *file, char * const argv[])
225 #ifndef GIT_WINDOWS_NATIVE
227 * execvp() doesn't return, so we all we can do is tell trace2
228 * what we are about to do and let it leave a hint in the log
229 * (unless of course the execvp() fails).
231 * we skip this for Windows because the compat layer already
232 * has to emulate the execvp() call anyway.
234 int exec_id = trace2_exec(file, (const char **)argv);
235 #endif
237 if (!execvp(file, argv))
238 return 0; /* cannot happen ;-) */
240 #ifndef GIT_WINDOWS_NATIVE
242 int ec = errno;
243 trace2_exec_result(exec_id, ec);
244 errno = ec;
246 #endif
249 * When a command can't be found because one of the directories
250 * listed in $PATH is unsearchable, execvp reports EACCES, but
251 * careful usability testing (read: analysis of occasional bug
252 * reports) reveals that "No such file or directory" is more
253 * intuitive.
255 * We avoid commands with "/", because execvp will not do $PATH
256 * lookups in that case.
258 * The reassignment of EACCES to errno looks like a no-op below,
259 * but we need to protect against exists_in_PATH overwriting errno.
261 if (errno == EACCES && !strchr(file, '/'))
262 errno = exists_in_PATH(file) ? EACCES : ENOENT;
263 else if (errno == ENOTDIR && !strchr(file, '/'))
264 errno = ENOENT;
265 return -1;
268 static const char **prepare_shell_cmd(struct strvec *out, const char **argv)
270 if (!argv[0])
271 BUG("shell command is empty");
273 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
274 #ifndef GIT_WINDOWS_NATIVE
275 strvec_push(out, SHELL_PATH);
276 #else
277 strvec_push(out, "sh");
278 #endif
279 strvec_push(out, "-c");
282 * If we have no extra arguments, we do not even need to
283 * bother with the "$@" magic.
285 if (!argv[1])
286 strvec_push(out, argv[0]);
287 else
288 strvec_pushf(out, "%s \"$@\"", argv[0]);
291 strvec_pushv(out, argv);
292 return out->v;
295 #ifndef GIT_WINDOWS_NATIVE
296 static int child_notifier = -1;
298 enum child_errcode {
299 CHILD_ERR_CHDIR,
300 CHILD_ERR_DUP2,
301 CHILD_ERR_CLOSE,
302 CHILD_ERR_SIGPROCMASK,
303 CHILD_ERR_ENOENT,
304 CHILD_ERR_SILENT,
305 CHILD_ERR_ERRNO
308 struct child_err {
309 enum child_errcode err;
310 int syserr; /* errno */
313 static void child_die(enum child_errcode err)
315 struct child_err buf;
317 buf.err = err;
318 buf.syserr = errno;
320 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
321 xwrite(child_notifier, &buf, sizeof(buf));
322 _exit(1);
325 static void child_dup2(int fd, int to)
327 if (dup2(fd, to) < 0)
328 child_die(CHILD_ERR_DUP2);
331 static void child_close(int fd)
333 if (close(fd))
334 child_die(CHILD_ERR_CLOSE);
337 static void child_close_pair(int fd[2])
339 child_close(fd[0]);
340 child_close(fd[1]);
343 static void child_error_fn(const char *err, va_list params)
345 const char msg[] = "error() should not be called in child\n";
346 xwrite(2, msg, sizeof(msg) - 1);
349 static void child_warn_fn(const char *err, va_list params)
351 const char msg[] = "warn() should not be called in child\n";
352 xwrite(2, msg, sizeof(msg) - 1);
355 static void NORETURN child_die_fn(const char *err, va_list params)
357 const char msg[] = "die() should not be called in child\n";
358 xwrite(2, msg, sizeof(msg) - 1);
359 _exit(2);
362 /* this runs in the parent process */
363 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
365 static void (*old_errfn)(const char *err, va_list params);
366 report_fn die_message_routine = get_die_message_routine();
368 old_errfn = get_error_routine();
369 set_error_routine(die_message_routine);
370 errno = cerr->syserr;
372 switch (cerr->err) {
373 case CHILD_ERR_CHDIR:
374 error_errno("exec '%s': cd to '%s' failed",
375 cmd->argv[0], cmd->dir);
376 break;
377 case CHILD_ERR_DUP2:
378 error_errno("dup2() in child failed");
379 break;
380 case CHILD_ERR_CLOSE:
381 error_errno("close() in child failed");
382 break;
383 case CHILD_ERR_SIGPROCMASK:
384 error_errno("sigprocmask failed restoring signals");
385 break;
386 case CHILD_ERR_ENOENT:
387 error_errno("cannot run %s", cmd->argv[0]);
388 break;
389 case CHILD_ERR_SILENT:
390 break;
391 case CHILD_ERR_ERRNO:
392 error_errno("cannot exec '%s'", cmd->argv[0]);
393 break;
395 set_error_routine(old_errfn);
398 static int prepare_cmd(struct strvec *out, const struct child_process *cmd)
400 if (!cmd->argv[0])
401 BUG("command is empty");
404 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
405 * attempt to interpret the command with 'sh'.
407 strvec_push(out, SHELL_PATH);
409 if (cmd->git_cmd) {
410 prepare_git_cmd(out, cmd->argv);
411 } else if (cmd->use_shell) {
412 prepare_shell_cmd(out, cmd->argv);
413 } else {
414 strvec_pushv(out, cmd->argv);
418 * If there are no dir separator characters in the command then perform
419 * a path lookup and use the resolved path as the command to exec. If
420 * there are dir separator characters, we have exec attempt to invoke
421 * the command directly.
423 if (!has_dir_sep(out->v[1])) {
424 char *program = locate_in_PATH(out->v[1]);
425 if (program) {
426 free((char *)out->v[1]);
427 out->v[1] = program;
428 } else {
429 strvec_clear(out);
430 errno = ENOENT;
431 return -1;
435 return 0;
438 static char **prep_childenv(const char *const *deltaenv)
440 extern char **environ;
441 char **childenv;
442 struct string_list env = STRING_LIST_INIT_DUP;
443 struct strbuf key = STRBUF_INIT;
444 const char *const *p;
445 int i;
447 /* Construct a sorted string list consisting of the current environ */
448 for (p = (const char *const *) environ; p && *p; p++) {
449 const char *equals = strchr(*p, '=');
451 if (equals) {
452 strbuf_reset(&key);
453 strbuf_add(&key, *p, equals - *p);
454 string_list_append(&env, key.buf)->util = (void *) *p;
455 } else {
456 string_list_append(&env, *p)->util = (void *) *p;
459 string_list_sort(&env);
461 /* Merge in 'deltaenv' with the current environ */
462 for (p = deltaenv; p && *p; p++) {
463 const char *equals = strchr(*p, '=');
465 if (equals) {
466 /* ('key=value'), insert or replace entry */
467 strbuf_reset(&key);
468 strbuf_add(&key, *p, equals - *p);
469 string_list_insert(&env, key.buf)->util = (void *) *p;
470 } else {
471 /* otherwise ('key') remove existing entry */
472 string_list_remove(&env, *p, 0);
476 /* Create an array of 'char *' to be used as the childenv */
477 ALLOC_ARRAY(childenv, env.nr + 1);
478 for (i = 0; i < env.nr; i++)
479 childenv[i] = env.items[i].util;
480 childenv[env.nr] = NULL;
482 string_list_clear(&env, 0);
483 strbuf_release(&key);
484 return childenv;
487 struct atfork_state {
488 #ifndef NO_PTHREADS
489 int cs;
490 #endif
491 sigset_t old;
494 #define CHECK_BUG(err, msg) \
495 do { \
496 int e = (err); \
497 if (e) \
498 BUG("%s: %s", msg, strerror(e)); \
499 } while(0)
501 static void atfork_prepare(struct atfork_state *as)
503 sigset_t all;
505 if (sigfillset(&all))
506 die_errno("sigfillset");
507 #ifdef NO_PTHREADS
508 if (sigprocmask(SIG_SETMASK, &all, &as->old))
509 die_errno("sigprocmask");
510 #else
511 CHECK_BUG(pthread_sigmask(SIG_SETMASK, &all, &as->old),
512 "blocking all signals");
513 CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
514 "disabling cancellation");
515 #endif
518 static void atfork_parent(struct atfork_state *as)
520 #ifdef NO_PTHREADS
521 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
522 die_errno("sigprocmask");
523 #else
524 CHECK_BUG(pthread_setcancelstate(as->cs, NULL),
525 "re-enabling cancellation");
526 CHECK_BUG(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
527 "restoring signal mask");
528 #endif
530 #endif /* GIT_WINDOWS_NATIVE */
532 static inline void set_cloexec(int fd)
534 int flags = fcntl(fd, F_GETFD);
535 if (flags >= 0)
536 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
539 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
541 int status, code = -1;
542 pid_t waiting;
543 int failed_errno = 0;
545 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
546 ; /* nothing */
547 if (in_signal) {
548 if (WIFEXITED(status))
549 code = WEXITSTATUS(status);
550 return code;
553 if (waiting < 0) {
554 failed_errno = errno;
555 error_errno("waitpid for %s failed", argv0);
556 } else if (waiting != pid) {
557 error("waitpid is confused (%s)", argv0);
558 } else if (WIFSIGNALED(status)) {
559 code = WTERMSIG(status);
560 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
561 error("%s died of signal %d", argv0, code);
563 * This return value is chosen so that code & 0xff
564 * mimics the exit code that a POSIX shell would report for
565 * a program that died from this signal.
567 code += 128;
568 } else if (WIFEXITED(status)) {
569 code = WEXITSTATUS(status);
570 } else {
571 error("waitpid is confused (%s)", argv0);
574 clear_child_for_cleanup(pid);
576 errno = failed_errno;
577 return code;
580 static void trace_add_env(struct strbuf *dst, const char *const *deltaenv)
582 struct string_list envs = STRING_LIST_INIT_DUP;
583 const char *const *e;
584 int i;
585 int printed_unset = 0;
587 /* Last one wins, see run-command.c:prep_childenv() for context */
588 for (e = deltaenv; e && *e; e++) {
589 struct strbuf key = STRBUF_INIT;
590 char *equals = strchr(*e, '=');
592 if (equals) {
593 strbuf_add(&key, *e, equals - *e);
594 string_list_insert(&envs, key.buf)->util = equals + 1;
595 } else {
596 string_list_insert(&envs, *e)->util = NULL;
598 strbuf_release(&key);
601 /* "unset X Y...;" */
602 for (i = 0; i < envs.nr; i++) {
603 const char *var = envs.items[i].string;
604 const char *val = envs.items[i].util;
606 if (val || !getenv(var))
607 continue;
609 if (!printed_unset) {
610 strbuf_addstr(dst, " unset");
611 printed_unset = 1;
613 strbuf_addf(dst, " %s", var);
615 if (printed_unset)
616 strbuf_addch(dst, ';');
618 /* ... followed by "A=B C=D ..." */
619 for (i = 0; i < envs.nr; i++) {
620 const char *var = envs.items[i].string;
621 const char *val = envs.items[i].util;
622 const char *oldval;
624 if (!val)
625 continue;
627 oldval = getenv(var);
628 if (oldval && !strcmp(val, oldval))
629 continue;
631 strbuf_addf(dst, " %s=", var);
632 sq_quote_buf_pretty(dst, val);
634 string_list_clear(&envs, 0);
637 static void trace_run_command(const struct child_process *cp)
639 struct strbuf buf = STRBUF_INIT;
641 if (!trace_want(&trace_default_key))
642 return;
644 strbuf_addstr(&buf, "trace: run_command:");
645 if (cp->dir) {
646 strbuf_addstr(&buf, " cd ");
647 sq_quote_buf_pretty(&buf, cp->dir);
648 strbuf_addch(&buf, ';');
651 * The caller is responsible for initializing cp->env from
652 * cp->env_array if needed. We only check one place.
654 if (cp->env)
655 trace_add_env(&buf, cp->env);
656 if (cp->git_cmd)
657 strbuf_addstr(&buf, " git");
658 sq_quote_argv_pretty(&buf, cp->argv);
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];
668 int failed_errno;
669 char *str;
671 if (!cmd->argv)
672 cmd->argv = cmd->args.v;
673 if (!cmd->env)
674 cmd->env = cmd->env_array.v;
677 * In case of errors we must keep the promise to close FDs
678 * that have been passed in via ->in and ->out.
681 need_in = !cmd->no_stdin && cmd->in < 0;
682 if (need_in) {
683 if (pipe(fdin) < 0) {
684 failed_errno = errno;
685 if (cmd->out > 0)
686 close(cmd->out);
687 str = "standard input";
688 goto fail_pipe;
690 cmd->in = fdin[1];
693 need_out = !cmd->no_stdout
694 && !cmd->stdout_to_stderr
695 && cmd->out < 0;
696 if (need_out) {
697 if (pipe(fdout) < 0) {
698 failed_errno = errno;
699 if (need_in)
700 close_pair(fdin);
701 else if (cmd->in)
702 close(cmd->in);
703 str = "standard output";
704 goto fail_pipe;
706 cmd->out = fdout[0];
709 need_err = !cmd->no_stderr && cmd->err < 0;
710 if (need_err) {
711 if (pipe(fderr) < 0) {
712 failed_errno = errno;
713 if (need_in)
714 close_pair(fdin);
715 else if (cmd->in)
716 close(cmd->in);
717 if (need_out)
718 close_pair(fdout);
719 else if (cmd->out)
720 close(cmd->out);
721 str = "standard error";
722 fail_pipe:
723 error("cannot create %s pipe for %s: %s",
724 str, cmd->argv[0], strerror(failed_errno));
725 child_process_clear(cmd);
726 errno = failed_errno;
727 return -1;
729 cmd->err = fderr[0];
732 trace2_child_start(cmd);
733 trace_run_command(cmd);
735 fflush(NULL);
737 if (cmd->close_object_store)
738 close_object_store(the_repository->objects);
740 #ifndef GIT_WINDOWS_NATIVE
742 int notify_pipe[2];
743 int null_fd = -1;
744 char **childenv;
745 struct strvec argv = STRVEC_INIT;
746 struct child_err cerr;
747 struct atfork_state as;
749 if (prepare_cmd(&argv, cmd) < 0) {
750 failed_errno = errno;
751 cmd->pid = -1;
752 if (!cmd->silent_exec_failure)
753 error_errno("cannot run %s", cmd->argv[0]);
754 goto end_of_spawn;
757 if (pipe(notify_pipe))
758 notify_pipe[0] = notify_pipe[1] = -1;
760 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
761 null_fd = xopen("/dev/null", O_RDWR | O_CLOEXEC);
762 set_cloexec(null_fd);
765 childenv = prep_childenv(cmd->env);
766 atfork_prepare(&as);
769 * NOTE: In order to prevent deadlocking when using threads special
770 * care should be taken with the function calls made in between the
771 * fork() and exec() calls. No calls should be made to functions which
772 * require acquiring a lock (e.g. malloc) as the lock could have been
773 * held by another thread at the time of forking, causing the lock to
774 * never be released in the child process. This means only
775 * Async-Signal-Safe functions are permitted in the child.
777 cmd->pid = fork();
778 failed_errno = errno;
779 if (!cmd->pid) {
780 int sig;
782 * Ensure the default die/error/warn routines do not get
783 * called, they can take stdio locks and malloc.
785 set_die_routine(child_die_fn);
786 set_error_routine(child_error_fn);
787 set_warn_routine(child_warn_fn);
789 close(notify_pipe[0]);
790 set_cloexec(notify_pipe[1]);
791 child_notifier = notify_pipe[1];
793 if (cmd->no_stdin)
794 child_dup2(null_fd, 0);
795 else if (need_in) {
796 child_dup2(fdin[0], 0);
797 child_close_pair(fdin);
798 } else if (cmd->in) {
799 child_dup2(cmd->in, 0);
800 child_close(cmd->in);
803 if (cmd->no_stderr)
804 child_dup2(null_fd, 2);
805 else if (need_err) {
806 child_dup2(fderr[1], 2);
807 child_close_pair(fderr);
808 } else if (cmd->err > 1) {
809 child_dup2(cmd->err, 2);
810 child_close(cmd->err);
813 if (cmd->no_stdout)
814 child_dup2(null_fd, 1);
815 else if (cmd->stdout_to_stderr)
816 child_dup2(2, 1);
817 else if (need_out) {
818 child_dup2(fdout[1], 1);
819 child_close_pair(fdout);
820 } else if (cmd->out > 1) {
821 child_dup2(cmd->out, 1);
822 child_close(cmd->out);
825 if (cmd->dir && chdir(cmd->dir))
826 child_die(CHILD_ERR_CHDIR);
829 * restore default signal handlers here, in case
830 * we catch a signal right before execve below
832 for (sig = 1; sig < NSIG; sig++) {
833 /* ignored signals get reset to SIG_DFL on execve */
834 if (signal(sig, SIG_DFL) == SIG_IGN)
835 signal(sig, SIG_IGN);
838 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
839 child_die(CHILD_ERR_SIGPROCMASK);
842 * Attempt to exec using the command and arguments starting at
843 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
844 * be used in the event exec failed with ENOEXEC at which point
845 * we will try to interpret the command using 'sh'.
847 execve(argv.v[1], (char *const *) argv.v + 1,
848 (char *const *) childenv);
849 if (errno == ENOEXEC)
850 execve(argv.v[0], (char *const *) argv.v,
851 (char *const *) childenv);
853 if (errno == ENOENT) {
854 if (cmd->silent_exec_failure)
855 child_die(CHILD_ERR_SILENT);
856 child_die(CHILD_ERR_ENOENT);
857 } else {
858 child_die(CHILD_ERR_ERRNO);
861 atfork_parent(&as);
862 if (cmd->pid < 0)
863 error_errno("cannot fork() for %s", cmd->argv[0]);
864 else if (cmd->clean_on_exit)
865 mark_child_for_cleanup(cmd->pid, cmd);
868 * Wait for child's exec. If the exec succeeds (or if fork()
869 * failed), EOF is seen immediately by the parent. Otherwise, the
870 * child process sends a child_err struct.
871 * Note that use of this infrastructure is completely advisory,
872 * therefore, we keep error checks minimal.
874 close(notify_pipe[1]);
875 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
877 * At this point we know that fork() succeeded, but exec()
878 * failed. Errors have been reported to our stderr.
880 wait_or_whine(cmd->pid, cmd->argv[0], 0);
881 child_err_spew(cmd, &cerr);
882 failed_errno = errno;
883 cmd->pid = -1;
885 close(notify_pipe[0]);
887 if (null_fd >= 0)
888 close(null_fd);
889 strvec_clear(&argv);
890 free(childenv);
892 end_of_spawn:
894 #else
896 int fhin = 0, fhout = 1, fherr = 2;
897 const char **sargv = cmd->argv;
898 struct strvec nargv = STRVEC_INIT;
900 if (cmd->no_stdin)
901 fhin = open("/dev/null", O_RDWR);
902 else if (need_in)
903 fhin = dup(fdin[0]);
904 else if (cmd->in)
905 fhin = dup(cmd->in);
907 if (cmd->no_stderr)
908 fherr = open("/dev/null", O_RDWR);
909 else if (need_err)
910 fherr = dup(fderr[1]);
911 else if (cmd->err > 2)
912 fherr = dup(cmd->err);
914 if (cmd->no_stdout)
915 fhout = open("/dev/null", O_RDWR);
916 else if (cmd->stdout_to_stderr)
917 fhout = dup(fherr);
918 else if (need_out)
919 fhout = dup(fdout[1]);
920 else if (cmd->out > 1)
921 fhout = dup(cmd->out);
923 if (cmd->git_cmd)
924 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
925 else if (cmd->use_shell)
926 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
928 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
929 cmd->dir, fhin, fhout, fherr);
930 failed_errno = errno;
931 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
932 error_errno("cannot spawn %s", cmd->argv[0]);
933 if (cmd->clean_on_exit && cmd->pid >= 0)
934 mark_child_for_cleanup(cmd->pid, cmd);
936 strvec_clear(&nargv);
937 cmd->argv = sargv;
938 if (fhin != 0)
939 close(fhin);
940 if (fhout != 1)
941 close(fhout);
942 if (fherr != 2)
943 close(fherr);
945 #endif
947 if (cmd->pid < 0) {
948 trace2_child_exit(cmd, -1);
950 if (need_in)
951 close_pair(fdin);
952 else if (cmd->in)
953 close(cmd->in);
954 if (need_out)
955 close_pair(fdout);
956 else if (cmd->out)
957 close(cmd->out);
958 if (need_err)
959 close_pair(fderr);
960 else if (cmd->err)
961 close(cmd->err);
962 child_process_clear(cmd);
963 errno = failed_errno;
964 return -1;
967 if (need_in)
968 close(fdin[0]);
969 else if (cmd->in)
970 close(cmd->in);
972 if (need_out)
973 close(fdout[1]);
974 else if (cmd->out)
975 close(cmd->out);
977 if (need_err)
978 close(fderr[1]);
979 else if (cmd->err)
980 close(cmd->err);
982 return 0;
985 int finish_command(struct child_process *cmd)
987 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
988 trace2_child_exit(cmd, ret);
989 child_process_clear(cmd);
990 invalidate_lstat_cache();
991 return ret;
994 int finish_command_in_signal(struct child_process *cmd)
996 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 1);
997 trace2_child_exit(cmd, ret);
998 return ret;
1002 int run_command(struct child_process *cmd)
1004 int code;
1006 if (cmd->out < 0 || cmd->err < 0)
1007 BUG("run_command with a pipe can cause deadlock");
1009 code = start_command(cmd);
1010 if (code)
1011 return code;
1012 return finish_command(cmd);
1015 int run_command_v_opt(const char **argv, int opt)
1017 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
1020 int run_command_v_opt_tr2(const char **argv, int opt, const char *tr2_class)
1022 return run_command_v_opt_cd_env_tr2(argv, opt, NULL, NULL, tr2_class);
1025 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
1027 return run_command_v_opt_cd_env_tr2(argv, opt, dir, env, NULL);
1030 int run_command_v_opt_cd_env_tr2(const char **argv, int opt, const char *dir,
1031 const char *const *env, const char *tr2_class)
1033 struct child_process cmd = CHILD_PROCESS_INIT;
1034 cmd.argv = argv;
1035 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
1036 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
1037 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
1038 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
1039 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
1040 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
1041 cmd.wait_after_clean = opt & RUN_WAIT_AFTER_CLEAN ? 1 : 0;
1042 cmd.close_object_store = opt & RUN_CLOSE_OBJECT_STORE ? 1 : 0;
1043 cmd.dir = dir;
1044 cmd.env = env;
1045 cmd.trace2_child_class = tr2_class;
1046 return run_command(&cmd);
1049 #ifndef NO_PTHREADS
1050 static pthread_t main_thread;
1051 static int main_thread_set;
1052 static pthread_key_t async_key;
1053 static pthread_key_t async_die_counter;
1055 static void *run_thread(void *data)
1057 struct async *async = data;
1058 intptr_t ret;
1060 if (async->isolate_sigpipe) {
1061 sigset_t mask;
1062 sigemptyset(&mask);
1063 sigaddset(&mask, SIGPIPE);
1064 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
1065 ret = error("unable to block SIGPIPE in async thread");
1066 return (void *)ret;
1070 pthread_setspecific(async_key, async);
1071 ret = async->proc(async->proc_in, async->proc_out, async->data);
1072 return (void *)ret;
1075 static NORETURN void die_async(const char *err, va_list params)
1077 report_fn die_message_fn = get_die_message_routine();
1079 die_message_fn(err, params);
1081 if (in_async()) {
1082 struct async *async = pthread_getspecific(async_key);
1083 if (async->proc_in >= 0)
1084 close(async->proc_in);
1085 if (async->proc_out >= 0)
1086 close(async->proc_out);
1087 pthread_exit((void *)128);
1090 exit(128);
1093 static int async_die_is_recursing(void)
1095 void *ret = pthread_getspecific(async_die_counter);
1096 pthread_setspecific(async_die_counter, &async_die_counter); /* set to any non-NULL valid pointer */
1097 return ret != NULL;
1100 int in_async(void)
1102 if (!main_thread_set)
1103 return 0; /* no asyncs started yet */
1104 return !pthread_equal(main_thread, pthread_self());
1107 static void NORETURN async_exit(int code)
1109 pthread_exit((void *)(intptr_t)code);
1112 #else
1114 static struct {
1115 void (**handlers)(void);
1116 size_t nr;
1117 size_t alloc;
1118 } git_atexit_hdlrs;
1120 static int git_atexit_installed;
1122 static void git_atexit_dispatch(void)
1124 size_t i;
1126 for (i=git_atexit_hdlrs.nr ; i ; i--)
1127 git_atexit_hdlrs.handlers[i-1]();
1130 static void git_atexit_clear(void)
1132 free(git_atexit_hdlrs.handlers);
1133 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
1134 git_atexit_installed = 0;
1137 #undef atexit
1138 int git_atexit(void (*handler)(void))
1140 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
1141 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
1142 if (!git_atexit_installed) {
1143 if (atexit(&git_atexit_dispatch))
1144 return -1;
1145 git_atexit_installed = 1;
1147 return 0;
1149 #define atexit git_atexit
1151 static int process_is_async;
1152 int in_async(void)
1154 return process_is_async;
1157 static void NORETURN async_exit(int code)
1159 exit(code);
1162 #endif
1164 void check_pipe(int err)
1166 if (err == EPIPE) {
1167 if (in_async())
1168 async_exit(141);
1170 signal(SIGPIPE, SIG_DFL);
1171 raise(SIGPIPE);
1172 /* Should never happen, but just in case... */
1173 exit(141);
1177 int start_async(struct async *async)
1179 int need_in, need_out;
1180 int fdin[2], fdout[2];
1181 int proc_in, proc_out;
1183 need_in = async->in < 0;
1184 if (need_in) {
1185 if (pipe(fdin) < 0) {
1186 if (async->out > 0)
1187 close(async->out);
1188 return error_errno("cannot create pipe");
1190 async->in = fdin[1];
1193 need_out = async->out < 0;
1194 if (need_out) {
1195 if (pipe(fdout) < 0) {
1196 if (need_in)
1197 close_pair(fdin);
1198 else if (async->in)
1199 close(async->in);
1200 return error_errno("cannot create pipe");
1202 async->out = fdout[0];
1205 if (need_in)
1206 proc_in = fdin[0];
1207 else if (async->in)
1208 proc_in = async->in;
1209 else
1210 proc_in = -1;
1212 if (need_out)
1213 proc_out = fdout[1];
1214 else if (async->out)
1215 proc_out = async->out;
1216 else
1217 proc_out = -1;
1219 #ifdef NO_PTHREADS
1220 /* Flush stdio before fork() to avoid cloning buffers */
1221 fflush(NULL);
1223 async->pid = fork();
1224 if (async->pid < 0) {
1225 error_errno("fork (async) failed");
1226 goto error;
1228 if (!async->pid) {
1229 if (need_in)
1230 close(fdin[1]);
1231 if (need_out)
1232 close(fdout[0]);
1233 git_atexit_clear();
1234 process_is_async = 1;
1235 exit(!!async->proc(proc_in, proc_out, async->data));
1238 mark_child_for_cleanup(async->pid, NULL);
1240 if (need_in)
1241 close(fdin[0]);
1242 else if (async->in)
1243 close(async->in);
1245 if (need_out)
1246 close(fdout[1]);
1247 else if (async->out)
1248 close(async->out);
1249 #else
1250 if (!main_thread_set) {
1252 * We assume that the first time that start_async is called
1253 * it is from the main thread.
1255 main_thread_set = 1;
1256 main_thread = pthread_self();
1257 pthread_key_create(&async_key, NULL);
1258 pthread_key_create(&async_die_counter, NULL);
1259 set_die_routine(die_async);
1260 set_die_is_recursing_routine(async_die_is_recursing);
1263 if (proc_in >= 0)
1264 set_cloexec(proc_in);
1265 if (proc_out >= 0)
1266 set_cloexec(proc_out);
1267 async->proc_in = proc_in;
1268 async->proc_out = proc_out;
1270 int err = pthread_create(&async->tid, NULL, run_thread, async);
1271 if (err) {
1272 error(_("cannot create async thread: %s"), strerror(err));
1273 goto error;
1276 #endif
1277 return 0;
1279 error:
1280 if (need_in)
1281 close_pair(fdin);
1282 else if (async->in)
1283 close(async->in);
1285 if (need_out)
1286 close_pair(fdout);
1287 else if (async->out)
1288 close(async->out);
1289 return -1;
1292 int finish_async(struct async *async)
1294 #ifdef NO_PTHREADS
1295 int ret = wait_or_whine(async->pid, "child process", 0);
1297 invalidate_lstat_cache();
1299 return ret;
1300 #else
1301 void *ret = (void *)(intptr_t)(-1);
1303 if (pthread_join(async->tid, &ret))
1304 error("pthread_join failed");
1305 invalidate_lstat_cache();
1306 return (int)(intptr_t)ret;
1308 #endif
1311 int async_with_fork(void)
1313 #ifdef NO_PTHREADS
1314 return 1;
1315 #else
1316 return 0;
1317 #endif
1320 int run_hook_ve(const char *const *env, const char *name, va_list args)
1322 struct child_process hook = CHILD_PROCESS_INIT;
1323 const char *p;
1325 p = find_hook(name);
1326 if (!p)
1327 return 0;
1329 strvec_push(&hook.args, p);
1330 while ((p = va_arg(args, const char *)))
1331 strvec_push(&hook.args, p);
1332 hook.env = env;
1333 hook.no_stdin = 1;
1334 hook.stdout_to_stderr = 1;
1335 hook.trace2_hook_name = name;
1337 return run_command(&hook);
1340 int run_hook_le(const char *const *env, const char *name, ...)
1342 va_list args;
1343 int ret;
1345 va_start(args, name);
1346 ret = run_hook_ve(env, name, args);
1347 va_end(args);
1349 return ret;
1352 struct io_pump {
1353 /* initialized by caller */
1354 int fd;
1355 int type; /* POLLOUT or POLLIN */
1356 union {
1357 struct {
1358 const char *buf;
1359 size_t len;
1360 } out;
1361 struct {
1362 struct strbuf *buf;
1363 size_t hint;
1364 } in;
1365 } u;
1367 /* returned by pump_io */
1368 int error; /* 0 for success, otherwise errno */
1370 /* internal use */
1371 struct pollfd *pfd;
1374 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1376 int pollsize = 0;
1377 int i;
1379 for (i = 0; i < nr; i++) {
1380 struct io_pump *io = &slots[i];
1381 if (io->fd < 0)
1382 continue;
1383 pfd[pollsize].fd = io->fd;
1384 pfd[pollsize].events = io->type;
1385 io->pfd = &pfd[pollsize++];
1388 if (!pollsize)
1389 return 0;
1391 if (poll(pfd, pollsize, -1) < 0) {
1392 if (errno == EINTR)
1393 return 1;
1394 die_errno("poll failed");
1397 for (i = 0; i < nr; i++) {
1398 struct io_pump *io = &slots[i];
1400 if (io->fd < 0)
1401 continue;
1403 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1404 continue;
1406 if (io->type == POLLOUT) {
1407 ssize_t len = xwrite(io->fd,
1408 io->u.out.buf, io->u.out.len);
1409 if (len < 0) {
1410 io->error = errno;
1411 close(io->fd);
1412 io->fd = -1;
1413 } else {
1414 io->u.out.buf += len;
1415 io->u.out.len -= len;
1416 if (!io->u.out.len) {
1417 close(io->fd);
1418 io->fd = -1;
1423 if (io->type == POLLIN) {
1424 ssize_t len = strbuf_read_once(io->u.in.buf,
1425 io->fd, io->u.in.hint);
1426 if (len < 0)
1427 io->error = errno;
1428 if (len <= 0) {
1429 close(io->fd);
1430 io->fd = -1;
1435 return 1;
1438 static int pump_io(struct io_pump *slots, int nr)
1440 struct pollfd *pfd;
1441 int i;
1443 for (i = 0; i < nr; i++)
1444 slots[i].error = 0;
1446 ALLOC_ARRAY(pfd, nr);
1447 while (pump_io_round(slots, nr, pfd))
1448 ; /* nothing */
1449 free(pfd);
1451 /* There may be multiple errno values, so just pick the first. */
1452 for (i = 0; i < nr; i++) {
1453 if (slots[i].error) {
1454 errno = slots[i].error;
1455 return -1;
1458 return 0;
1462 int pipe_command(struct child_process *cmd,
1463 const char *in, size_t in_len,
1464 struct strbuf *out, size_t out_hint,
1465 struct strbuf *err, size_t err_hint)
1467 struct io_pump io[3];
1468 int nr = 0;
1470 if (in)
1471 cmd->in = -1;
1472 if (out)
1473 cmd->out = -1;
1474 if (err)
1475 cmd->err = -1;
1477 if (start_command(cmd) < 0)
1478 return -1;
1480 if (in) {
1481 io[nr].fd = cmd->in;
1482 io[nr].type = POLLOUT;
1483 io[nr].u.out.buf = in;
1484 io[nr].u.out.len = in_len;
1485 nr++;
1487 if (out) {
1488 io[nr].fd = cmd->out;
1489 io[nr].type = POLLIN;
1490 io[nr].u.in.buf = out;
1491 io[nr].u.in.hint = out_hint;
1492 nr++;
1494 if (err) {
1495 io[nr].fd = cmd->err;
1496 io[nr].type = POLLIN;
1497 io[nr].u.in.buf = err;
1498 io[nr].u.in.hint = err_hint;
1499 nr++;
1502 if (pump_io(io, nr) < 0) {
1503 finish_command(cmd); /* throw away exit code */
1504 return -1;
1507 return finish_command(cmd);
1510 enum child_state {
1511 GIT_CP_FREE,
1512 GIT_CP_WORKING,
1513 GIT_CP_WAIT_CLEANUP,
1516 struct parallel_processes {
1517 void *data;
1519 int max_processes;
1520 int nr_processes;
1522 get_next_task_fn get_next_task;
1523 start_failure_fn start_failure;
1524 task_finished_fn task_finished;
1526 struct {
1527 enum child_state state;
1528 struct child_process process;
1529 struct strbuf err;
1530 void *data;
1531 } *children;
1533 * The struct pollfd is logically part of *children,
1534 * but the system call expects it as its own array.
1536 struct pollfd *pfd;
1538 unsigned shutdown : 1;
1540 int output_owner;
1541 struct strbuf buffered_output; /* of finished children */
1544 static int default_start_failure(struct strbuf *out,
1545 void *pp_cb,
1546 void *pp_task_cb)
1548 return 0;
1551 static int default_task_finished(int result,
1552 struct strbuf *out,
1553 void *pp_cb,
1554 void *pp_task_cb)
1556 return 0;
1559 static void kill_children(struct parallel_processes *pp, int signo)
1561 int i, n = pp->max_processes;
1563 for (i = 0; i < n; i++)
1564 if (pp->children[i].state == GIT_CP_WORKING)
1565 kill(pp->children[i].process.pid, signo);
1568 static struct parallel_processes *pp_for_signal;
1570 static void handle_children_on_signal(int signo)
1572 kill_children(pp_for_signal, signo);
1573 sigchain_pop(signo);
1574 raise(signo);
1577 static void pp_init(struct parallel_processes *pp,
1578 int n,
1579 get_next_task_fn get_next_task,
1580 start_failure_fn start_failure,
1581 task_finished_fn task_finished,
1582 void *data)
1584 int i;
1586 if (n < 1)
1587 n = online_cpus();
1589 pp->max_processes = n;
1591 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1593 pp->data = data;
1594 if (!get_next_task)
1595 BUG("you need to specify a get_next_task function");
1596 pp->get_next_task = get_next_task;
1598 pp->start_failure = start_failure ? start_failure : default_start_failure;
1599 pp->task_finished = task_finished ? task_finished : default_task_finished;
1601 pp->nr_processes = 0;
1602 pp->output_owner = 0;
1603 pp->shutdown = 0;
1604 CALLOC_ARRAY(pp->children, n);
1605 CALLOC_ARRAY(pp->pfd, n);
1606 strbuf_init(&pp->buffered_output, 0);
1608 for (i = 0; i < n; i++) {
1609 strbuf_init(&pp->children[i].err, 0);
1610 child_process_init(&pp->children[i].process);
1611 pp->pfd[i].events = POLLIN | POLLHUP;
1612 pp->pfd[i].fd = -1;
1615 pp_for_signal = pp;
1616 sigchain_push_common(handle_children_on_signal);
1619 static void pp_cleanup(struct parallel_processes *pp)
1621 int i;
1623 trace_printf("run_processes_parallel: done");
1624 for (i = 0; i < pp->max_processes; i++) {
1625 strbuf_release(&pp->children[i].err);
1626 child_process_clear(&pp->children[i].process);
1629 free(pp->children);
1630 free(pp->pfd);
1633 * When get_next_task added messages to the buffer in its last
1634 * iteration, the buffered output is non empty.
1636 strbuf_write(&pp->buffered_output, stderr);
1637 strbuf_release(&pp->buffered_output);
1639 sigchain_pop_common();
1642 /* returns
1643 * 0 if a new task was started.
1644 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1645 * problem with starting a new command)
1646 * <0 no new job was started, user wishes to shutdown early. Use negative code
1647 * to signal the children.
1649 static int pp_start_one(struct parallel_processes *pp)
1651 int i, code;
1653 for (i = 0; i < pp->max_processes; i++)
1654 if (pp->children[i].state == GIT_CP_FREE)
1655 break;
1656 if (i == pp->max_processes)
1657 BUG("bookkeeping is hard");
1659 code = pp->get_next_task(&pp->children[i].process,
1660 &pp->children[i].err,
1661 pp->data,
1662 &pp->children[i].data);
1663 if (!code) {
1664 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1665 strbuf_reset(&pp->children[i].err);
1666 return 1;
1668 pp->children[i].process.err = -1;
1669 pp->children[i].process.stdout_to_stderr = 1;
1670 pp->children[i].process.no_stdin = 1;
1672 if (start_command(&pp->children[i].process)) {
1673 code = pp->start_failure(&pp->children[i].err,
1674 pp->data,
1675 pp->children[i].data);
1676 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1677 strbuf_reset(&pp->children[i].err);
1678 if (code)
1679 pp->shutdown = 1;
1680 return code;
1683 pp->nr_processes++;
1684 pp->children[i].state = GIT_CP_WORKING;
1685 pp->pfd[i].fd = pp->children[i].process.err;
1686 return 0;
1689 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1691 int i;
1693 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1694 if (errno == EINTR)
1695 continue;
1696 pp_cleanup(pp);
1697 die_errno("poll");
1700 /* Buffer output from all pipes. */
1701 for (i = 0; i < pp->max_processes; i++) {
1702 if (pp->children[i].state == GIT_CP_WORKING &&
1703 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1704 int n = strbuf_read_once(&pp->children[i].err,
1705 pp->children[i].process.err, 0);
1706 if (n == 0) {
1707 close(pp->children[i].process.err);
1708 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1709 } else if (n < 0)
1710 if (errno != EAGAIN)
1711 die_errno("read");
1716 static void pp_output(struct parallel_processes *pp)
1718 int i = pp->output_owner;
1719 if (pp->children[i].state == GIT_CP_WORKING &&
1720 pp->children[i].err.len) {
1721 strbuf_write(&pp->children[i].err, stderr);
1722 strbuf_reset(&pp->children[i].err);
1726 static int pp_collect_finished(struct parallel_processes *pp)
1728 int i, code;
1729 int n = pp->max_processes;
1730 int result = 0;
1732 while (pp->nr_processes > 0) {
1733 for (i = 0; i < pp->max_processes; i++)
1734 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1735 break;
1736 if (i == pp->max_processes)
1737 break;
1739 code = finish_command(&pp->children[i].process);
1741 code = pp->task_finished(code,
1742 &pp->children[i].err, pp->data,
1743 pp->children[i].data);
1745 if (code)
1746 result = code;
1747 if (code < 0)
1748 break;
1750 pp->nr_processes--;
1751 pp->children[i].state = GIT_CP_FREE;
1752 pp->pfd[i].fd = -1;
1753 child_process_init(&pp->children[i].process);
1755 if (i != pp->output_owner) {
1756 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1757 strbuf_reset(&pp->children[i].err);
1758 } else {
1759 strbuf_write(&pp->children[i].err, stderr);
1760 strbuf_reset(&pp->children[i].err);
1762 /* Output all other finished child processes */
1763 strbuf_write(&pp->buffered_output, stderr);
1764 strbuf_reset(&pp->buffered_output);
1767 * Pick next process to output live.
1768 * NEEDSWORK:
1769 * For now we pick it randomly by doing a round
1770 * robin. Later we may want to pick the one with
1771 * the most output or the longest or shortest
1772 * running process time.
1774 for (i = 0; i < n; i++)
1775 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1776 break;
1777 pp->output_owner = (pp->output_owner + i) % n;
1780 return result;
1783 int run_processes_parallel(int n,
1784 get_next_task_fn get_next_task,
1785 start_failure_fn start_failure,
1786 task_finished_fn task_finished,
1787 void *pp_cb)
1789 int i, code;
1790 int output_timeout = 100;
1791 int spawn_cap = 4;
1792 struct parallel_processes pp;
1794 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1795 while (1) {
1796 for (i = 0;
1797 i < spawn_cap && !pp.shutdown &&
1798 pp.nr_processes < pp.max_processes;
1799 i++) {
1800 code = pp_start_one(&pp);
1801 if (!code)
1802 continue;
1803 if (code < 0) {
1804 pp.shutdown = 1;
1805 kill_children(&pp, -code);
1807 break;
1809 if (!pp.nr_processes)
1810 break;
1811 pp_buffer_stderr(&pp, output_timeout);
1812 pp_output(&pp);
1813 code = pp_collect_finished(&pp);
1814 if (code) {
1815 pp.shutdown = 1;
1816 if (code < 0)
1817 kill_children(&pp, -code);
1821 pp_cleanup(&pp);
1822 return 0;
1825 int run_processes_parallel_tr2(int n, get_next_task_fn get_next_task,
1826 start_failure_fn start_failure,
1827 task_finished_fn task_finished, void *pp_cb,
1828 const char *tr2_category, const char *tr2_label)
1830 int result;
1832 trace2_region_enter_printf(tr2_category, tr2_label, NULL, "max:%d",
1833 ((n < 1) ? online_cpus() : n));
1835 result = run_processes_parallel(n, get_next_task, start_failure,
1836 task_finished, pp_cb);
1838 trace2_region_leave(tr2_category, tr2_label, NULL);
1840 return result;
1843 int run_auto_maintenance(int quiet)
1845 int enabled;
1846 struct child_process maint = CHILD_PROCESS_INIT;
1848 if (!git_config_get_bool("maintenance.auto", &enabled) &&
1849 !enabled)
1850 return 0;
1852 maint.git_cmd = 1;
1853 maint.close_object_store = 1;
1854 strvec_pushl(&maint.args, "maintenance", "run", "--auto", NULL);
1855 strvec_push(&maint.args, quiet ? "--quiet" : "--no-quiet");
1857 return run_command(&maint);
1860 void prepare_other_repo_env(struct strvec *env_array, const char *new_git_dir)
1862 const char * const *var;
1864 for (var = local_repo_env; *var; var++) {
1865 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT) &&
1866 strcmp(*var, CONFIG_COUNT_ENVIRONMENT))
1867 strvec_push(env_array, *var);
1869 strvec_pushf(env_array, "%s=%s", GIT_DIR_ENVIRONMENT, new_git_dir);
1872 enum start_bg_result start_bg_command(struct child_process *cmd,
1873 start_bg_wait_cb *wait_cb,
1874 void *cb_data,
1875 unsigned int timeout_sec)
1877 enum start_bg_result sbgr = SBGR_ERROR;
1878 int ret;
1879 int wait_status;
1880 pid_t pid_seen;
1881 time_t time_limit;
1884 * We do not allow clean-on-exit because the child process
1885 * should persist in the background and possibly/probably
1886 * after this process exits. So we don't want to kill the
1887 * child during our atexit routine.
1889 if (cmd->clean_on_exit)
1890 BUG("start_bg_command() does not allow non-zero clean_on_exit");
1892 if (!cmd->trace2_child_class)
1893 cmd->trace2_child_class = "background";
1895 ret = start_command(cmd);
1896 if (ret) {
1898 * We assume that if `start_command()` fails, we
1899 * either get a complete `trace2_child_start() /
1900 * trace2_child_exit()` pair or it fails before the
1901 * `trace2_child_start()` is emitted, so we do not
1902 * need to worry about it here.
1904 * We also assume that `start_command()` does not add
1905 * us to the cleanup list. And that it calls
1906 * calls `child_process_clear()`.
1908 sbgr = SBGR_ERROR;
1909 goto done;
1912 time(&time_limit);
1913 time_limit += timeout_sec;
1915 wait:
1916 pid_seen = waitpid(cmd->pid, &wait_status, WNOHANG);
1918 if (!pid_seen) {
1920 * The child is currently running. Ask the callback
1921 * if the child is ready to do work or whether we
1922 * should keep waiting for it to boot up.
1924 ret = (*wait_cb)(cmd, cb_data);
1925 if (!ret) {
1927 * The child is running and "ready".
1929 trace2_child_ready(cmd, "ready");
1930 sbgr = SBGR_READY;
1931 goto done;
1932 } else if (ret > 0) {
1934 * The callback said to give it more time to boot up
1935 * (subject to our timeout limit).
1937 time_t now;
1939 time(&now);
1940 if (now < time_limit)
1941 goto wait;
1944 * Our timeout has expired. We don't try to
1945 * kill the child, but rather let it continue
1946 * (hopefully) trying to startup.
1948 trace2_child_ready(cmd, "timeout");
1949 sbgr = SBGR_TIMEOUT;
1950 goto done;
1951 } else {
1953 * The cb gave up on this child. It is still running,
1954 * but our cb got an error trying to probe it.
1956 trace2_child_ready(cmd, "error");
1957 sbgr = SBGR_CB_ERROR;
1958 goto done;
1962 else if (pid_seen == cmd->pid) {
1963 int child_code = -1;
1966 * The child started, but exited or was terminated
1967 * before becoming "ready".
1969 * We try to match the behavior of `wait_or_whine()`
1970 * WRT the handling of WIFSIGNALED() and WIFEXITED()
1971 * and convert the child's status to a return code for
1972 * tracing purposes and emit the `trace2_child_exit()`
1973 * event.
1975 * We do not want the wait_or_whine() error message
1976 * because we will be called by client-side library
1977 * routines.
1979 if (WIFEXITED(wait_status))
1980 child_code = WEXITSTATUS(wait_status);
1981 else if (WIFSIGNALED(wait_status))
1982 child_code = WTERMSIG(wait_status) + 128;
1983 trace2_child_exit(cmd, child_code);
1985 sbgr = SBGR_DIED;
1986 goto done;
1989 else if (pid_seen < 0 && errno == EINTR)
1990 goto wait;
1992 trace2_child_exit(cmd, -1);
1993 sbgr = SBGR_ERROR;
1995 done:
1996 child_process_clear(cmd);
1997 invalidate_lstat_cache();
1998 return sbgr;