always quote shell arguments to test -z/-n
[git/gitweb.git] / run-command.c
blobe4593cd99b13fdbfec02939526ac151270aa20f5
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"
9 void child_process_init(struct child_process *child)
11 memset(child, 0, sizeof(*child));
12 argv_array_init(&child->args);
13 argv_array_init(&child->env_array);
16 void child_process_clear(struct child_process *child)
18 argv_array_clear(&child->args);
19 argv_array_clear(&child->env_array);
22 struct child_to_clean {
23 pid_t pid;
24 struct child_to_clean *next;
26 static struct child_to_clean *children_to_clean;
27 static int installed_child_cleanup_handler;
29 static void cleanup_children(int sig, int in_signal)
31 while (children_to_clean) {
32 struct child_to_clean *p = children_to_clean;
33 children_to_clean = p->next;
34 kill(p->pid, sig);
35 if (!in_signal)
36 free(p);
40 static void cleanup_children_on_signal(int sig)
42 cleanup_children(sig, 1);
43 sigchain_pop(sig);
44 raise(sig);
47 static void cleanup_children_on_exit(void)
49 cleanup_children(SIGTERM, 0);
52 static void mark_child_for_cleanup(pid_t pid)
54 struct child_to_clean *p = xmalloc(sizeof(*p));
55 p->pid = pid;
56 p->next = children_to_clean;
57 children_to_clean = p;
59 if (!installed_child_cleanup_handler) {
60 atexit(cleanup_children_on_exit);
61 sigchain_push_common(cleanup_children_on_signal);
62 installed_child_cleanup_handler = 1;
66 static void clear_child_for_cleanup(pid_t pid)
68 struct child_to_clean **pp;
70 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
71 struct child_to_clean *clean_me = *pp;
73 if (clean_me->pid == pid) {
74 *pp = clean_me->next;
75 free(clean_me);
76 return;
81 static inline void close_pair(int fd[2])
83 close(fd[0]);
84 close(fd[1]);
87 #ifndef GIT_WINDOWS_NATIVE
88 static inline void dup_devnull(int to)
90 int fd = open("/dev/null", O_RDWR);
91 if (fd < 0)
92 die_errno(_("open /dev/null failed"));
93 if (dup2(fd, to) < 0)
94 die_errno(_("dup2(%d,%d) failed"), fd, to);
95 close(fd);
97 #endif
99 static char *locate_in_PATH(const char *file)
101 const char *p = getenv("PATH");
102 struct strbuf buf = STRBUF_INIT;
104 if (!p || !*p)
105 return NULL;
107 while (1) {
108 const char *end = strchrnul(p, ':');
110 strbuf_reset(&buf);
112 /* POSIX specifies an empty entry as the current directory. */
113 if (end != p) {
114 strbuf_add(&buf, p, end - p);
115 strbuf_addch(&buf, '/');
117 strbuf_addstr(&buf, file);
119 if (!access(buf.buf, F_OK))
120 return strbuf_detach(&buf, NULL);
122 if (!*end)
123 break;
124 p = end + 1;
127 strbuf_release(&buf);
128 return NULL;
131 static int exists_in_PATH(const char *file)
133 char *r = locate_in_PATH(file);
134 free(r);
135 return r != NULL;
138 int sane_execvp(const char *file, char * const argv[])
140 if (!execvp(file, argv))
141 return 0; /* cannot happen ;-) */
144 * When a command can't be found because one of the directories
145 * listed in $PATH is unsearchable, execvp reports EACCES, but
146 * careful usability testing (read: analysis of occasional bug
147 * reports) reveals that "No such file or directory" is more
148 * intuitive.
150 * We avoid commands with "/", because execvp will not do $PATH
151 * lookups in that case.
153 * The reassignment of EACCES to errno looks like a no-op below,
154 * but we need to protect against exists_in_PATH overwriting errno.
156 if (errno == EACCES && !strchr(file, '/'))
157 errno = exists_in_PATH(file) ? EACCES : ENOENT;
158 else if (errno == ENOTDIR && !strchr(file, '/'))
159 errno = ENOENT;
160 return -1;
163 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
165 if (!argv[0])
166 die("BUG: shell command is empty");
168 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
169 #ifndef GIT_WINDOWS_NATIVE
170 argv_array_push(out, SHELL_PATH);
171 #else
172 argv_array_push(out, "sh");
173 #endif
174 argv_array_push(out, "-c");
177 * If we have no extra arguments, we do not even need to
178 * bother with the "$@" magic.
180 if (!argv[1])
181 argv_array_push(out, argv[0]);
182 else
183 argv_array_pushf(out, "%s \"$@\"", argv[0]);
186 argv_array_pushv(out, argv);
187 return out->argv;
190 #ifndef GIT_WINDOWS_NATIVE
191 static int execv_shell_cmd(const char **argv)
193 struct argv_array nargv = ARGV_ARRAY_INIT;
194 prepare_shell_cmd(&nargv, argv);
195 trace_argv_printf(nargv.argv, "trace: exec:");
196 sane_execvp(nargv.argv[0], (char **)nargv.argv);
197 argv_array_clear(&nargv);
198 return -1;
200 #endif
202 #ifndef GIT_WINDOWS_NATIVE
203 static int child_notifier = -1;
205 static void notify_parent(void)
208 * execvp failed. If possible, we'd like to let start_command
209 * know, so failures like ENOENT can be handled right away; but
210 * otherwise, finish_command will still report the error.
212 xwrite(child_notifier, "", 1);
214 #endif
216 static inline void set_cloexec(int fd)
218 int flags = fcntl(fd, F_GETFD);
219 if (flags >= 0)
220 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
223 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
225 int status, code = -1;
226 pid_t waiting;
227 int failed_errno = 0;
229 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
230 ; /* nothing */
231 if (in_signal)
232 return 0;
234 if (waiting < 0) {
235 failed_errno = errno;
236 error("waitpid for %s failed: %s", argv0, strerror(errno));
237 } else if (waiting != pid) {
238 error("waitpid is confused (%s)", argv0);
239 } else if (WIFSIGNALED(status)) {
240 code = WTERMSIG(status);
241 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
242 error("%s died of signal %d", argv0, code);
244 * This return value is chosen so that code & 0xff
245 * mimics the exit code that a POSIX shell would report for
246 * a program that died from this signal.
248 code += 128;
249 } else if (WIFEXITED(status)) {
250 code = WEXITSTATUS(status);
252 * Convert special exit code when execvp failed.
254 if (code == 127) {
255 code = -1;
256 failed_errno = ENOENT;
258 } else {
259 error("waitpid is confused (%s)", argv0);
262 clear_child_for_cleanup(pid);
264 errno = failed_errno;
265 return code;
268 int start_command(struct child_process *cmd)
270 int need_in, need_out, need_err;
271 int fdin[2], fdout[2], fderr[2];
272 int failed_errno;
273 char *str;
275 if (!cmd->argv)
276 cmd->argv = cmd->args.argv;
277 if (!cmd->env)
278 cmd->env = cmd->env_array.argv;
281 * In case of errors we must keep the promise to close FDs
282 * that have been passed in via ->in and ->out.
285 need_in = !cmd->no_stdin && cmd->in < 0;
286 if (need_in) {
287 if (pipe(fdin) < 0) {
288 failed_errno = errno;
289 if (cmd->out > 0)
290 close(cmd->out);
291 str = "standard input";
292 goto fail_pipe;
294 cmd->in = fdin[1];
297 need_out = !cmd->no_stdout
298 && !cmd->stdout_to_stderr
299 && cmd->out < 0;
300 if (need_out) {
301 if (pipe(fdout) < 0) {
302 failed_errno = errno;
303 if (need_in)
304 close_pair(fdin);
305 else if (cmd->in)
306 close(cmd->in);
307 str = "standard output";
308 goto fail_pipe;
310 cmd->out = fdout[0];
313 need_err = !cmd->no_stderr && cmd->err < 0;
314 if (need_err) {
315 if (pipe(fderr) < 0) {
316 failed_errno = errno;
317 if (need_in)
318 close_pair(fdin);
319 else if (cmd->in)
320 close(cmd->in);
321 if (need_out)
322 close_pair(fdout);
323 else if (cmd->out)
324 close(cmd->out);
325 str = "standard error";
326 fail_pipe:
327 error("cannot create %s pipe for %s: %s",
328 str, cmd->argv[0], strerror(failed_errno));
329 child_process_clear(cmd);
330 errno = failed_errno;
331 return -1;
333 cmd->err = fderr[0];
336 trace_argv_printf(cmd->argv, "trace: run_command:");
337 fflush(NULL);
339 #ifndef GIT_WINDOWS_NATIVE
341 int notify_pipe[2];
342 if (pipe(notify_pipe))
343 notify_pipe[0] = notify_pipe[1] = -1;
345 cmd->pid = fork();
346 failed_errno = errno;
347 if (!cmd->pid) {
349 * Redirect the channel to write syscall error messages to
350 * before redirecting the process's stderr so that all die()
351 * in subsequent call paths use the parent's stderr.
353 if (cmd->no_stderr || need_err) {
354 int child_err = dup(2);
355 set_cloexec(child_err);
356 set_error_handle(fdopen(child_err, "w"));
359 close(notify_pipe[0]);
360 set_cloexec(notify_pipe[1]);
361 child_notifier = notify_pipe[1];
362 atexit(notify_parent);
364 if (cmd->no_stdin)
365 dup_devnull(0);
366 else if (need_in) {
367 dup2(fdin[0], 0);
368 close_pair(fdin);
369 } else if (cmd->in) {
370 dup2(cmd->in, 0);
371 close(cmd->in);
374 if (cmd->no_stderr)
375 dup_devnull(2);
376 else if (need_err) {
377 dup2(fderr[1], 2);
378 close_pair(fderr);
379 } else if (cmd->err > 1) {
380 dup2(cmd->err, 2);
381 close(cmd->err);
384 if (cmd->no_stdout)
385 dup_devnull(1);
386 else if (cmd->stdout_to_stderr)
387 dup2(2, 1);
388 else if (need_out) {
389 dup2(fdout[1], 1);
390 close_pair(fdout);
391 } else if (cmd->out > 1) {
392 dup2(cmd->out, 1);
393 close(cmd->out);
396 if (cmd->dir && chdir(cmd->dir))
397 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
398 cmd->dir);
399 if (cmd->env) {
400 for (; *cmd->env; cmd->env++) {
401 if (strchr(*cmd->env, '='))
402 putenv((char *)*cmd->env);
403 else
404 unsetenv(*cmd->env);
407 if (cmd->git_cmd)
408 execv_git_cmd(cmd->argv);
409 else if (cmd->use_shell)
410 execv_shell_cmd(cmd->argv);
411 else
412 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
413 if (errno == ENOENT) {
414 if (!cmd->silent_exec_failure)
415 error("cannot run %s: %s", cmd->argv[0],
416 strerror(ENOENT));
417 exit(127);
418 } else {
419 die_errno("cannot exec '%s'", cmd->argv[0]);
422 if (cmd->pid < 0)
423 error("cannot fork() for %s: %s", cmd->argv[0],
424 strerror(errno));
425 else if (cmd->clean_on_exit)
426 mark_child_for_cleanup(cmd->pid);
429 * Wait for child's execvp. If the execvp succeeds (or if fork()
430 * failed), EOF is seen immediately by the parent. Otherwise, the
431 * child process sends a single byte.
432 * Note that use of this infrastructure is completely advisory,
433 * therefore, we keep error checks minimal.
435 close(notify_pipe[1]);
436 if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
438 * At this point we know that fork() succeeded, but execvp()
439 * failed. Errors have been reported to our stderr.
441 wait_or_whine(cmd->pid, cmd->argv[0], 0);
442 failed_errno = errno;
443 cmd->pid = -1;
445 close(notify_pipe[0]);
447 #else
449 int fhin = 0, fhout = 1, fherr = 2;
450 const char **sargv = cmd->argv;
451 struct argv_array nargv = ARGV_ARRAY_INIT;
453 if (cmd->no_stdin)
454 fhin = open("/dev/null", O_RDWR);
455 else if (need_in)
456 fhin = dup(fdin[0]);
457 else if (cmd->in)
458 fhin = dup(cmd->in);
460 if (cmd->no_stderr)
461 fherr = open("/dev/null", O_RDWR);
462 else if (need_err)
463 fherr = dup(fderr[1]);
464 else if (cmd->err > 2)
465 fherr = dup(cmd->err);
467 if (cmd->no_stdout)
468 fhout = open("/dev/null", O_RDWR);
469 else if (cmd->stdout_to_stderr)
470 fhout = dup(fherr);
471 else if (need_out)
472 fhout = dup(fdout[1]);
473 else if (cmd->out > 1)
474 fhout = dup(cmd->out);
476 if (cmd->git_cmd)
477 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
478 else if (cmd->use_shell)
479 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
481 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
482 cmd->dir, fhin, fhout, fherr);
483 failed_errno = errno;
484 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
485 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
486 if (cmd->clean_on_exit && cmd->pid >= 0)
487 mark_child_for_cleanup(cmd->pid);
489 argv_array_clear(&nargv);
490 cmd->argv = sargv;
491 if (fhin != 0)
492 close(fhin);
493 if (fhout != 1)
494 close(fhout);
495 if (fherr != 2)
496 close(fherr);
498 #endif
500 if (cmd->pid < 0) {
501 if (need_in)
502 close_pair(fdin);
503 else if (cmd->in)
504 close(cmd->in);
505 if (need_out)
506 close_pair(fdout);
507 else if (cmd->out)
508 close(cmd->out);
509 if (need_err)
510 close_pair(fderr);
511 else if (cmd->err)
512 close(cmd->err);
513 child_process_clear(cmd);
514 errno = failed_errno;
515 return -1;
518 if (need_in)
519 close(fdin[0]);
520 else if (cmd->in)
521 close(cmd->in);
523 if (need_out)
524 close(fdout[1]);
525 else if (cmd->out)
526 close(cmd->out);
528 if (need_err)
529 close(fderr[1]);
530 else if (cmd->err)
531 close(cmd->err);
533 return 0;
536 int finish_command(struct child_process *cmd)
538 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
539 child_process_clear(cmd);
540 return ret;
543 int finish_command_in_signal(struct child_process *cmd)
545 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
549 int run_command(struct child_process *cmd)
551 int code;
553 if (cmd->out < 0 || cmd->err < 0)
554 die("BUG: run_command with a pipe can cause deadlock");
556 code = start_command(cmd);
557 if (code)
558 return code;
559 return finish_command(cmd);
562 int run_command_v_opt(const char **argv, int opt)
564 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
567 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
569 struct child_process cmd = CHILD_PROCESS_INIT;
570 cmd.argv = argv;
571 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
572 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
573 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
574 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
575 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
576 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
577 cmd.dir = dir;
578 cmd.env = env;
579 return run_command(&cmd);
582 #ifndef NO_PTHREADS
583 static pthread_t main_thread;
584 static int main_thread_set;
585 static pthread_key_t async_key;
586 static pthread_key_t async_die_counter;
588 static void *run_thread(void *data)
590 struct async *async = data;
591 intptr_t ret;
593 if (async->isolate_sigpipe) {
594 sigset_t mask;
595 sigemptyset(&mask);
596 sigaddset(&mask, SIGPIPE);
597 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
598 ret = error("unable to block SIGPIPE in async thread");
599 return (void *)ret;
603 pthread_setspecific(async_key, async);
604 ret = async->proc(async->proc_in, async->proc_out, async->data);
605 return (void *)ret;
608 static NORETURN void die_async(const char *err, va_list params)
610 vreportf("fatal: ", err, params);
612 if (in_async()) {
613 struct async *async = pthread_getspecific(async_key);
614 if (async->proc_in >= 0)
615 close(async->proc_in);
616 if (async->proc_out >= 0)
617 close(async->proc_out);
618 pthread_exit((void *)128);
621 exit(128);
624 static int async_die_is_recursing(void)
626 void *ret = pthread_getspecific(async_die_counter);
627 pthread_setspecific(async_die_counter, (void *)1);
628 return ret != NULL;
631 int in_async(void)
633 if (!main_thread_set)
634 return 0; /* no asyncs started yet */
635 return !pthread_equal(main_thread, pthread_self());
638 void NORETURN async_exit(int code)
640 pthread_exit((void *)(intptr_t)code);
643 #else
645 static struct {
646 void (**handlers)(void);
647 size_t nr;
648 size_t alloc;
649 } git_atexit_hdlrs;
651 static int git_atexit_installed;
653 static void git_atexit_dispatch(void)
655 size_t i;
657 for (i=git_atexit_hdlrs.nr ; i ; i--)
658 git_atexit_hdlrs.handlers[i-1]();
661 static void git_atexit_clear(void)
663 free(git_atexit_hdlrs.handlers);
664 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
665 git_atexit_installed = 0;
668 #undef atexit
669 int git_atexit(void (*handler)(void))
671 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
672 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
673 if (!git_atexit_installed) {
674 if (atexit(&git_atexit_dispatch))
675 return -1;
676 git_atexit_installed = 1;
678 return 0;
680 #define atexit git_atexit
682 static int process_is_async;
683 int in_async(void)
685 return process_is_async;
688 void NORETURN async_exit(int code)
690 exit(code);
693 #endif
695 int start_async(struct async *async)
697 int need_in, need_out;
698 int fdin[2], fdout[2];
699 int proc_in, proc_out;
701 need_in = async->in < 0;
702 if (need_in) {
703 if (pipe(fdin) < 0) {
704 if (async->out > 0)
705 close(async->out);
706 return error("cannot create pipe: %s", strerror(errno));
708 async->in = fdin[1];
711 need_out = async->out < 0;
712 if (need_out) {
713 if (pipe(fdout) < 0) {
714 if (need_in)
715 close_pair(fdin);
716 else if (async->in)
717 close(async->in);
718 return error("cannot create pipe: %s", strerror(errno));
720 async->out = fdout[0];
723 if (need_in)
724 proc_in = fdin[0];
725 else if (async->in)
726 proc_in = async->in;
727 else
728 proc_in = -1;
730 if (need_out)
731 proc_out = fdout[1];
732 else if (async->out)
733 proc_out = async->out;
734 else
735 proc_out = -1;
737 #ifdef NO_PTHREADS
738 /* Flush stdio before fork() to avoid cloning buffers */
739 fflush(NULL);
741 async->pid = fork();
742 if (async->pid < 0) {
743 error("fork (async) failed: %s", strerror(errno));
744 goto error;
746 if (!async->pid) {
747 if (need_in)
748 close(fdin[1]);
749 if (need_out)
750 close(fdout[0]);
751 git_atexit_clear();
752 process_is_async = 1;
753 exit(!!async->proc(proc_in, proc_out, async->data));
756 mark_child_for_cleanup(async->pid);
758 if (need_in)
759 close(fdin[0]);
760 else if (async->in)
761 close(async->in);
763 if (need_out)
764 close(fdout[1]);
765 else if (async->out)
766 close(async->out);
767 #else
768 if (!main_thread_set) {
770 * We assume that the first time that start_async is called
771 * it is from the main thread.
773 main_thread_set = 1;
774 main_thread = pthread_self();
775 pthread_key_create(&async_key, NULL);
776 pthread_key_create(&async_die_counter, NULL);
777 set_die_routine(die_async);
778 set_die_is_recursing_routine(async_die_is_recursing);
781 if (proc_in >= 0)
782 set_cloexec(proc_in);
783 if (proc_out >= 0)
784 set_cloexec(proc_out);
785 async->proc_in = proc_in;
786 async->proc_out = proc_out;
788 int err = pthread_create(&async->tid, NULL, run_thread, async);
789 if (err) {
790 error("cannot create thread: %s", strerror(err));
791 goto error;
794 #endif
795 return 0;
797 error:
798 if (need_in)
799 close_pair(fdin);
800 else if (async->in)
801 close(async->in);
803 if (need_out)
804 close_pair(fdout);
805 else if (async->out)
806 close(async->out);
807 return -1;
810 int finish_async(struct async *async)
812 #ifdef NO_PTHREADS
813 return wait_or_whine(async->pid, "child process", 0);
814 #else
815 void *ret = (void *)(intptr_t)(-1);
817 if (pthread_join(async->tid, &ret))
818 error("pthread_join failed");
819 return (int)(intptr_t)ret;
820 #endif
823 const char *find_hook(const char *name)
825 static struct strbuf path = STRBUF_INIT;
827 strbuf_reset(&path);
828 strbuf_git_path(&path, "hooks/%s", name);
829 if (access(path.buf, X_OK) < 0)
830 return NULL;
831 return path.buf;
834 int run_hook_ve(const char *const *env, const char *name, va_list args)
836 struct child_process hook = CHILD_PROCESS_INIT;
837 const char *p;
839 p = find_hook(name);
840 if (!p)
841 return 0;
843 argv_array_push(&hook.args, p);
844 while ((p = va_arg(args, const char *)))
845 argv_array_push(&hook.args, p);
846 hook.env = env;
847 hook.no_stdin = 1;
848 hook.stdout_to_stderr = 1;
850 return run_command(&hook);
853 int run_hook_le(const char *const *env, const char *name, ...)
855 va_list args;
856 int ret;
858 va_start(args, name);
859 ret = run_hook_ve(env, name, args);
860 va_end(args);
862 return ret;
865 int capture_command(struct child_process *cmd, struct strbuf *buf, size_t hint)
867 cmd->out = -1;
868 if (start_command(cmd) < 0)
869 return -1;
871 if (strbuf_read(buf, cmd->out, hint) < 0) {
872 close(cmd->out);
873 finish_command(cmd); /* throw away exit code */
874 return -1;
877 close(cmd->out);
878 return finish_command(cmd);
881 enum child_state {
882 GIT_CP_FREE,
883 GIT_CP_WORKING,
884 GIT_CP_WAIT_CLEANUP,
887 struct parallel_processes {
888 void *data;
890 int max_processes;
891 int nr_processes;
893 get_next_task_fn get_next_task;
894 start_failure_fn start_failure;
895 task_finished_fn task_finished;
897 struct {
898 enum child_state state;
899 struct child_process process;
900 struct strbuf err;
901 void *data;
902 } *children;
904 * The struct pollfd is logically part of *children,
905 * but the system call expects it as its own array.
907 struct pollfd *pfd;
909 unsigned shutdown : 1;
911 int output_owner;
912 struct strbuf buffered_output; /* of finished children */
915 static int default_start_failure(struct strbuf *out,
916 void *pp_cb,
917 void *pp_task_cb)
919 return 0;
922 static int default_task_finished(int result,
923 struct strbuf *out,
924 void *pp_cb,
925 void *pp_task_cb)
927 return 0;
930 static void kill_children(struct parallel_processes *pp, int signo)
932 int i, n = pp->max_processes;
934 for (i = 0; i < n; i++)
935 if (pp->children[i].state == GIT_CP_WORKING)
936 kill(pp->children[i].process.pid, signo);
939 static struct parallel_processes *pp_for_signal;
941 static void handle_children_on_signal(int signo)
943 kill_children(pp_for_signal, signo);
944 sigchain_pop(signo);
945 raise(signo);
948 static void pp_init(struct parallel_processes *pp,
949 int n,
950 get_next_task_fn get_next_task,
951 start_failure_fn start_failure,
952 task_finished_fn task_finished,
953 void *data)
955 int i;
957 if (n < 1)
958 n = online_cpus();
960 pp->max_processes = n;
962 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
964 pp->data = data;
965 if (!get_next_task)
966 die("BUG: you need to specify a get_next_task function");
967 pp->get_next_task = get_next_task;
969 pp->start_failure = start_failure ? start_failure : default_start_failure;
970 pp->task_finished = task_finished ? task_finished : default_task_finished;
972 pp->nr_processes = 0;
973 pp->output_owner = 0;
974 pp->shutdown = 0;
975 pp->children = xcalloc(n, sizeof(*pp->children));
976 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
977 strbuf_init(&pp->buffered_output, 0);
979 for (i = 0; i < n; i++) {
980 strbuf_init(&pp->children[i].err, 0);
981 child_process_init(&pp->children[i].process);
982 pp->pfd[i].events = POLLIN | POLLHUP;
983 pp->pfd[i].fd = -1;
986 pp_for_signal = pp;
987 sigchain_push_common(handle_children_on_signal);
990 static void pp_cleanup(struct parallel_processes *pp)
992 int i;
994 trace_printf("run_processes_parallel: done");
995 for (i = 0; i < pp->max_processes; i++) {
996 strbuf_release(&pp->children[i].err);
997 child_process_clear(&pp->children[i].process);
1000 free(pp->children);
1001 free(pp->pfd);
1004 * When get_next_task added messages to the buffer in its last
1005 * iteration, the buffered output is non empty.
1007 strbuf_write(&pp->buffered_output, stderr);
1008 strbuf_release(&pp->buffered_output);
1010 sigchain_pop_common();
1013 /* returns
1014 * 0 if a new task was started.
1015 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1016 * problem with starting a new command)
1017 * <0 no new job was started, user wishes to shutdown early. Use negative code
1018 * to signal the children.
1020 static int pp_start_one(struct parallel_processes *pp)
1022 int i, code;
1024 for (i = 0; i < pp->max_processes; i++)
1025 if (pp->children[i].state == GIT_CP_FREE)
1026 break;
1027 if (i == pp->max_processes)
1028 die("BUG: bookkeeping is hard");
1030 code = pp->get_next_task(&pp->children[i].process,
1031 &pp->children[i].err,
1032 pp->data,
1033 &pp->children[i].data);
1034 if (!code) {
1035 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1036 strbuf_reset(&pp->children[i].err);
1037 return 1;
1039 pp->children[i].process.err = -1;
1040 pp->children[i].process.stdout_to_stderr = 1;
1041 pp->children[i].process.no_stdin = 1;
1043 if (start_command(&pp->children[i].process)) {
1044 code = pp->start_failure(&pp->children[i].err,
1045 pp->data,
1046 &pp->children[i].data);
1047 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1048 strbuf_reset(&pp->children[i].err);
1049 if (code)
1050 pp->shutdown = 1;
1051 return code;
1054 pp->nr_processes++;
1055 pp->children[i].state = GIT_CP_WORKING;
1056 pp->pfd[i].fd = pp->children[i].process.err;
1057 return 0;
1060 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1062 int i;
1064 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1065 if (errno == EINTR)
1066 continue;
1067 pp_cleanup(pp);
1068 die_errno("poll");
1071 /* Buffer output from all pipes. */
1072 for (i = 0; i < pp->max_processes; i++) {
1073 if (pp->children[i].state == GIT_CP_WORKING &&
1074 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1075 int n = strbuf_read_once(&pp->children[i].err,
1076 pp->children[i].process.err, 0);
1077 if (n == 0) {
1078 close(pp->children[i].process.err);
1079 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1080 } else if (n < 0)
1081 if (errno != EAGAIN)
1082 die_errno("read");
1087 static void pp_output(struct parallel_processes *pp)
1089 int i = pp->output_owner;
1090 if (pp->children[i].state == GIT_CP_WORKING &&
1091 pp->children[i].err.len) {
1092 strbuf_write(&pp->children[i].err, stderr);
1093 strbuf_reset(&pp->children[i].err);
1097 static int pp_collect_finished(struct parallel_processes *pp)
1099 int i, code;
1100 int n = pp->max_processes;
1101 int result = 0;
1103 while (pp->nr_processes > 0) {
1104 for (i = 0; i < pp->max_processes; i++)
1105 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1106 break;
1107 if (i == pp->max_processes)
1108 break;
1110 code = finish_command(&pp->children[i].process);
1112 code = pp->task_finished(code,
1113 &pp->children[i].err, pp->data,
1114 &pp->children[i].data);
1116 if (code)
1117 result = code;
1118 if (code < 0)
1119 break;
1121 pp->nr_processes--;
1122 pp->children[i].state = GIT_CP_FREE;
1123 pp->pfd[i].fd = -1;
1124 child_process_init(&pp->children[i].process);
1126 if (i != pp->output_owner) {
1127 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1128 strbuf_reset(&pp->children[i].err);
1129 } else {
1130 strbuf_write(&pp->children[i].err, stderr);
1131 strbuf_reset(&pp->children[i].err);
1133 /* Output all other finished child processes */
1134 strbuf_write(&pp->buffered_output, stderr);
1135 strbuf_reset(&pp->buffered_output);
1138 * Pick next process to output live.
1139 * NEEDSWORK:
1140 * For now we pick it randomly by doing a round
1141 * robin. Later we may want to pick the one with
1142 * the most output or the longest or shortest
1143 * running process time.
1145 for (i = 0; i < n; i++)
1146 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1147 break;
1148 pp->output_owner = (pp->output_owner + i) % n;
1151 return result;
1154 int run_processes_parallel(int n,
1155 get_next_task_fn get_next_task,
1156 start_failure_fn start_failure,
1157 task_finished_fn task_finished,
1158 void *pp_cb)
1160 int i, code;
1161 int output_timeout = 100;
1162 int spawn_cap = 4;
1163 struct parallel_processes pp;
1165 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1166 while (1) {
1167 for (i = 0;
1168 i < spawn_cap && !pp.shutdown &&
1169 pp.nr_processes < pp.max_processes;
1170 i++) {
1171 code = pp_start_one(&pp);
1172 if (!code)
1173 continue;
1174 if (code < 0) {
1175 pp.shutdown = 1;
1176 kill_children(&pp, -code);
1178 break;
1180 if (!pp.nr_processes)
1181 break;
1182 pp_buffer_stderr(&pp, output_timeout);
1183 pp_output(&pp);
1184 code = pp_collect_finished(&pp);
1185 if (code) {
1186 pp.shutdown = 1;
1187 if (code < 0)
1188 kill_children(&pp, -code);
1192 pp_cleanup(&pp);
1193 return 0;