repository: pre-initialize hash algo pointer
[git/debian.git] / run-command.c
blob31fc5ea86eb6a3fe3650b8ac50f19f8621d90b9d
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec_cmd.h"
4 #include "sigchain.h"
5 #include "argv-array.h"
6 #include "thread-utils.h"
7 #include "strbuf.h"
8 #include "string-list.h"
10 void child_process_init(struct child_process *child)
12 memset(child, 0, sizeof(*child));
13 argv_array_init(&child->args);
14 argv_array_init(&child->env_array);
17 void child_process_clear(struct child_process *child)
19 argv_array_clear(&child->args);
20 argv_array_clear(&child->env_array);
23 struct child_to_clean {
24 pid_t pid;
25 struct child_process *process;
26 struct child_to_clean *next;
28 static struct child_to_clean *children_to_clean;
29 static int installed_child_cleanup_handler;
31 static void cleanup_children(int sig, int in_signal)
33 struct child_to_clean *children_to_wait_for = NULL;
35 while (children_to_clean) {
36 struct child_to_clean *p = children_to_clean;
37 children_to_clean = p->next;
39 if (p->process && !in_signal) {
40 struct child_process *process = p->process;
41 if (process->clean_on_exit_handler) {
42 trace_printf(
43 "trace: run_command: running exit handler for pid %"
44 PRIuMAX, (uintmax_t)p->pid
46 process->clean_on_exit_handler(process);
50 kill(p->pid, sig);
52 if (p->process && p->process->wait_after_clean) {
53 p->next = children_to_wait_for;
54 children_to_wait_for = p;
55 } else {
56 if (!in_signal)
57 free(p);
61 while (children_to_wait_for) {
62 struct child_to_clean *p = children_to_wait_for;
63 children_to_wait_for = p->next;
65 while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
66 ; /* spin waiting for process exit or error */
68 if (!in_signal)
69 free(p);
73 static void cleanup_children_on_signal(int sig)
75 cleanup_children(sig, 1);
76 sigchain_pop(sig);
77 raise(sig);
80 static void cleanup_children_on_exit(void)
82 cleanup_children(SIGTERM, 0);
85 static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
87 struct child_to_clean *p = xmalloc(sizeof(*p));
88 p->pid = pid;
89 p->process = process;
90 p->next = children_to_clean;
91 children_to_clean = p;
93 if (!installed_child_cleanup_handler) {
94 atexit(cleanup_children_on_exit);
95 sigchain_push_common(cleanup_children_on_signal);
96 installed_child_cleanup_handler = 1;
100 static void clear_child_for_cleanup(pid_t pid)
102 struct child_to_clean **pp;
104 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
105 struct child_to_clean *clean_me = *pp;
107 if (clean_me->pid == pid) {
108 *pp = clean_me->next;
109 free(clean_me);
110 return;
115 static inline void close_pair(int fd[2])
117 close(fd[0]);
118 close(fd[1]);
121 int is_executable(const char *name)
123 struct stat st;
125 if (stat(name, &st) || /* stat, not lstat */
126 !S_ISREG(st.st_mode))
127 return 0;
129 #if defined(GIT_WINDOWS_NATIVE)
131 * On Windows there is no executable bit. The file extension
132 * indicates whether it can be run as an executable, and Git
133 * has special-handling to detect scripts and launch them
134 * through the indicated script interpreter. We test for the
135 * file extension first because virus scanners may make
136 * it quite expensive to open many files.
138 if (ends_with(name, ".exe"))
139 return S_IXUSR;
143 * Now that we know it does not have an executable extension,
144 * peek into the file instead.
146 char buf[3] = { 0 };
147 int n;
148 int fd = open(name, O_RDONLY);
149 st.st_mode &= ~S_IXUSR;
150 if (fd >= 0) {
151 n = read(fd, buf, 2);
152 if (n == 2)
153 /* look for a she-bang */
154 if (!strcmp(buf, "#!"))
155 st.st_mode |= S_IXUSR;
156 close(fd);
159 #endif
160 return st.st_mode & S_IXUSR;
164 * Search $PATH for a command. This emulates the path search that
165 * execvp would perform, without actually executing the command so it
166 * can be used before fork() to prepare to run a command using
167 * execve() or after execvp() to diagnose why it failed.
169 * The caller should ensure that file contains no directory
170 * separators.
172 * Returns the path to the command, as found in $PATH or NULL if the
173 * command could not be found. The caller inherits ownership of the memory
174 * used to store the resultant path.
176 * This should not be used on Windows, where the $PATH search rules
177 * are more complicated (e.g., a search for "foo" should find
178 * "foo.exe").
180 static char *locate_in_PATH(const char *file)
182 const char *p = getenv("PATH");
183 struct strbuf buf = STRBUF_INIT;
185 if (!p || !*p)
186 return NULL;
188 while (1) {
189 const char *end = strchrnul(p, ':');
191 strbuf_reset(&buf);
193 /* POSIX specifies an empty entry as the current directory. */
194 if (end != p) {
195 strbuf_add(&buf, p, end - p);
196 strbuf_addch(&buf, '/');
198 strbuf_addstr(&buf, file);
200 if (is_executable(buf.buf))
201 return strbuf_detach(&buf, NULL);
203 if (!*end)
204 break;
205 p = end + 1;
208 strbuf_release(&buf);
209 return NULL;
212 static int exists_in_PATH(const char *file)
214 char *r = locate_in_PATH(file);
215 free(r);
216 return r != NULL;
219 int sane_execvp(const char *file, char * const argv[])
221 if (!execvp(file, argv))
222 return 0; /* cannot happen ;-) */
225 * When a command can't be found because one of the directories
226 * listed in $PATH is unsearchable, execvp reports EACCES, but
227 * careful usability testing (read: analysis of occasional bug
228 * reports) reveals that "No such file or directory" is more
229 * intuitive.
231 * We avoid commands with "/", because execvp will not do $PATH
232 * lookups in that case.
234 * The reassignment of EACCES to errno looks like a no-op below,
235 * but we need to protect against exists_in_PATH overwriting errno.
237 if (errno == EACCES && !strchr(file, '/'))
238 errno = exists_in_PATH(file) ? EACCES : ENOENT;
239 else if (errno == ENOTDIR && !strchr(file, '/'))
240 errno = ENOENT;
241 return -1;
244 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
246 if (!argv[0])
247 die("BUG: shell command is empty");
249 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
250 #ifndef GIT_WINDOWS_NATIVE
251 argv_array_push(out, SHELL_PATH);
252 #else
253 argv_array_push(out, "sh");
254 #endif
255 argv_array_push(out, "-c");
258 * If we have no extra arguments, we do not even need to
259 * bother with the "$@" magic.
261 if (!argv[1])
262 argv_array_push(out, argv[0]);
263 else
264 argv_array_pushf(out, "%s \"$@\"", argv[0]);
267 argv_array_pushv(out, argv);
268 return out->argv;
271 #ifndef GIT_WINDOWS_NATIVE
272 static int child_notifier = -1;
274 enum child_errcode {
275 CHILD_ERR_CHDIR,
276 CHILD_ERR_DUP2,
277 CHILD_ERR_CLOSE,
278 CHILD_ERR_SIGPROCMASK,
279 CHILD_ERR_ENOENT,
280 CHILD_ERR_SILENT,
281 CHILD_ERR_ERRNO
284 struct child_err {
285 enum child_errcode err;
286 int syserr; /* errno */
289 static void child_die(enum child_errcode err)
291 struct child_err buf;
293 buf.err = err;
294 buf.syserr = errno;
296 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
297 xwrite(child_notifier, &buf, sizeof(buf));
298 _exit(1);
301 static void child_dup2(int fd, int to)
303 if (dup2(fd, to) < 0)
304 child_die(CHILD_ERR_DUP2);
307 static void child_close(int fd)
309 if (close(fd))
310 child_die(CHILD_ERR_CLOSE);
313 static void child_close_pair(int fd[2])
315 child_close(fd[0]);
316 child_close(fd[1]);
320 * parent will make it look like the child spewed a fatal error and died
321 * this is needed to prevent changes to t0061.
323 static void fake_fatal(const char *err, va_list params)
325 vreportf("fatal: ", err, params);
328 static void child_error_fn(const char *err, va_list params)
330 const char msg[] = "error() should not be called in child\n";
331 xwrite(2, msg, sizeof(msg) - 1);
334 static void child_warn_fn(const char *err, va_list params)
336 const char msg[] = "warn() should not be called in child\n";
337 xwrite(2, msg, sizeof(msg) - 1);
340 static void NORETURN child_die_fn(const char *err, va_list params)
342 const char msg[] = "die() should not be called in child\n";
343 xwrite(2, msg, sizeof(msg) - 1);
344 _exit(2);
347 /* this runs in the parent process */
348 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
350 static void (*old_errfn)(const char *err, va_list params);
352 old_errfn = get_error_routine();
353 set_error_routine(fake_fatal);
354 errno = cerr->syserr;
356 switch (cerr->err) {
357 case CHILD_ERR_CHDIR:
358 error_errno("exec '%s': cd to '%s' failed",
359 cmd->argv[0], cmd->dir);
360 break;
361 case CHILD_ERR_DUP2:
362 error_errno("dup2() in child failed");
363 break;
364 case CHILD_ERR_CLOSE:
365 error_errno("close() in child failed");
366 break;
367 case CHILD_ERR_SIGPROCMASK:
368 error_errno("sigprocmask failed restoring signals");
369 break;
370 case CHILD_ERR_ENOENT:
371 error_errno("cannot run %s", cmd->argv[0]);
372 break;
373 case CHILD_ERR_SILENT:
374 break;
375 case CHILD_ERR_ERRNO:
376 error_errno("cannot exec '%s'", cmd->argv[0]);
377 break;
379 set_error_routine(old_errfn);
382 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
384 if (!cmd->argv[0])
385 die("BUG: command is empty");
388 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
389 * attempt to interpret the command with 'sh'.
391 argv_array_push(out, SHELL_PATH);
393 if (cmd->git_cmd) {
394 argv_array_push(out, "git");
395 argv_array_pushv(out, cmd->argv);
396 } else if (cmd->use_shell) {
397 prepare_shell_cmd(out, cmd->argv);
398 } else {
399 argv_array_pushv(out, cmd->argv);
403 * If there are no '/' characters in the command then perform a path
404 * lookup and use the resolved path as the command to exec. If there
405 * are no '/' characters or if the command wasn't found in the path,
406 * have exec attempt to invoke the command directly.
408 if (!strchr(out->argv[1], '/')) {
409 char *program = locate_in_PATH(out->argv[1]);
410 if (program) {
411 free((char *)out->argv[1]);
412 out->argv[1] = program;
417 static char **prep_childenv(const char *const *deltaenv)
419 extern char **environ;
420 char **childenv;
421 struct string_list env = STRING_LIST_INIT_DUP;
422 struct strbuf key = STRBUF_INIT;
423 const char *const *p;
424 int i;
426 /* Construct a sorted string list consisting of the current environ */
427 for (p = (const char *const *) environ; p && *p; p++) {
428 const char *equals = strchr(*p, '=');
430 if (equals) {
431 strbuf_reset(&key);
432 strbuf_add(&key, *p, equals - *p);
433 string_list_append(&env, key.buf)->util = (void *) *p;
434 } else {
435 string_list_append(&env, *p)->util = (void *) *p;
438 string_list_sort(&env);
440 /* Merge in 'deltaenv' with the current environ */
441 for (p = deltaenv; p && *p; p++) {
442 const char *equals = strchr(*p, '=');
444 if (equals) {
445 /* ('key=value'), insert or replace entry */
446 strbuf_reset(&key);
447 strbuf_add(&key, *p, equals - *p);
448 string_list_insert(&env, key.buf)->util = (void *) *p;
449 } else {
450 /* otherwise ('key') remove existing entry */
451 string_list_remove(&env, *p, 0);
455 /* Create an array of 'char *' to be used as the childenv */
456 ALLOC_ARRAY(childenv, env.nr + 1);
457 for (i = 0; i < env.nr; i++)
458 childenv[i] = env.items[i].util;
459 childenv[env.nr] = NULL;
461 string_list_clear(&env, 0);
462 strbuf_release(&key);
463 return childenv;
466 struct atfork_state {
467 #ifndef NO_PTHREADS
468 int cs;
469 #endif
470 sigset_t old;
473 #ifndef NO_PTHREADS
474 static void bug_die(int err, const char *msg)
476 if (err) {
477 errno = err;
478 die_errno("BUG: %s", msg);
481 #endif
483 static void atfork_prepare(struct atfork_state *as)
485 sigset_t all;
487 if (sigfillset(&all))
488 die_errno("sigfillset");
489 #ifdef NO_PTHREADS
490 if (sigprocmask(SIG_SETMASK, &all, &as->old))
491 die_errno("sigprocmask");
492 #else
493 bug_die(pthread_sigmask(SIG_SETMASK, &all, &as->old),
494 "blocking all signals");
495 bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
496 "disabling cancellation");
497 #endif
500 static void atfork_parent(struct atfork_state *as)
502 #ifdef NO_PTHREADS
503 if (sigprocmask(SIG_SETMASK, &as->old, NULL))
504 die_errno("sigprocmask");
505 #else
506 bug_die(pthread_setcancelstate(as->cs, NULL),
507 "re-enabling cancellation");
508 bug_die(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
509 "restoring signal mask");
510 #endif
512 #endif /* GIT_WINDOWS_NATIVE */
514 static inline void set_cloexec(int fd)
516 int flags = fcntl(fd, F_GETFD);
517 if (flags >= 0)
518 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
521 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
523 int status, code = -1;
524 pid_t waiting;
525 int failed_errno = 0;
527 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
528 ; /* nothing */
529 if (in_signal)
530 return 0;
532 if (waiting < 0) {
533 failed_errno = errno;
534 error_errno("waitpid for %s failed", argv0);
535 } else if (waiting != pid) {
536 error("waitpid is confused (%s)", argv0);
537 } else if (WIFSIGNALED(status)) {
538 code = WTERMSIG(status);
539 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
540 error("%s died of signal %d", argv0, code);
542 * This return value is chosen so that code & 0xff
543 * mimics the exit code that a POSIX shell would report for
544 * a program that died from this signal.
546 code += 128;
547 } else if (WIFEXITED(status)) {
548 code = WEXITSTATUS(status);
549 } else {
550 error("waitpid is confused (%s)", argv0);
553 clear_child_for_cleanup(pid);
555 errno = failed_errno;
556 return code;
559 int start_command(struct child_process *cmd)
561 int need_in, need_out, need_err;
562 int fdin[2], fdout[2], fderr[2];
563 int failed_errno;
564 char *str;
566 if (!cmd->argv)
567 cmd->argv = cmd->args.argv;
568 if (!cmd->env)
569 cmd->env = cmd->env_array.argv;
572 * In case of errors we must keep the promise to close FDs
573 * that have been passed in via ->in and ->out.
576 need_in = !cmd->no_stdin && cmd->in < 0;
577 if (need_in) {
578 if (pipe(fdin) < 0) {
579 failed_errno = errno;
580 if (cmd->out > 0)
581 close(cmd->out);
582 str = "standard input";
583 goto fail_pipe;
585 cmd->in = fdin[1];
588 need_out = !cmd->no_stdout
589 && !cmd->stdout_to_stderr
590 && cmd->out < 0;
591 if (need_out) {
592 if (pipe(fdout) < 0) {
593 failed_errno = errno;
594 if (need_in)
595 close_pair(fdin);
596 else if (cmd->in)
597 close(cmd->in);
598 str = "standard output";
599 goto fail_pipe;
601 cmd->out = fdout[0];
604 need_err = !cmd->no_stderr && cmd->err < 0;
605 if (need_err) {
606 if (pipe(fderr) < 0) {
607 failed_errno = errno;
608 if (need_in)
609 close_pair(fdin);
610 else if (cmd->in)
611 close(cmd->in);
612 if (need_out)
613 close_pair(fdout);
614 else if (cmd->out)
615 close(cmd->out);
616 str = "standard error";
617 fail_pipe:
618 error("cannot create %s pipe for %s: %s",
619 str, cmd->argv[0], strerror(failed_errno));
620 child_process_clear(cmd);
621 errno = failed_errno;
622 return -1;
624 cmd->err = fderr[0];
627 trace_argv_printf(cmd->argv, "trace: run_command:");
628 fflush(NULL);
630 #ifndef GIT_WINDOWS_NATIVE
632 int notify_pipe[2];
633 int null_fd = -1;
634 char **childenv;
635 struct argv_array argv = ARGV_ARRAY_INIT;
636 struct child_err cerr;
637 struct atfork_state as;
639 if (pipe(notify_pipe))
640 notify_pipe[0] = notify_pipe[1] = -1;
642 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
643 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
644 if (null_fd < 0)
645 die_errno(_("open /dev/null failed"));
646 set_cloexec(null_fd);
649 prepare_cmd(&argv, cmd);
650 childenv = prep_childenv(cmd->env);
651 atfork_prepare(&as);
654 * NOTE: In order to prevent deadlocking when using threads special
655 * care should be taken with the function calls made in between the
656 * fork() and exec() calls. No calls should be made to functions which
657 * require acquiring a lock (e.g. malloc) as the lock could have been
658 * held by another thread at the time of forking, causing the lock to
659 * never be released in the child process. This means only
660 * Async-Signal-Safe functions are permitted in the child.
662 cmd->pid = fork();
663 failed_errno = errno;
664 if (!cmd->pid) {
665 int sig;
667 * Ensure the default die/error/warn routines do not get
668 * called, they can take stdio locks and malloc.
670 set_die_routine(child_die_fn);
671 set_error_routine(child_error_fn);
672 set_warn_routine(child_warn_fn);
674 close(notify_pipe[0]);
675 set_cloexec(notify_pipe[1]);
676 child_notifier = notify_pipe[1];
678 if (cmd->no_stdin)
679 child_dup2(null_fd, 0);
680 else if (need_in) {
681 child_dup2(fdin[0], 0);
682 child_close_pair(fdin);
683 } else if (cmd->in) {
684 child_dup2(cmd->in, 0);
685 child_close(cmd->in);
688 if (cmd->no_stderr)
689 child_dup2(null_fd, 2);
690 else if (need_err) {
691 child_dup2(fderr[1], 2);
692 child_close_pair(fderr);
693 } else if (cmd->err > 1) {
694 child_dup2(cmd->err, 2);
695 child_close(cmd->err);
698 if (cmd->no_stdout)
699 child_dup2(null_fd, 1);
700 else if (cmd->stdout_to_stderr)
701 child_dup2(2, 1);
702 else if (need_out) {
703 child_dup2(fdout[1], 1);
704 child_close_pair(fdout);
705 } else if (cmd->out > 1) {
706 child_dup2(cmd->out, 1);
707 child_close(cmd->out);
710 if (cmd->dir && chdir(cmd->dir))
711 child_die(CHILD_ERR_CHDIR);
714 * restore default signal handlers here, in case
715 * we catch a signal right before execve below
717 for (sig = 1; sig < NSIG; sig++) {
718 /* ignored signals get reset to SIG_DFL on execve */
719 if (signal(sig, SIG_DFL) == SIG_IGN)
720 signal(sig, SIG_IGN);
723 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
724 child_die(CHILD_ERR_SIGPROCMASK);
727 * Attempt to exec using the command and arguments starting at
728 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
729 * be used in the event exec failed with ENOEXEC at which point
730 * we will try to interpret the command using 'sh'.
732 execve(argv.argv[1], (char *const *) argv.argv + 1,
733 (char *const *) childenv);
734 if (errno == ENOEXEC)
735 execve(argv.argv[0], (char *const *) argv.argv,
736 (char *const *) childenv);
738 if (errno == ENOENT) {
739 if (cmd->silent_exec_failure)
740 child_die(CHILD_ERR_SILENT);
741 child_die(CHILD_ERR_ENOENT);
742 } else {
743 child_die(CHILD_ERR_ERRNO);
746 atfork_parent(&as);
747 if (cmd->pid < 0)
748 error_errno("cannot fork() for %s", cmd->argv[0]);
749 else if (cmd->clean_on_exit)
750 mark_child_for_cleanup(cmd->pid, cmd);
753 * Wait for child's exec. If the exec succeeds (or if fork()
754 * failed), EOF is seen immediately by the parent. Otherwise, the
755 * child process sends a child_err struct.
756 * Note that use of this infrastructure is completely advisory,
757 * therefore, we keep error checks minimal.
759 close(notify_pipe[1]);
760 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
762 * At this point we know that fork() succeeded, but exec()
763 * failed. Errors have been reported to our stderr.
765 wait_or_whine(cmd->pid, cmd->argv[0], 0);
766 child_err_spew(cmd, &cerr);
767 failed_errno = errno;
768 cmd->pid = -1;
770 close(notify_pipe[0]);
772 if (null_fd >= 0)
773 close(null_fd);
774 argv_array_clear(&argv);
775 free(childenv);
777 #else
779 int fhin = 0, fhout = 1, fherr = 2;
780 const char **sargv = cmd->argv;
781 struct argv_array nargv = ARGV_ARRAY_INIT;
783 if (cmd->no_stdin)
784 fhin = open("/dev/null", O_RDWR);
785 else if (need_in)
786 fhin = dup(fdin[0]);
787 else if (cmd->in)
788 fhin = dup(cmd->in);
790 if (cmd->no_stderr)
791 fherr = open("/dev/null", O_RDWR);
792 else if (need_err)
793 fherr = dup(fderr[1]);
794 else if (cmd->err > 2)
795 fherr = dup(cmd->err);
797 if (cmd->no_stdout)
798 fhout = open("/dev/null", O_RDWR);
799 else if (cmd->stdout_to_stderr)
800 fhout = dup(fherr);
801 else if (need_out)
802 fhout = dup(fdout[1]);
803 else if (cmd->out > 1)
804 fhout = dup(cmd->out);
806 if (cmd->git_cmd)
807 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
808 else if (cmd->use_shell)
809 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
811 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
812 cmd->dir, fhin, fhout, fherr);
813 failed_errno = errno;
814 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
815 error_errno("cannot spawn %s", cmd->argv[0]);
816 if (cmd->clean_on_exit && cmd->pid >= 0)
817 mark_child_for_cleanup(cmd->pid, cmd);
819 argv_array_clear(&nargv);
820 cmd->argv = sargv;
821 if (fhin != 0)
822 close(fhin);
823 if (fhout != 1)
824 close(fhout);
825 if (fherr != 2)
826 close(fherr);
828 #endif
830 if (cmd->pid < 0) {
831 if (need_in)
832 close_pair(fdin);
833 else if (cmd->in)
834 close(cmd->in);
835 if (need_out)
836 close_pair(fdout);
837 else if (cmd->out)
838 close(cmd->out);
839 if (need_err)
840 close_pair(fderr);
841 else if (cmd->err)
842 close(cmd->err);
843 child_process_clear(cmd);
844 errno = failed_errno;
845 return -1;
848 if (need_in)
849 close(fdin[0]);
850 else if (cmd->in)
851 close(cmd->in);
853 if (need_out)
854 close(fdout[1]);
855 else if (cmd->out)
856 close(cmd->out);
858 if (need_err)
859 close(fderr[1]);
860 else if (cmd->err)
861 close(cmd->err);
863 return 0;
866 int finish_command(struct child_process *cmd)
868 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
869 child_process_clear(cmd);
870 return ret;
873 int finish_command_in_signal(struct child_process *cmd)
875 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
879 int run_command(struct child_process *cmd)
881 int code;
883 if (cmd->out < 0 || cmd->err < 0)
884 die("BUG: run_command with a pipe can cause deadlock");
886 code = start_command(cmd);
887 if (code)
888 return code;
889 return finish_command(cmd);
892 int run_command_v_opt(const char **argv, int opt)
894 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
897 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
899 struct child_process cmd = CHILD_PROCESS_INIT;
900 cmd.argv = argv;
901 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
902 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
903 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
904 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
905 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
906 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
907 cmd.dir = dir;
908 cmd.env = env;
909 return run_command(&cmd);
912 #ifndef NO_PTHREADS
913 static pthread_t main_thread;
914 static int main_thread_set;
915 static pthread_key_t async_key;
916 static pthread_key_t async_die_counter;
918 static void *run_thread(void *data)
920 struct async *async = data;
921 intptr_t ret;
923 if (async->isolate_sigpipe) {
924 sigset_t mask;
925 sigemptyset(&mask);
926 sigaddset(&mask, SIGPIPE);
927 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
928 ret = error("unable to block SIGPIPE in async thread");
929 return (void *)ret;
933 pthread_setspecific(async_key, async);
934 ret = async->proc(async->proc_in, async->proc_out, async->data);
935 return (void *)ret;
938 static NORETURN void die_async(const char *err, va_list params)
940 vreportf("fatal: ", err, params);
942 if (in_async()) {
943 struct async *async = pthread_getspecific(async_key);
944 if (async->proc_in >= 0)
945 close(async->proc_in);
946 if (async->proc_out >= 0)
947 close(async->proc_out);
948 pthread_exit((void *)128);
951 exit(128);
954 static int async_die_is_recursing(void)
956 void *ret = pthread_getspecific(async_die_counter);
957 pthread_setspecific(async_die_counter, (void *)1);
958 return ret != NULL;
961 int in_async(void)
963 if (!main_thread_set)
964 return 0; /* no asyncs started yet */
965 return !pthread_equal(main_thread, pthread_self());
968 static void NORETURN async_exit(int code)
970 pthread_exit((void *)(intptr_t)code);
973 #else
975 static struct {
976 void (**handlers)(void);
977 size_t nr;
978 size_t alloc;
979 } git_atexit_hdlrs;
981 static int git_atexit_installed;
983 static void git_atexit_dispatch(void)
985 size_t i;
987 for (i=git_atexit_hdlrs.nr ; i ; i--)
988 git_atexit_hdlrs.handlers[i-1]();
991 static void git_atexit_clear(void)
993 free(git_atexit_hdlrs.handlers);
994 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
995 git_atexit_installed = 0;
998 #undef atexit
999 int git_atexit(void (*handler)(void))
1001 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
1002 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
1003 if (!git_atexit_installed) {
1004 if (atexit(&git_atexit_dispatch))
1005 return -1;
1006 git_atexit_installed = 1;
1008 return 0;
1010 #define atexit git_atexit
1012 static int process_is_async;
1013 int in_async(void)
1015 return process_is_async;
1018 static void NORETURN async_exit(int code)
1020 exit(code);
1023 #endif
1025 void check_pipe(int err)
1027 if (err == EPIPE) {
1028 if (in_async())
1029 async_exit(141);
1031 signal(SIGPIPE, SIG_DFL);
1032 raise(SIGPIPE);
1033 /* Should never happen, but just in case... */
1034 exit(141);
1038 int start_async(struct async *async)
1040 int need_in, need_out;
1041 int fdin[2], fdout[2];
1042 int proc_in, proc_out;
1044 need_in = async->in < 0;
1045 if (need_in) {
1046 if (pipe(fdin) < 0) {
1047 if (async->out > 0)
1048 close(async->out);
1049 return error_errno("cannot create pipe");
1051 async->in = fdin[1];
1054 need_out = async->out < 0;
1055 if (need_out) {
1056 if (pipe(fdout) < 0) {
1057 if (need_in)
1058 close_pair(fdin);
1059 else if (async->in)
1060 close(async->in);
1061 return error_errno("cannot create pipe");
1063 async->out = fdout[0];
1066 if (need_in)
1067 proc_in = fdin[0];
1068 else if (async->in)
1069 proc_in = async->in;
1070 else
1071 proc_in = -1;
1073 if (need_out)
1074 proc_out = fdout[1];
1075 else if (async->out)
1076 proc_out = async->out;
1077 else
1078 proc_out = -1;
1080 #ifdef NO_PTHREADS
1081 /* Flush stdio before fork() to avoid cloning buffers */
1082 fflush(NULL);
1084 async->pid = fork();
1085 if (async->pid < 0) {
1086 error_errno("fork (async) failed");
1087 goto error;
1089 if (!async->pid) {
1090 if (need_in)
1091 close(fdin[1]);
1092 if (need_out)
1093 close(fdout[0]);
1094 git_atexit_clear();
1095 process_is_async = 1;
1096 exit(!!async->proc(proc_in, proc_out, async->data));
1099 mark_child_for_cleanup(async->pid, NULL);
1101 if (need_in)
1102 close(fdin[0]);
1103 else if (async->in)
1104 close(async->in);
1106 if (need_out)
1107 close(fdout[1]);
1108 else if (async->out)
1109 close(async->out);
1110 #else
1111 if (!main_thread_set) {
1113 * We assume that the first time that start_async is called
1114 * it is from the main thread.
1116 main_thread_set = 1;
1117 main_thread = pthread_self();
1118 pthread_key_create(&async_key, NULL);
1119 pthread_key_create(&async_die_counter, NULL);
1120 set_die_routine(die_async);
1121 set_die_is_recursing_routine(async_die_is_recursing);
1124 if (proc_in >= 0)
1125 set_cloexec(proc_in);
1126 if (proc_out >= 0)
1127 set_cloexec(proc_out);
1128 async->proc_in = proc_in;
1129 async->proc_out = proc_out;
1131 int err = pthread_create(&async->tid, NULL, run_thread, async);
1132 if (err) {
1133 error_errno("cannot create thread");
1134 goto error;
1137 #endif
1138 return 0;
1140 error:
1141 if (need_in)
1142 close_pair(fdin);
1143 else if (async->in)
1144 close(async->in);
1146 if (need_out)
1147 close_pair(fdout);
1148 else if (async->out)
1149 close(async->out);
1150 return -1;
1153 int finish_async(struct async *async)
1155 #ifdef NO_PTHREADS
1156 return wait_or_whine(async->pid, "child process", 0);
1157 #else
1158 void *ret = (void *)(intptr_t)(-1);
1160 if (pthread_join(async->tid, &ret))
1161 error("pthread_join failed");
1162 return (int)(intptr_t)ret;
1163 #endif
1166 const char *find_hook(const char *name)
1168 static struct strbuf path = STRBUF_INIT;
1170 strbuf_reset(&path);
1171 strbuf_git_path(&path, "hooks/%s", name);
1172 if (access(path.buf, X_OK) < 0) {
1173 int err = errno;
1175 #ifdef STRIP_EXTENSION
1176 strbuf_addstr(&path, STRIP_EXTENSION);
1177 if (access(path.buf, X_OK) >= 0)
1178 return path.buf;
1179 if (errno == EACCES)
1180 err = errno;
1181 #endif
1183 if (err == EACCES && advice_ignored_hook) {
1184 static struct string_list advise_given = STRING_LIST_INIT_DUP;
1186 if (!string_list_lookup(&advise_given, name)) {
1187 string_list_insert(&advise_given, name);
1188 advise(_("The '%s' hook was ignored because "
1189 "it's not set as executable.\n"
1190 "You can disable this warning with "
1191 "`git config advice.ignoredHook false`."),
1192 path.buf);
1195 return NULL;
1197 return path.buf;
1200 int run_hook_ve(const char *const *env, const char *name, va_list args)
1202 struct child_process hook = CHILD_PROCESS_INIT;
1203 const char *p;
1205 p = find_hook(name);
1206 if (!p)
1207 return 0;
1209 argv_array_push(&hook.args, p);
1210 while ((p = va_arg(args, const char *)))
1211 argv_array_push(&hook.args, p);
1212 hook.env = env;
1213 hook.no_stdin = 1;
1214 hook.stdout_to_stderr = 1;
1216 return run_command(&hook);
1219 int run_hook_le(const char *const *env, const char *name, ...)
1221 va_list args;
1222 int ret;
1224 va_start(args, name);
1225 ret = run_hook_ve(env, name, args);
1226 va_end(args);
1228 return ret;
1231 struct io_pump {
1232 /* initialized by caller */
1233 int fd;
1234 int type; /* POLLOUT or POLLIN */
1235 union {
1236 struct {
1237 const char *buf;
1238 size_t len;
1239 } out;
1240 struct {
1241 struct strbuf *buf;
1242 size_t hint;
1243 } in;
1244 } u;
1246 /* returned by pump_io */
1247 int error; /* 0 for success, otherwise errno */
1249 /* internal use */
1250 struct pollfd *pfd;
1253 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1255 int pollsize = 0;
1256 int i;
1258 for (i = 0; i < nr; i++) {
1259 struct io_pump *io = &slots[i];
1260 if (io->fd < 0)
1261 continue;
1262 pfd[pollsize].fd = io->fd;
1263 pfd[pollsize].events = io->type;
1264 io->pfd = &pfd[pollsize++];
1267 if (!pollsize)
1268 return 0;
1270 if (poll(pfd, pollsize, -1) < 0) {
1271 if (errno == EINTR)
1272 return 1;
1273 die_errno("poll failed");
1276 for (i = 0; i < nr; i++) {
1277 struct io_pump *io = &slots[i];
1279 if (io->fd < 0)
1280 continue;
1282 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1283 continue;
1285 if (io->type == POLLOUT) {
1286 ssize_t len = xwrite(io->fd,
1287 io->u.out.buf, io->u.out.len);
1288 if (len < 0) {
1289 io->error = errno;
1290 close(io->fd);
1291 io->fd = -1;
1292 } else {
1293 io->u.out.buf += len;
1294 io->u.out.len -= len;
1295 if (!io->u.out.len) {
1296 close(io->fd);
1297 io->fd = -1;
1302 if (io->type == POLLIN) {
1303 ssize_t len = strbuf_read_once(io->u.in.buf,
1304 io->fd, io->u.in.hint);
1305 if (len < 0)
1306 io->error = errno;
1307 if (len <= 0) {
1308 close(io->fd);
1309 io->fd = -1;
1314 return 1;
1317 static int pump_io(struct io_pump *slots, int nr)
1319 struct pollfd *pfd;
1320 int i;
1322 for (i = 0; i < nr; i++)
1323 slots[i].error = 0;
1325 ALLOC_ARRAY(pfd, nr);
1326 while (pump_io_round(slots, nr, pfd))
1327 ; /* nothing */
1328 free(pfd);
1330 /* There may be multiple errno values, so just pick the first. */
1331 for (i = 0; i < nr; i++) {
1332 if (slots[i].error) {
1333 errno = slots[i].error;
1334 return -1;
1337 return 0;
1341 int pipe_command(struct child_process *cmd,
1342 const char *in, size_t in_len,
1343 struct strbuf *out, size_t out_hint,
1344 struct strbuf *err, size_t err_hint)
1346 struct io_pump io[3];
1347 int nr = 0;
1349 if (in)
1350 cmd->in = -1;
1351 if (out)
1352 cmd->out = -1;
1353 if (err)
1354 cmd->err = -1;
1356 if (start_command(cmd) < 0)
1357 return -1;
1359 if (in) {
1360 io[nr].fd = cmd->in;
1361 io[nr].type = POLLOUT;
1362 io[nr].u.out.buf = in;
1363 io[nr].u.out.len = in_len;
1364 nr++;
1366 if (out) {
1367 io[nr].fd = cmd->out;
1368 io[nr].type = POLLIN;
1369 io[nr].u.in.buf = out;
1370 io[nr].u.in.hint = out_hint;
1371 nr++;
1373 if (err) {
1374 io[nr].fd = cmd->err;
1375 io[nr].type = POLLIN;
1376 io[nr].u.in.buf = err;
1377 io[nr].u.in.hint = err_hint;
1378 nr++;
1381 if (pump_io(io, nr) < 0) {
1382 finish_command(cmd); /* throw away exit code */
1383 return -1;
1386 return finish_command(cmd);
1389 enum child_state {
1390 GIT_CP_FREE,
1391 GIT_CP_WORKING,
1392 GIT_CP_WAIT_CLEANUP,
1395 struct parallel_processes {
1396 void *data;
1398 int max_processes;
1399 int nr_processes;
1401 get_next_task_fn get_next_task;
1402 start_failure_fn start_failure;
1403 task_finished_fn task_finished;
1405 struct {
1406 enum child_state state;
1407 struct child_process process;
1408 struct strbuf err;
1409 void *data;
1410 } *children;
1412 * The struct pollfd is logically part of *children,
1413 * but the system call expects it as its own array.
1415 struct pollfd *pfd;
1417 unsigned shutdown : 1;
1419 int output_owner;
1420 struct strbuf buffered_output; /* of finished children */
1423 static int default_start_failure(struct strbuf *out,
1424 void *pp_cb,
1425 void *pp_task_cb)
1427 return 0;
1430 static int default_task_finished(int result,
1431 struct strbuf *out,
1432 void *pp_cb,
1433 void *pp_task_cb)
1435 return 0;
1438 static void kill_children(struct parallel_processes *pp, int signo)
1440 int i, n = pp->max_processes;
1442 for (i = 0; i < n; i++)
1443 if (pp->children[i].state == GIT_CP_WORKING)
1444 kill(pp->children[i].process.pid, signo);
1447 static struct parallel_processes *pp_for_signal;
1449 static void handle_children_on_signal(int signo)
1451 kill_children(pp_for_signal, signo);
1452 sigchain_pop(signo);
1453 raise(signo);
1456 static void pp_init(struct parallel_processes *pp,
1457 int n,
1458 get_next_task_fn get_next_task,
1459 start_failure_fn start_failure,
1460 task_finished_fn task_finished,
1461 void *data)
1463 int i;
1465 if (n < 1)
1466 n = online_cpus();
1468 pp->max_processes = n;
1470 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1472 pp->data = data;
1473 if (!get_next_task)
1474 die("BUG: you need to specify a get_next_task function");
1475 pp->get_next_task = get_next_task;
1477 pp->start_failure = start_failure ? start_failure : default_start_failure;
1478 pp->task_finished = task_finished ? task_finished : default_task_finished;
1480 pp->nr_processes = 0;
1481 pp->output_owner = 0;
1482 pp->shutdown = 0;
1483 pp->children = xcalloc(n, sizeof(*pp->children));
1484 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1485 strbuf_init(&pp->buffered_output, 0);
1487 for (i = 0; i < n; i++) {
1488 strbuf_init(&pp->children[i].err, 0);
1489 child_process_init(&pp->children[i].process);
1490 pp->pfd[i].events = POLLIN | POLLHUP;
1491 pp->pfd[i].fd = -1;
1494 pp_for_signal = pp;
1495 sigchain_push_common(handle_children_on_signal);
1498 static void pp_cleanup(struct parallel_processes *pp)
1500 int i;
1502 trace_printf("run_processes_parallel: done");
1503 for (i = 0; i < pp->max_processes; i++) {
1504 strbuf_release(&pp->children[i].err);
1505 child_process_clear(&pp->children[i].process);
1508 free(pp->children);
1509 free(pp->pfd);
1512 * When get_next_task added messages to the buffer in its last
1513 * iteration, the buffered output is non empty.
1515 strbuf_write(&pp->buffered_output, stderr);
1516 strbuf_release(&pp->buffered_output);
1518 sigchain_pop_common();
1521 /* returns
1522 * 0 if a new task was started.
1523 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1524 * problem with starting a new command)
1525 * <0 no new job was started, user wishes to shutdown early. Use negative code
1526 * to signal the children.
1528 static int pp_start_one(struct parallel_processes *pp)
1530 int i, code;
1532 for (i = 0; i < pp->max_processes; i++)
1533 if (pp->children[i].state == GIT_CP_FREE)
1534 break;
1535 if (i == pp->max_processes)
1536 die("BUG: bookkeeping is hard");
1538 code = pp->get_next_task(&pp->children[i].process,
1539 &pp->children[i].err,
1540 pp->data,
1541 &pp->children[i].data);
1542 if (!code) {
1543 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1544 strbuf_reset(&pp->children[i].err);
1545 return 1;
1547 pp->children[i].process.err = -1;
1548 pp->children[i].process.stdout_to_stderr = 1;
1549 pp->children[i].process.no_stdin = 1;
1551 if (start_command(&pp->children[i].process)) {
1552 code = pp->start_failure(&pp->children[i].err,
1553 pp->data,
1554 pp->children[i].data);
1555 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1556 strbuf_reset(&pp->children[i].err);
1557 if (code)
1558 pp->shutdown = 1;
1559 return code;
1562 pp->nr_processes++;
1563 pp->children[i].state = GIT_CP_WORKING;
1564 pp->pfd[i].fd = pp->children[i].process.err;
1565 return 0;
1568 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1570 int i;
1572 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1573 if (errno == EINTR)
1574 continue;
1575 pp_cleanup(pp);
1576 die_errno("poll");
1579 /* Buffer output from all pipes. */
1580 for (i = 0; i < pp->max_processes; i++) {
1581 if (pp->children[i].state == GIT_CP_WORKING &&
1582 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1583 int n = strbuf_read_once(&pp->children[i].err,
1584 pp->children[i].process.err, 0);
1585 if (n == 0) {
1586 close(pp->children[i].process.err);
1587 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1588 } else if (n < 0)
1589 if (errno != EAGAIN)
1590 die_errno("read");
1595 static void pp_output(struct parallel_processes *pp)
1597 int i = pp->output_owner;
1598 if (pp->children[i].state == GIT_CP_WORKING &&
1599 pp->children[i].err.len) {
1600 strbuf_write(&pp->children[i].err, stderr);
1601 strbuf_reset(&pp->children[i].err);
1605 static int pp_collect_finished(struct parallel_processes *pp)
1607 int i, code;
1608 int n = pp->max_processes;
1609 int result = 0;
1611 while (pp->nr_processes > 0) {
1612 for (i = 0; i < pp->max_processes; i++)
1613 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1614 break;
1615 if (i == pp->max_processes)
1616 break;
1618 code = finish_command(&pp->children[i].process);
1620 code = pp->task_finished(code,
1621 &pp->children[i].err, pp->data,
1622 pp->children[i].data);
1624 if (code)
1625 result = code;
1626 if (code < 0)
1627 break;
1629 pp->nr_processes--;
1630 pp->children[i].state = GIT_CP_FREE;
1631 pp->pfd[i].fd = -1;
1632 child_process_init(&pp->children[i].process);
1634 if (i != pp->output_owner) {
1635 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1636 strbuf_reset(&pp->children[i].err);
1637 } else {
1638 strbuf_write(&pp->children[i].err, stderr);
1639 strbuf_reset(&pp->children[i].err);
1641 /* Output all other finished child processes */
1642 strbuf_write(&pp->buffered_output, stderr);
1643 strbuf_reset(&pp->buffered_output);
1646 * Pick next process to output live.
1647 * NEEDSWORK:
1648 * For now we pick it randomly by doing a round
1649 * robin. Later we may want to pick the one with
1650 * the most output or the longest or shortest
1651 * running process time.
1653 for (i = 0; i < n; i++)
1654 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1655 break;
1656 pp->output_owner = (pp->output_owner + i) % n;
1659 return result;
1662 int run_processes_parallel(int n,
1663 get_next_task_fn get_next_task,
1664 start_failure_fn start_failure,
1665 task_finished_fn task_finished,
1666 void *pp_cb)
1668 int i, code;
1669 int output_timeout = 100;
1670 int spawn_cap = 4;
1671 struct parallel_processes pp;
1673 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1674 while (1) {
1675 for (i = 0;
1676 i < spawn_cap && !pp.shutdown &&
1677 pp.nr_processes < pp.max_processes;
1678 i++) {
1679 code = pp_start_one(&pp);
1680 if (!code)
1681 continue;
1682 if (code < 0) {
1683 pp.shutdown = 1;
1684 kill_children(&pp, -code);
1686 break;
1688 if (!pp.nr_processes)
1689 break;
1690 pp_buffer_stderr(&pp, output_timeout);
1691 pp_output(&pp);
1692 code = pp_collect_finished(&pp);
1693 if (code) {
1694 pp.shutdown = 1;
1695 if (code < 0)
1696 kill_children(&pp, -code);
1700 pp_cleanup(&pp);
1701 return 0;