The eleventh batch
[git/gitster.git] / run-command.c
blob94f2f3079ff754a0445e1c443c4991691879d04e
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 char *git_shell_path(void)
279 #ifndef GIT_WINDOWS_NATIVE
280 return xstrdup(SHELL_PATH);
281 #else
282 char *p = locate_in_PATH("sh");
283 convert_slashes(p);
284 return p;
285 #endif
288 static const char **prepare_shell_cmd(struct strvec *out, const char **argv)
290 if (!argv[0])
291 BUG("shell command is empty");
293 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
294 strvec_push_nodup(out, git_shell_path());
295 strvec_push(out, "-c");
298 * If we have no extra arguments, we do not even need to
299 * bother with the "$@" magic.
301 if (!argv[1])
302 strvec_push(out, argv[0]);
303 else
304 strvec_pushf(out, "%s \"$@\"", argv[0]);
307 strvec_pushv(out, argv);
308 return out->v;
311 #ifndef GIT_WINDOWS_NATIVE
312 static int child_notifier = -1;
314 enum child_errcode {
315 CHILD_ERR_CHDIR,
316 CHILD_ERR_DUP2,
317 CHILD_ERR_CLOSE,
318 CHILD_ERR_SIGPROCMASK,
319 CHILD_ERR_SILENT,
320 CHILD_ERR_ERRNO
323 struct child_err {
324 enum child_errcode err;
325 int syserr; /* errno */
328 static void child_die(enum child_errcode err)
330 struct child_err buf;
332 buf.err = err;
333 buf.syserr = errno;
335 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
336 xwrite(child_notifier, &buf, sizeof(buf));
337 _exit(1);
340 static void child_dup2(int fd, int to)
342 if (dup2(fd, to) < 0)
343 child_die(CHILD_ERR_DUP2);
346 static void child_close(int fd)
348 if (close(fd))
349 child_die(CHILD_ERR_CLOSE);
352 static void child_close_pair(int fd[2])
354 child_close(fd[0]);
355 child_close(fd[1]);
358 static void child_error_fn(const char *err UNUSED, va_list params UNUSED)
360 const char msg[] = "error() should not be called in child\n";
361 xwrite(2, msg, sizeof(msg) - 1);
364 static void child_warn_fn(const char *err UNUSED, va_list params UNUSED)
366 const char msg[] = "warn() should not be called in child\n";
367 xwrite(2, msg, sizeof(msg) - 1);
370 static void NORETURN child_die_fn(const char *err UNUSED, va_list params UNUSED)
372 const char msg[] = "die() should not be called in child\n";
373 xwrite(2, msg, sizeof(msg) - 1);
374 _exit(2);
377 /* this runs in the parent process */
378 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
380 static void (*old_errfn)(const char *err, va_list params);
381 report_fn die_message_routine = get_die_message_routine();
383 old_errfn = get_error_routine();
384 set_error_routine(die_message_routine);
385 errno = cerr->syserr;
387 switch (cerr->err) {
388 case CHILD_ERR_CHDIR:
389 error_errno("exec '%s': cd to '%s' failed",
390 cmd->args.v[0], cmd->dir);
391 break;
392 case CHILD_ERR_DUP2:
393 error_errno("dup2() in child failed");
394 break;
395 case CHILD_ERR_CLOSE:
396 error_errno("close() in child failed");
397 break;
398 case CHILD_ERR_SIGPROCMASK:
399 error_errno("sigprocmask failed restoring signals");
400 break;
401 case CHILD_ERR_SILENT:
402 break;
403 case CHILD_ERR_ERRNO:
404 error_errno("cannot exec '%s'", cmd->args.v[0]);
405 break;
407 set_error_routine(old_errfn);
410 static int prepare_cmd(struct strvec *out, const struct child_process *cmd)
412 if (!cmd->args.v[0])
413 BUG("command is empty");
416 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
417 * attempt to interpret the command with 'sh'.
419 strvec_push(out, SHELL_PATH);
421 if (cmd->git_cmd) {
422 prepare_git_cmd(out, cmd->args.v);
423 } else if (cmd->use_shell) {
424 prepare_shell_cmd(out, cmd->args.v);
425 } else {
426 strvec_pushv(out, cmd->args.v);
430 * If there are no dir separator characters in the command then perform
431 * a path lookup and use the resolved path as the command to exec. If
432 * there are dir separator characters, we have exec attempt to invoke
433 * the command directly.
435 if (!has_dir_sep(out->v[1])) {
436 char *program = locate_in_PATH(out->v[1]);
437 if (program) {
438 free((char *)out->v[1]);
439 out->v[1] = program;
440 } else {
441 strvec_clear(out);
442 errno = ENOENT;
443 return -1;
447 return 0;
450 static char **prep_childenv(const char *const *deltaenv)
452 extern char **environ;
453 char **childenv;
454 struct string_list env = STRING_LIST_INIT_DUP;
455 struct strbuf key = STRBUF_INIT;
456 const char *const *p;
457 int i;
459 /* Construct a sorted string list consisting of the current environ */
460 for (p = (const char *const *) environ; p && *p; p++) {
461 const char *equals = strchr(*p, '=');
463 if (equals) {
464 strbuf_reset(&key);
465 strbuf_add(&key, *p, equals - *p);
466 string_list_append(&env, key.buf)->util = (void *) *p;
467 } else {
468 string_list_append(&env, *p)->util = (void *) *p;
471 string_list_sort(&env);
473 /* Merge in 'deltaenv' with the current environ */
474 for (p = deltaenv; p && *p; p++) {
475 const char *equals = strchr(*p, '=');
477 if (equals) {
478 /* ('key=value'), insert or replace entry */
479 strbuf_reset(&key);
480 strbuf_add(&key, *p, equals - *p);
481 string_list_insert(&env, key.buf)->util = (void *) *p;
482 } else {
483 /* otherwise ('key') remove existing entry */
484 string_list_remove(&env, *p, 0);
488 /* Create an array of 'char *' to be used as the childenv */
489 ALLOC_ARRAY(childenv, env.nr + 1);
490 for (i = 0; i < env.nr; i++)
491 childenv[i] = env.items[i].util;
492 childenv[env.nr] = NULL;
494 string_list_clear(&env, 0);
495 strbuf_release(&key);
496 return childenv;
499 struct atfork_state {
500 #ifndef NO_PTHREADS
501 int cs;
502 #endif
503 sigset_t old;
506 #define CHECK_BUG(err, msg) \
507 do { \
508 int e = (err); \
509 if (e) \
510 BUG("%s: %s", msg, strerror(e)); \
511 } while(0)
513 static void atfork_prepare(struct atfork_state *as)
515 sigset_t all;
517 if (sigfillset(&all))
518 die_errno("sigfillset");
519 #ifdef NO_PTHREADS
520 if (sigprocmask(SIG_SETMASK, &all, &as->old))
521 die_errno("sigprocmask");
522 #else
523 CHECK_BUG(pthread_sigmask(SIG_SETMASK, &all, &as->old),
524 "blocking all signals");
525 CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
526 "disabling cancellation");
527 #endif
530 static void atfork_parent(struct atfork_state *as)
532 #ifdef NO_PTHREADS
533 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
534 die_errno("sigprocmask");
535 #else
536 CHECK_BUG(pthread_setcancelstate(as->cs, NULL),
537 "re-enabling cancellation");
538 CHECK_BUG(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
539 "restoring signal mask");
540 #endif
542 #endif /* GIT_WINDOWS_NATIVE */
544 static inline void set_cloexec(int fd)
546 int flags = fcntl(fd, F_GETFD);
547 if (flags >= 0)
548 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
551 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
553 int status, code = -1;
554 pid_t waiting;
555 int failed_errno = 0;
557 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
558 ; /* nothing */
560 if (waiting < 0) {
561 failed_errno = errno;
562 if (!in_signal)
563 error_errno("waitpid for %s failed", argv0);
564 } else if (waiting != pid) {
565 if (!in_signal)
566 error("waitpid is confused (%s)", argv0);
567 } else if (WIFSIGNALED(status)) {
568 code = WTERMSIG(status);
569 if (!in_signal && code != SIGINT && code != SIGQUIT && code != SIGPIPE)
570 error("%s died of signal %d", argv0, code);
572 * This return value is chosen so that code & 0xff
573 * mimics the exit code that a POSIX shell would report for
574 * a program that died from this signal.
576 code += 128;
577 } else if (WIFEXITED(status)) {
578 code = WEXITSTATUS(status);
579 } else {
580 if (!in_signal)
581 error("waitpid is confused (%s)", argv0);
584 if (!in_signal)
585 clear_child_for_cleanup(pid);
587 errno = failed_errno;
588 return code;
591 static void trace_add_env(struct strbuf *dst, const char *const *deltaenv)
593 struct string_list envs = STRING_LIST_INIT_DUP;
594 const char *const *e;
595 int i;
596 int printed_unset = 0;
598 /* Last one wins, see run-command.c:prep_childenv() for context */
599 for (e = deltaenv; e && *e; e++) {
600 struct strbuf key = STRBUF_INIT;
601 char *equals = strchr(*e, '=');
603 if (equals) {
604 strbuf_add(&key, *e, equals - *e);
605 string_list_insert(&envs, key.buf)->util = equals + 1;
606 } else {
607 string_list_insert(&envs, *e)->util = NULL;
609 strbuf_release(&key);
612 /* "unset X Y...;" */
613 for (i = 0; i < envs.nr; i++) {
614 const char *var = envs.items[i].string;
615 const char *val = envs.items[i].util;
617 if (val || !getenv(var))
618 continue;
620 if (!printed_unset) {
621 strbuf_addstr(dst, " unset");
622 printed_unset = 1;
624 strbuf_addf(dst, " %s", var);
626 if (printed_unset)
627 strbuf_addch(dst, ';');
629 /* ... followed by "A=B C=D ..." */
630 for (i = 0; i < envs.nr; i++) {
631 const char *var = envs.items[i].string;
632 const char *val = envs.items[i].util;
633 const char *oldval;
635 if (!val)
636 continue;
638 oldval = getenv(var);
639 if (oldval && !strcmp(val, oldval))
640 continue;
642 strbuf_addf(dst, " %s=", var);
643 sq_quote_buf_pretty(dst, val);
645 string_list_clear(&envs, 0);
648 static void trace_run_command(const struct child_process *cp)
650 struct strbuf buf = STRBUF_INIT;
652 if (!trace_want(&trace_default_key))
653 return;
655 strbuf_addstr(&buf, "trace: run_command:");
656 if (cp->dir) {
657 strbuf_addstr(&buf, " cd ");
658 sq_quote_buf_pretty(&buf, cp->dir);
659 strbuf_addch(&buf, ';');
661 trace_add_env(&buf, cp->env.v);
662 if (cp->git_cmd)
663 strbuf_addstr(&buf, " git");
664 sq_quote_argv_pretty(&buf, cp->args.v);
666 trace_printf("%s", buf.buf);
667 strbuf_release(&buf);
670 int start_command(struct child_process *cmd)
672 int need_in, need_out, need_err;
673 int fdin[2], fdout[2], fderr[2];
674 int failed_errno;
675 const char *str;
678 * In case of errors we must keep the promise to close FDs
679 * that have been passed in via ->in and ->out.
682 need_in = !cmd->no_stdin && cmd->in < 0;
683 if (need_in) {
684 if (pipe(fdin) < 0) {
685 failed_errno = errno;
686 if (cmd->out > 0)
687 close(cmd->out);
688 str = "standard input";
689 goto fail_pipe;
691 cmd->in = fdin[1];
694 need_out = !cmd->no_stdout
695 && !cmd->stdout_to_stderr
696 && cmd->out < 0;
697 if (need_out) {
698 if (pipe(fdout) < 0) {
699 failed_errno = errno;
700 if (need_in)
701 close_pair(fdin);
702 else if (cmd->in)
703 close(cmd->in);
704 str = "standard output";
705 goto fail_pipe;
707 cmd->out = fdout[0];
710 need_err = !cmd->no_stderr && cmd->err < 0;
711 if (need_err) {
712 if (pipe(fderr) < 0) {
713 failed_errno = errno;
714 if (need_in)
715 close_pair(fdin);
716 else if (cmd->in)
717 close(cmd->in);
718 if (need_out)
719 close_pair(fdout);
720 else if (cmd->out)
721 close(cmd->out);
722 str = "standard error";
723 fail_pipe:
724 error("cannot create %s pipe for %s: %s",
725 str, cmd->args.v[0], strerror(failed_errno));
726 child_process_clear(cmd);
727 errno = failed_errno;
728 return -1;
730 cmd->err = fderr[0];
733 trace2_child_start(cmd);
734 trace_run_command(cmd);
736 fflush(NULL);
738 if (cmd->close_object_store)
739 close_object_store(the_repository->objects);
741 #ifndef GIT_WINDOWS_NATIVE
743 int notify_pipe[2];
744 int null_fd = -1;
745 char **childenv;
746 struct strvec argv = STRVEC_INIT;
747 struct child_err cerr;
748 struct atfork_state as;
750 if (prepare_cmd(&argv, cmd) < 0) {
751 failed_errno = errno;
752 cmd->pid = -1;
753 if (!cmd->silent_exec_failure)
754 error_errno("cannot run %s", cmd->args.v[0]);
755 goto end_of_spawn;
758 trace_argv_printf(&argv.v[1], "trace: start_command:");
760 if (pipe(notify_pipe))
761 notify_pipe[0] = notify_pipe[1] = -1;
763 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
764 null_fd = xopen("/dev/null", O_RDWR | O_CLOEXEC);
765 set_cloexec(null_fd);
768 childenv = prep_childenv(cmd->env.v);
769 atfork_prepare(&as);
772 * NOTE: In order to prevent deadlocking when using threads special
773 * care should be taken with the function calls made in between the
774 * fork() and exec() calls. No calls should be made to functions which
775 * require acquiring a lock (e.g. malloc) as the lock could have been
776 * held by another thread at the time of forking, causing the lock to
777 * never be released in the child process. This means only
778 * Async-Signal-Safe functions are permitted in the child.
780 cmd->pid = fork();
781 failed_errno = errno;
782 if (!cmd->pid) {
783 int sig;
785 * Ensure the default die/error/warn routines do not get
786 * called, they can take stdio locks and malloc.
788 set_die_routine(child_die_fn);
789 set_error_routine(child_error_fn);
790 set_warn_routine(child_warn_fn);
792 close(notify_pipe[0]);
793 set_cloexec(notify_pipe[1]);
794 child_notifier = notify_pipe[1];
796 if (cmd->no_stdin)
797 child_dup2(null_fd, 0);
798 else if (need_in) {
799 child_dup2(fdin[0], 0);
800 child_close_pair(fdin);
801 } else if (cmd->in) {
802 child_dup2(cmd->in, 0);
803 child_close(cmd->in);
806 if (cmd->no_stderr)
807 child_dup2(null_fd, 2);
808 else if (need_err) {
809 child_dup2(fderr[1], 2);
810 child_close_pair(fderr);
811 } else if (cmd->err > 1) {
812 child_dup2(cmd->err, 2);
813 child_close(cmd->err);
816 if (cmd->no_stdout)
817 child_dup2(null_fd, 1);
818 else if (cmd->stdout_to_stderr)
819 child_dup2(2, 1);
820 else if (need_out) {
821 child_dup2(fdout[1], 1);
822 child_close_pair(fdout);
823 } else if (cmd->out > 1) {
824 child_dup2(cmd->out, 1);
825 child_close(cmd->out);
828 if (cmd->dir && chdir(cmd->dir))
829 child_die(CHILD_ERR_CHDIR);
832 * restore default signal handlers here, in case
833 * we catch a signal right before execve below
835 for (sig = 1; sig < NSIG; sig++) {
836 /* ignored signals get reset to SIG_DFL on execve */
837 if (signal(sig, SIG_DFL) == SIG_IGN)
838 signal(sig, SIG_IGN);
841 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
842 child_die(CHILD_ERR_SIGPROCMASK);
845 * Attempt to exec using the command and arguments starting at
846 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
847 * be used in the event exec failed with ENOEXEC at which point
848 * we will try to interpret the command using 'sh'.
850 execve(argv.v[1], (char *const *) argv.v + 1,
851 (char *const *) childenv);
852 if (errno == ENOEXEC)
853 execve(argv.v[0], (char *const *) argv.v,
854 (char *const *) childenv);
856 if (cmd->silent_exec_failure && errno == ENOENT)
857 child_die(CHILD_ERR_SILENT);
858 child_die(CHILD_ERR_ERRNO);
860 atfork_parent(&as);
861 if (cmd->pid < 0)
862 error_errno("cannot fork() for %s", cmd->args.v[0]);
863 else if (cmd->clean_on_exit)
864 mark_child_for_cleanup(cmd->pid, cmd);
867 * Wait for child's exec. If the exec succeeds (or if fork()
868 * failed), EOF is seen immediately by the parent. Otherwise, the
869 * child process sends a child_err struct.
870 * Note that use of this infrastructure is completely advisory,
871 * therefore, we keep error checks minimal.
873 close(notify_pipe[1]);
874 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
876 * At this point we know that fork() succeeded, but exec()
877 * failed. Errors have been reported to our stderr.
879 wait_or_whine(cmd->pid, cmd->args.v[0], 0);
880 child_err_spew(cmd, &cerr);
881 failed_errno = errno;
882 cmd->pid = -1;
884 close(notify_pipe[0]);
886 if (null_fd >= 0)
887 close(null_fd);
888 strvec_clear(&argv);
889 free(childenv);
891 end_of_spawn:
893 #else
895 int fhin = 0, fhout = 1, fherr = 2;
896 const char **sargv = cmd->args.v;
897 struct strvec nargv = STRVEC_INIT;
899 if (cmd->no_stdin)
900 fhin = open("/dev/null", O_RDWR);
901 else if (need_in)
902 fhin = dup(fdin[0]);
903 else if (cmd->in)
904 fhin = dup(cmd->in);
906 if (cmd->no_stderr)
907 fherr = open("/dev/null", O_RDWR);
908 else if (need_err)
909 fherr = dup(fderr[1]);
910 else if (cmd->err > 2)
911 fherr = dup(cmd->err);
913 if (cmd->no_stdout)
914 fhout = open("/dev/null", O_RDWR);
915 else if (cmd->stdout_to_stderr)
916 fhout = dup(fherr);
917 else if (need_out)
918 fhout = dup(fdout[1]);
919 else if (cmd->out > 1)
920 fhout = dup(cmd->out);
922 if (cmd->git_cmd)
923 cmd->args.v = prepare_git_cmd(&nargv, sargv);
924 else if (cmd->use_shell)
925 cmd->args.v = prepare_shell_cmd(&nargv, sargv);
927 trace_argv_printf(cmd->args.v, "trace: start_command:");
928 cmd->pid = mingw_spawnvpe(cmd->args.v[0], cmd->args.v,
929 (char**) cmd->env.v,
930 cmd->dir, fhin, fhout, fherr);
931 failed_errno = errno;
932 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
933 error_errno("cannot spawn %s", cmd->args.v[0]);
934 if (cmd->clean_on_exit && cmd->pid >= 0)
935 mark_child_for_cleanup(cmd->pid, cmd);
937 strvec_clear(&nargv);
938 cmd->args.v = sargv;
939 if (fhin != 0)
940 close(fhin);
941 if (fhout != 1)
942 close(fhout);
943 if (fherr != 2)
944 close(fherr);
946 #endif
948 if (cmd->pid < 0) {
949 trace2_child_exit(cmd, -1);
951 if (need_in)
952 close_pair(fdin);
953 else if (cmd->in)
954 close(cmd->in);
955 if (need_out)
956 close_pair(fdout);
957 else if (cmd->out)
958 close(cmd->out);
959 if (need_err)
960 close_pair(fderr);
961 else if (cmd->err)
962 close(cmd->err);
963 child_process_clear(cmd);
964 errno = failed_errno;
965 return -1;
968 if (need_in)
969 close(fdin[0]);
970 else if (cmd->in)
971 close(cmd->in);
973 if (need_out)
974 close(fdout[1]);
975 else if (cmd->out)
976 close(cmd->out);
978 if (need_err)
979 close(fderr[1]);
980 else if (cmd->err)
981 close(cmd->err);
983 return 0;
986 int finish_command(struct child_process *cmd)
988 int ret = wait_or_whine(cmd->pid, cmd->args.v[0], 0);
989 trace2_child_exit(cmd, ret);
990 child_process_clear(cmd);
991 invalidate_lstat_cache();
992 return ret;
995 int finish_command_in_signal(struct child_process *cmd)
997 int ret = wait_or_whine(cmd->pid, cmd->args.v[0], 1);
998 if (ret != -1)
999 trace2_child_exit(cmd, ret);
1000 return ret;
1004 int run_command(struct child_process *cmd)
1006 int code;
1008 if (cmd->out < 0 || cmd->err < 0)
1009 BUG("run_command with a pipe can cause deadlock");
1011 code = start_command(cmd);
1012 if (code)
1013 return code;
1014 return finish_command(cmd);
1017 #ifndef NO_PTHREADS
1018 static pthread_t main_thread;
1019 static int main_thread_set;
1020 static pthread_key_t async_key;
1021 static pthread_key_t async_die_counter;
1023 static void *run_thread(void *data)
1025 struct async *async = data;
1026 intptr_t ret;
1028 if (async->isolate_sigpipe) {
1029 sigset_t mask;
1030 sigemptyset(&mask);
1031 sigaddset(&mask, SIGPIPE);
1032 if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) {
1033 ret = error("unable to block SIGPIPE in async thread");
1034 return (void *)ret;
1038 pthread_setspecific(async_key, async);
1039 ret = async->proc(async->proc_in, async->proc_out, async->data);
1040 return (void *)ret;
1043 static NORETURN void die_async(const char *err, va_list params)
1045 report_fn die_message_fn = get_die_message_routine();
1047 die_message_fn(err, params);
1049 if (in_async()) {
1050 struct async *async = pthread_getspecific(async_key);
1051 if (async->proc_in >= 0)
1052 close(async->proc_in);
1053 if (async->proc_out >= 0)
1054 close(async->proc_out);
1055 pthread_exit((void *)128);
1058 exit(128);
1061 static int async_die_is_recursing(void)
1063 void *ret = pthread_getspecific(async_die_counter);
1064 pthread_setspecific(async_die_counter, &async_die_counter); /* set to any non-NULL valid pointer */
1065 return ret != NULL;
1068 int in_async(void)
1070 if (!main_thread_set)
1071 return 0; /* no asyncs started yet */
1072 return !pthread_equal(main_thread, pthread_self());
1075 static void NORETURN async_exit(int code)
1077 pthread_exit((void *)(intptr_t)code);
1080 #else
1082 static struct {
1083 void (**handlers)(void);
1084 size_t nr;
1085 size_t alloc;
1086 } git_atexit_hdlrs;
1088 static int git_atexit_installed;
1090 static void git_atexit_dispatch(void)
1092 size_t i;
1094 for (i=git_atexit_hdlrs.nr ; i ; i--)
1095 git_atexit_hdlrs.handlers[i-1]();
1098 static void git_atexit_clear(void)
1100 free(git_atexit_hdlrs.handlers);
1101 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
1102 git_atexit_installed = 0;
1105 #undef atexit
1106 int git_atexit(void (*handler)(void))
1108 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
1109 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
1110 if (!git_atexit_installed) {
1111 if (atexit(&git_atexit_dispatch))
1112 return -1;
1113 git_atexit_installed = 1;
1115 return 0;
1117 #define atexit git_atexit
1119 static int process_is_async;
1120 int in_async(void)
1122 return process_is_async;
1125 static void NORETURN async_exit(int code)
1127 exit(code);
1130 #endif
1132 void check_pipe(int err)
1134 if (err == EPIPE) {
1135 if (in_async())
1136 async_exit(141);
1138 signal(SIGPIPE, SIG_DFL);
1139 raise(SIGPIPE);
1140 /* Should never happen, but just in case... */
1141 exit(141);
1145 int start_async(struct async *async)
1147 int need_in, need_out;
1148 int fdin[2], fdout[2];
1149 int proc_in, proc_out;
1151 need_in = async->in < 0;
1152 if (need_in) {
1153 if (pipe(fdin) < 0) {
1154 if (async->out > 0)
1155 close(async->out);
1156 return error_errno("cannot create pipe");
1158 async->in = fdin[1];
1161 need_out = async->out < 0;
1162 if (need_out) {
1163 if (pipe(fdout) < 0) {
1164 if (need_in)
1165 close_pair(fdin);
1166 else if (async->in)
1167 close(async->in);
1168 return error_errno("cannot create pipe");
1170 async->out = fdout[0];
1173 if (need_in)
1174 proc_in = fdin[0];
1175 else if (async->in)
1176 proc_in = async->in;
1177 else
1178 proc_in = -1;
1180 if (need_out)
1181 proc_out = fdout[1];
1182 else if (async->out)
1183 proc_out = async->out;
1184 else
1185 proc_out = -1;
1187 #ifdef NO_PTHREADS
1188 /* Flush stdio before fork() to avoid cloning buffers */
1189 fflush(NULL);
1191 async->pid = fork();
1192 if (async->pid < 0) {
1193 error_errno("fork (async) failed");
1194 goto error;
1196 if (!async->pid) {
1197 if (need_in)
1198 close(fdin[1]);
1199 if (need_out)
1200 close(fdout[0]);
1201 git_atexit_clear();
1202 process_is_async = 1;
1203 exit(!!async->proc(proc_in, proc_out, async->data));
1206 mark_child_for_cleanup(async->pid, NULL);
1208 if (need_in)
1209 close(fdin[0]);
1210 else if (async->in)
1211 close(async->in);
1213 if (need_out)
1214 close(fdout[1]);
1215 else if (async->out)
1216 close(async->out);
1217 #else
1218 if (!main_thread_set) {
1220 * We assume that the first time that start_async is called
1221 * it is from the main thread.
1223 main_thread_set = 1;
1224 main_thread = pthread_self();
1225 pthread_key_create(&async_key, NULL);
1226 pthread_key_create(&async_die_counter, NULL);
1227 set_die_routine(die_async);
1228 set_die_is_recursing_routine(async_die_is_recursing);
1231 if (proc_in >= 0)
1232 set_cloexec(proc_in);
1233 if (proc_out >= 0)
1234 set_cloexec(proc_out);
1235 async->proc_in = proc_in;
1236 async->proc_out = proc_out;
1238 int err = pthread_create(&async->tid, NULL, run_thread, async);
1239 if (err) {
1240 error(_("cannot create async thread: %s"), strerror(err));
1241 goto error;
1244 #endif
1245 return 0;
1247 error:
1248 if (need_in)
1249 close_pair(fdin);
1250 else if (async->in)
1251 close(async->in);
1253 if (need_out)
1254 close_pair(fdout);
1255 else if (async->out)
1256 close(async->out);
1257 return -1;
1260 int finish_async(struct async *async)
1262 #ifdef NO_PTHREADS
1263 int ret = wait_or_whine(async->pid, "child process", 0);
1265 invalidate_lstat_cache();
1267 return ret;
1268 #else
1269 void *ret = (void *)(intptr_t)(-1);
1271 if (pthread_join(async->tid, &ret))
1272 error("pthread_join failed");
1273 invalidate_lstat_cache();
1274 return (int)(intptr_t)ret;
1276 #endif
1279 int async_with_fork(void)
1281 #ifdef NO_PTHREADS
1282 return 1;
1283 #else
1284 return 0;
1285 #endif
1288 struct io_pump {
1289 /* initialized by caller */
1290 int fd;
1291 int type; /* POLLOUT or POLLIN */
1292 union {
1293 struct {
1294 const char *buf;
1295 size_t len;
1296 } out;
1297 struct {
1298 struct strbuf *buf;
1299 size_t hint;
1300 } in;
1301 } u;
1303 /* returned by pump_io */
1304 int error; /* 0 for success, otherwise errno */
1306 /* internal use */
1307 struct pollfd *pfd;
1310 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1312 int pollsize = 0;
1313 int i;
1315 for (i = 0; i < nr; i++) {
1316 struct io_pump *io = &slots[i];
1317 if (io->fd < 0)
1318 continue;
1319 pfd[pollsize].fd = io->fd;
1320 pfd[pollsize].events = io->type;
1321 io->pfd = &pfd[pollsize++];
1324 if (!pollsize)
1325 return 0;
1327 if (poll(pfd, pollsize, -1) < 0) {
1328 if (errno == EINTR)
1329 return 1;
1330 die_errno("poll failed");
1333 for (i = 0; i < nr; i++) {
1334 struct io_pump *io = &slots[i];
1336 if (io->fd < 0)
1337 continue;
1339 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1340 continue;
1342 if (io->type == POLLOUT) {
1343 ssize_t len;
1346 * Don't use xwrite() here. It loops forever on EAGAIN,
1347 * and we're in our own poll() loop here.
1349 * Note that we lose xwrite()'s handling of MAX_IO_SIZE
1350 * and EINTR, so we have to implement those ourselves.
1352 len = write(io->fd, io->u.out.buf,
1353 io->u.out.len <= MAX_IO_SIZE ?
1354 io->u.out.len : MAX_IO_SIZE);
1355 if (len < 0) {
1356 if (errno != EINTR && errno != EAGAIN &&
1357 errno != ENOSPC) {
1358 io->error = errno;
1359 close(io->fd);
1360 io->fd = -1;
1362 } else {
1363 io->u.out.buf += len;
1364 io->u.out.len -= len;
1365 if (!io->u.out.len) {
1366 close(io->fd);
1367 io->fd = -1;
1372 if (io->type == POLLIN) {
1373 ssize_t len = strbuf_read_once(io->u.in.buf,
1374 io->fd, io->u.in.hint);
1375 if (len < 0)
1376 io->error = errno;
1377 if (len <= 0) {
1378 close(io->fd);
1379 io->fd = -1;
1384 return 1;
1387 static int pump_io(struct io_pump *slots, int nr)
1389 struct pollfd *pfd;
1390 int i;
1392 for (i = 0; i < nr; i++)
1393 slots[i].error = 0;
1395 ALLOC_ARRAY(pfd, nr);
1396 while (pump_io_round(slots, nr, pfd))
1397 ; /* nothing */
1398 free(pfd);
1400 /* There may be multiple errno values, so just pick the first. */
1401 for (i = 0; i < nr; i++) {
1402 if (slots[i].error) {
1403 errno = slots[i].error;
1404 return -1;
1407 return 0;
1411 int pipe_command(struct child_process *cmd,
1412 const char *in, size_t in_len,
1413 struct strbuf *out, size_t out_hint,
1414 struct strbuf *err, size_t err_hint)
1416 struct io_pump io[3];
1417 int nr = 0;
1419 if (in)
1420 cmd->in = -1;
1421 if (out)
1422 cmd->out = -1;
1423 if (err)
1424 cmd->err = -1;
1426 if (start_command(cmd) < 0)
1427 return -1;
1429 if (in) {
1430 if (enable_pipe_nonblock(cmd->in) < 0) {
1431 error_errno("unable to make pipe non-blocking");
1432 close(cmd->in);
1433 if (out)
1434 close(cmd->out);
1435 if (err)
1436 close(cmd->err);
1437 return -1;
1439 io[nr].fd = cmd->in;
1440 io[nr].type = POLLOUT;
1441 io[nr].u.out.buf = in;
1442 io[nr].u.out.len = in_len;
1443 nr++;
1445 if (out) {
1446 io[nr].fd = cmd->out;
1447 io[nr].type = POLLIN;
1448 io[nr].u.in.buf = out;
1449 io[nr].u.in.hint = out_hint;
1450 nr++;
1452 if (err) {
1453 io[nr].fd = cmd->err;
1454 io[nr].type = POLLIN;
1455 io[nr].u.in.buf = err;
1456 io[nr].u.in.hint = err_hint;
1457 nr++;
1460 if (pump_io(io, nr) < 0) {
1461 finish_command(cmd); /* throw away exit code */
1462 return -1;
1465 return finish_command(cmd);
1468 enum child_state {
1469 GIT_CP_FREE,
1470 GIT_CP_WORKING,
1471 GIT_CP_WAIT_CLEANUP,
1474 struct parallel_processes {
1475 size_t nr_processes;
1477 struct {
1478 enum child_state state;
1479 struct child_process process;
1480 struct strbuf err;
1481 void *data;
1482 } *children;
1484 * The struct pollfd is logically part of *children,
1485 * but the system call expects it as its own array.
1487 struct pollfd *pfd;
1489 unsigned shutdown : 1;
1491 size_t output_owner;
1492 struct strbuf buffered_output; /* of finished children */
1495 struct parallel_processes_for_signal {
1496 const struct run_process_parallel_opts *opts;
1497 const struct parallel_processes *pp;
1500 static void kill_children(const struct parallel_processes *pp,
1501 const struct run_process_parallel_opts *opts,
1502 int signo)
1504 for (size_t i = 0; i < opts->processes; i++)
1505 if (pp->children[i].state == GIT_CP_WORKING)
1506 kill(pp->children[i].process.pid, signo);
1509 static void kill_children_signal(const struct parallel_processes_for_signal *pp_sig,
1510 int signo)
1512 kill_children(pp_sig->pp, pp_sig->opts, signo);
1515 static struct parallel_processes_for_signal *pp_for_signal;
1517 static void handle_children_on_signal(int signo)
1519 kill_children_signal(pp_for_signal, signo);
1520 sigchain_pop(signo);
1521 raise(signo);
1524 static void pp_init(struct parallel_processes *pp,
1525 const struct run_process_parallel_opts *opts,
1526 struct parallel_processes_for_signal *pp_sig)
1528 const size_t n = opts->processes;
1530 if (!n)
1531 BUG("you must provide a non-zero number of processes!");
1533 trace_printf("run_processes_parallel: preparing to run up to %"PRIuMAX" tasks",
1534 (uintmax_t)n);
1536 if (!opts->get_next_task)
1537 BUG("you need to specify a get_next_task function");
1539 CALLOC_ARRAY(pp->children, n);
1540 if (!opts->ungroup)
1541 CALLOC_ARRAY(pp->pfd, n);
1543 for (size_t i = 0; i < n; i++) {
1544 strbuf_init(&pp->children[i].err, 0);
1545 child_process_init(&pp->children[i].process);
1546 if (pp->pfd) {
1547 pp->pfd[i].events = POLLIN | POLLHUP;
1548 pp->pfd[i].fd = -1;
1552 pp_sig->pp = pp;
1553 pp_sig->opts = opts;
1554 pp_for_signal = pp_sig;
1555 sigchain_push_common(handle_children_on_signal);
1558 static void pp_cleanup(struct parallel_processes *pp,
1559 const struct run_process_parallel_opts *opts)
1561 trace_printf("run_processes_parallel: done");
1562 for (size_t i = 0; i < opts->processes; i++) {
1563 strbuf_release(&pp->children[i].err);
1564 child_process_clear(&pp->children[i].process);
1567 free(pp->children);
1568 free(pp->pfd);
1571 * When get_next_task added messages to the buffer in its last
1572 * iteration, the buffered output is non empty.
1574 strbuf_write(&pp->buffered_output, stderr);
1575 strbuf_release(&pp->buffered_output);
1577 sigchain_pop_common();
1580 /* returns
1581 * 0 if a new task was started.
1582 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1583 * problem with starting a new command)
1584 * <0 no new job was started, user wishes to shutdown early. Use negative code
1585 * to signal the children.
1587 static int pp_start_one(struct parallel_processes *pp,
1588 const struct run_process_parallel_opts *opts)
1590 size_t i;
1591 int code;
1593 for (i = 0; i < opts->processes; i++)
1594 if (pp->children[i].state == GIT_CP_FREE)
1595 break;
1596 if (i == opts->processes)
1597 BUG("bookkeeping is hard");
1600 * By default, do not inherit stdin from the parent process - otherwise,
1601 * all children would share stdin! Users may overwrite this to provide
1602 * something to the child's stdin by having their 'get_next_task'
1603 * callback assign 0 to .no_stdin and an appropriate integer to .in.
1605 pp->children[i].process.no_stdin = 1;
1607 code = opts->get_next_task(&pp->children[i].process,
1608 opts->ungroup ? NULL : &pp->children[i].err,
1609 opts->data,
1610 &pp->children[i].data);
1611 if (!code) {
1612 if (!opts->ungroup) {
1613 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1614 strbuf_reset(&pp->children[i].err);
1616 return 1;
1618 if (!opts->ungroup) {
1619 pp->children[i].process.err = -1;
1620 pp->children[i].process.stdout_to_stderr = 1;
1623 if (start_command(&pp->children[i].process)) {
1624 if (opts->start_failure)
1625 code = opts->start_failure(opts->ungroup ? NULL :
1626 &pp->children[i].err,
1627 opts->data,
1628 pp->children[i].data);
1629 else
1630 code = 0;
1632 if (!opts->ungroup) {
1633 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1634 strbuf_reset(&pp->children[i].err);
1636 if (code)
1637 pp->shutdown = 1;
1638 return code;
1641 pp->nr_processes++;
1642 pp->children[i].state = GIT_CP_WORKING;
1643 if (pp->pfd)
1644 pp->pfd[i].fd = pp->children[i].process.err;
1645 return 0;
1648 static void pp_buffer_stderr(struct parallel_processes *pp,
1649 const struct run_process_parallel_opts *opts,
1650 int output_timeout)
1652 while (poll(pp->pfd, opts->processes, output_timeout) < 0) {
1653 if (errno == EINTR)
1654 continue;
1655 pp_cleanup(pp, opts);
1656 die_errno("poll");
1659 /* Buffer output from all pipes. */
1660 for (size_t i = 0; i < opts->processes; i++) {
1661 if (pp->children[i].state == GIT_CP_WORKING &&
1662 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1663 int n = strbuf_read_once(&pp->children[i].err,
1664 pp->children[i].process.err, 0);
1665 if (n == 0) {
1666 close(pp->children[i].process.err);
1667 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1668 } else if (n < 0)
1669 if (errno != EAGAIN)
1670 die_errno("read");
1675 static void pp_output(const struct parallel_processes *pp)
1677 size_t i = pp->output_owner;
1679 if (pp->children[i].state == GIT_CP_WORKING &&
1680 pp->children[i].err.len) {
1681 strbuf_write(&pp->children[i].err, stderr);
1682 strbuf_reset(&pp->children[i].err);
1686 static int pp_collect_finished(struct parallel_processes *pp,
1687 const struct run_process_parallel_opts *opts)
1689 int code;
1690 size_t i;
1691 int result = 0;
1693 while (pp->nr_processes > 0) {
1694 for (i = 0; i < opts->processes; i++)
1695 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1696 break;
1697 if (i == opts->processes)
1698 break;
1700 code = finish_command(&pp->children[i].process);
1702 if (opts->task_finished)
1703 code = opts->task_finished(code, opts->ungroup ? NULL :
1704 &pp->children[i].err, opts->data,
1705 pp->children[i].data);
1706 else
1707 code = 0;
1709 if (code)
1710 result = code;
1711 if (code < 0)
1712 break;
1714 pp->nr_processes--;
1715 pp->children[i].state = GIT_CP_FREE;
1716 if (pp->pfd)
1717 pp->pfd[i].fd = -1;
1718 child_process_init(&pp->children[i].process);
1720 if (opts->ungroup) {
1721 ; /* no strbuf_*() work to do here */
1722 } else if (i != pp->output_owner) {
1723 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1724 strbuf_reset(&pp->children[i].err);
1725 } else {
1726 const size_t n = opts->processes;
1728 strbuf_write(&pp->children[i].err, stderr);
1729 strbuf_reset(&pp->children[i].err);
1731 /* Output all other finished child processes */
1732 strbuf_write(&pp->buffered_output, stderr);
1733 strbuf_reset(&pp->buffered_output);
1736 * Pick next process to output live.
1737 * NEEDSWORK:
1738 * For now we pick it randomly by doing a round
1739 * robin. Later we may want to pick the one with
1740 * the most output or the longest or shortest
1741 * running process time.
1743 for (i = 0; i < n; i++)
1744 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1745 break;
1746 pp->output_owner = (pp->output_owner + i) % n;
1749 return result;
1752 void run_processes_parallel(const struct run_process_parallel_opts *opts)
1754 int i, code;
1755 int output_timeout = 100;
1756 int spawn_cap = 4;
1757 struct parallel_processes_for_signal pp_sig;
1758 struct parallel_processes pp = {
1759 .buffered_output = STRBUF_INIT,
1761 /* options */
1762 const char *tr2_category = opts->tr2_category;
1763 const char *tr2_label = opts->tr2_label;
1764 const int do_trace2 = tr2_category && tr2_label;
1766 if (do_trace2)
1767 trace2_region_enter_printf(tr2_category, tr2_label, NULL,
1768 "max:%"PRIuMAX,
1769 (uintmax_t)opts->processes);
1771 pp_init(&pp, opts, &pp_sig);
1772 while (1) {
1773 for (i = 0;
1774 i < spawn_cap && !pp.shutdown &&
1775 pp.nr_processes < opts->processes;
1776 i++) {
1777 code = pp_start_one(&pp, opts);
1778 if (!code)
1779 continue;
1780 if (code < 0) {
1781 pp.shutdown = 1;
1782 kill_children(&pp, opts, -code);
1784 break;
1786 if (!pp.nr_processes)
1787 break;
1788 if (opts->ungroup) {
1789 for (size_t i = 0; i < opts->processes; i++)
1790 pp.children[i].state = GIT_CP_WAIT_CLEANUP;
1791 } else {
1792 pp_buffer_stderr(&pp, opts, output_timeout);
1793 pp_output(&pp);
1795 code = pp_collect_finished(&pp, opts);
1796 if (code) {
1797 pp.shutdown = 1;
1798 if (code < 0)
1799 kill_children(&pp, opts,-code);
1803 pp_cleanup(&pp, opts);
1805 if (do_trace2)
1806 trace2_region_leave(tr2_category, tr2_label, NULL);
1809 int prepare_auto_maintenance(int quiet, struct child_process *maint)
1811 int enabled, auto_detach;
1813 if (!git_config_get_bool("maintenance.auto", &enabled) &&
1814 !enabled)
1815 return 0;
1818 * When `maintenance.autoDetach` isn't set, then we fall back to
1819 * honoring `gc.autoDetach`. This is somewhat weird, but required to
1820 * retain behaviour from when we used to run git-gc(1) here.
1822 if (git_config_get_bool("maintenance.autodetach", &auto_detach) &&
1823 git_config_get_bool("gc.autodetach", &auto_detach))
1824 auto_detach = 1;
1826 maint->git_cmd = 1;
1827 maint->close_object_store = 1;
1828 strvec_pushl(&maint->args, "maintenance", "run", "--auto", NULL);
1829 strvec_push(&maint->args, quiet ? "--quiet" : "--no-quiet");
1830 strvec_push(&maint->args, auto_detach ? "--detach" : "--no-detach");
1832 return 1;
1835 int run_auto_maintenance(int quiet)
1837 struct child_process maint = CHILD_PROCESS_INIT;
1838 if (!prepare_auto_maintenance(quiet, &maint))
1839 return 0;
1840 return run_command(&maint);
1843 void prepare_other_repo_env(struct strvec *env, const char *new_git_dir)
1845 const char * const *var;
1847 for (var = local_repo_env; *var; var++) {
1848 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT) &&
1849 strcmp(*var, CONFIG_COUNT_ENVIRONMENT))
1850 strvec_push(env, *var);
1852 strvec_pushf(env, "%s=%s", GIT_DIR_ENVIRONMENT, new_git_dir);
1855 enum start_bg_result start_bg_command(struct child_process *cmd,
1856 start_bg_wait_cb *wait_cb,
1857 void *cb_data,
1858 unsigned int timeout_sec)
1860 enum start_bg_result sbgr = SBGR_ERROR;
1861 int ret;
1862 int wait_status;
1863 pid_t pid_seen;
1864 time_t time_limit;
1867 * We do not allow clean-on-exit because the child process
1868 * should persist in the background and possibly/probably
1869 * after this process exits. So we don't want to kill the
1870 * child during our atexit routine.
1872 if (cmd->clean_on_exit)
1873 BUG("start_bg_command() does not allow non-zero clean_on_exit");
1875 if (!cmd->trace2_child_class)
1876 cmd->trace2_child_class = "background";
1878 ret = start_command(cmd);
1879 if (ret) {
1881 * We assume that if `start_command()` fails, we
1882 * either get a complete `trace2_child_start() /
1883 * trace2_child_exit()` pair or it fails before the
1884 * `trace2_child_start()` is emitted, so we do not
1885 * need to worry about it here.
1887 * We also assume that `start_command()` does not add
1888 * us to the cleanup list. And that it calls
1889 * `child_process_clear()`.
1891 sbgr = SBGR_ERROR;
1892 goto done;
1895 time(&time_limit);
1896 time_limit += timeout_sec;
1898 wait:
1899 pid_seen = waitpid(cmd->pid, &wait_status, WNOHANG);
1901 if (!pid_seen) {
1903 * The child is currently running. Ask the callback
1904 * if the child is ready to do work or whether we
1905 * should keep waiting for it to boot up.
1907 ret = (*wait_cb)(cmd, cb_data);
1908 if (!ret) {
1910 * The child is running and "ready".
1912 trace2_child_ready(cmd, "ready");
1913 sbgr = SBGR_READY;
1914 goto done;
1915 } else if (ret > 0) {
1917 * The callback said to give it more time to boot up
1918 * (subject to our timeout limit).
1920 time_t now;
1922 time(&now);
1923 if (now < time_limit)
1924 goto wait;
1927 * Our timeout has expired. We don't try to
1928 * kill the child, but rather let it continue
1929 * (hopefully) trying to startup.
1931 trace2_child_ready(cmd, "timeout");
1932 sbgr = SBGR_TIMEOUT;
1933 goto done;
1934 } else {
1936 * The cb gave up on this child. It is still running,
1937 * but our cb got an error trying to probe it.
1939 trace2_child_ready(cmd, "error");
1940 sbgr = SBGR_CB_ERROR;
1941 goto done;
1945 else if (pid_seen == cmd->pid) {
1946 int child_code = -1;
1949 * The child started, but exited or was terminated
1950 * before becoming "ready".
1952 * We try to match the behavior of `wait_or_whine()`
1953 * WRT the handling of WIFSIGNALED() and WIFEXITED()
1954 * and convert the child's status to a return code for
1955 * tracing purposes and emit the `trace2_child_exit()`
1956 * event.
1958 * We do not want the wait_or_whine() error message
1959 * because we will be called by client-side library
1960 * routines.
1962 if (WIFEXITED(wait_status))
1963 child_code = WEXITSTATUS(wait_status);
1964 else if (WIFSIGNALED(wait_status))
1965 child_code = WTERMSIG(wait_status) + 128;
1966 trace2_child_exit(cmd, child_code);
1968 sbgr = SBGR_DIED;
1969 goto done;
1972 else if (pid_seen < 0 && errno == EINTR)
1973 goto wait;
1975 trace2_child_exit(cmd, -1);
1976 sbgr = SBGR_ERROR;
1978 done:
1979 child_process_clear(cmd);
1980 invalidate_lstat_cache();
1981 return sbgr;