run-command: mark path lookup errors with ENOENT
[git] / run-command.c
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
9 void child_process_init(struct child_process *child)
10 {
11         memset(child, 0, sizeof(*child));
12         argv_array_init(&child->args);
13         argv_array_init(&child->env_array);
14 }
15
16 void child_process_clear(struct child_process *child)
17 {
18         argv_array_clear(&child->args);
19         argv_array_clear(&child->env_array);
20 }
21
22 struct child_to_clean {
23         pid_t pid;
24         struct child_process *process;
25         struct child_to_clean *next;
26 };
27 static struct child_to_clean *children_to_clean;
28 static int installed_child_cleanup_handler;
29
30 static void cleanup_children(int sig, int in_signal)
31 {
32         struct child_to_clean *children_to_wait_for = NULL;
33
34         while (children_to_clean) {
35                 struct child_to_clean *p = children_to_clean;
36                 children_to_clean = p->next;
37
38                 if (p->process && !in_signal) {
39                         struct child_process *process = p->process;
40                         if (process->clean_on_exit_handler) {
41                                 trace_printf(
42                                         "trace: run_command: running exit handler for pid %"
43                                         PRIuMAX, (uintmax_t)p->pid
44                                 );
45                                 process->clean_on_exit_handler(process);
46                         }
47                 }
48
49                 kill(p->pid, sig);
50
51                 if (p->process && p->process->wait_after_clean) {
52                         p->next = children_to_wait_for;
53                         children_to_wait_for = p;
54                 } else {
55                         if (!in_signal)
56                                 free(p);
57                 }
58         }
59
60         while (children_to_wait_for) {
61                 struct child_to_clean *p = children_to_wait_for;
62                 children_to_wait_for = p->next;
63
64                 while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
65                         ; /* spin waiting for process exit or error */
66
67                 if (!in_signal)
68                         free(p);
69         }
70 }
71
72 static void cleanup_children_on_signal(int sig)
73 {
74         cleanup_children(sig, 1);
75         sigchain_pop(sig);
76         raise(sig);
77 }
78
79 static void cleanup_children_on_exit(void)
80 {
81         cleanup_children(SIGTERM, 0);
82 }
83
84 static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
85 {
86         struct child_to_clean *p = xmalloc(sizeof(*p));
87         p->pid = pid;
88         p->process = process;
89         p->next = children_to_clean;
90         children_to_clean = p;
91
92         if (!installed_child_cleanup_handler) {
93                 atexit(cleanup_children_on_exit);
94                 sigchain_push_common(cleanup_children_on_signal);
95                 installed_child_cleanup_handler = 1;
96         }
97 }
98
99 static void clear_child_for_cleanup(pid_t pid)
100 {
101         struct child_to_clean **pp;
102
103         for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
104                 struct child_to_clean *clean_me = *pp;
105
106                 if (clean_me->pid == pid) {
107                         *pp = clean_me->next;
108                         free(clean_me);
109                         return;
110                 }
111         }
112 }
113
114 static inline void close_pair(int fd[2])
115 {
116         close(fd[0]);
117         close(fd[1]);
118 }
119
120 int is_executable(const char *name)
121 {
122         struct stat st;
123
124         if (stat(name, &st) || /* stat, not lstat */
125             !S_ISREG(st.st_mode))
126                 return 0;
127
128 #if defined(GIT_WINDOWS_NATIVE)
129         /*
130          * On Windows there is no executable bit. The file extension
131          * indicates whether it can be run as an executable, and Git
132          * has special-handling to detect scripts and launch them
133          * through the indicated script interpreter. We test for the
134          * file extension first because virus scanners may make
135          * it quite expensive to open many files.
136          */
137         if (ends_with(name, ".exe"))
138                 return S_IXUSR;
139
140 {
141         /*
142          * Now that we know it does not have an executable extension,
143          * peek into the file instead.
144          */
145         char buf[3] = { 0 };
146         int n;
147         int fd = open(name, O_RDONLY);
148         st.st_mode &= ~S_IXUSR;
149         if (fd >= 0) {
150                 n = read(fd, buf, 2);
151                 if (n == 2)
152                         /* look for a she-bang */
153                         if (!strcmp(buf, "#!"))
154                                 st.st_mode |= S_IXUSR;
155                 close(fd);
156         }
157 }
158 #endif
159         return st.st_mode & S_IXUSR;
160 }
161
162 /*
163  * Search $PATH for a command.  This emulates the path search that
164  * execvp would perform, without actually executing the command so it
165  * can be used before fork() to prepare to run a command using
166  * execve() or after execvp() to diagnose why it failed.
167  *
168  * The caller should ensure that file contains no directory
169  * separators.
170  *
171  * Returns the path to the command, as found in $PATH or NULL if the
172  * command could not be found.  The caller inherits ownership of the memory
173  * used to store the resultant path.
174  *
175  * This should not be used on Windows, where the $PATH search rules
176  * are more complicated (e.g., a search for "foo" should find
177  * "foo.exe").
178  */
179 static char *locate_in_PATH(const char *file)
180 {
181         const char *p = getenv("PATH");
182         struct strbuf buf = STRBUF_INIT;
183
184         if (!p || !*p)
185                 return NULL;
186
187         while (1) {
188                 const char *end = strchrnul(p, ':');
189
190                 strbuf_reset(&buf);
191
192                 /* POSIX specifies an empty entry as the current directory. */
193                 if (end != p) {
194                         strbuf_add(&buf, p, end - p);
195                         strbuf_addch(&buf, '/');
196                 }
197                 strbuf_addstr(&buf, file);
198
199                 if (is_executable(buf.buf))
200                         return strbuf_detach(&buf, NULL);
201
202                 if (!*end)
203                         break;
204                 p = end + 1;
205         }
206
207         strbuf_release(&buf);
208         return NULL;
209 }
210
211 static int exists_in_PATH(const char *file)
212 {
213         char *r = locate_in_PATH(file);
214         free(r);
215         return r != NULL;
216 }
217
218 int sane_execvp(const char *file, char * const argv[])
219 {
220         if (!execvp(file, argv))
221                 return 0; /* cannot happen ;-) */
222
223         /*
224          * When a command can't be found because one of the directories
225          * listed in $PATH is unsearchable, execvp reports EACCES, but
226          * careful usability testing (read: analysis of occasional bug
227          * reports) reveals that "No such file or directory" is more
228          * intuitive.
229          *
230          * We avoid commands with "/", because execvp will not do $PATH
231          * lookups in that case.
232          *
233          * The reassignment of EACCES to errno looks like a no-op below,
234          * but we need to protect against exists_in_PATH overwriting errno.
235          */
236         if (errno == EACCES && !strchr(file, '/'))
237                 errno = exists_in_PATH(file) ? EACCES : ENOENT;
238         else if (errno == ENOTDIR && !strchr(file, '/'))
239                 errno = ENOENT;
240         return -1;
241 }
242
243 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
244 {
245         if (!argv[0])
246                 die("BUG: shell command is empty");
247
248         if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
249 #ifndef GIT_WINDOWS_NATIVE
250                 argv_array_push(out, SHELL_PATH);
251 #else
252                 argv_array_push(out, "sh");
253 #endif
254                 argv_array_push(out, "-c");
255
256                 /*
257                  * If we have no extra arguments, we do not even need to
258                  * bother with the "$@" magic.
259                  */
260                 if (!argv[1])
261                         argv_array_push(out, argv[0]);
262                 else
263                         argv_array_pushf(out, "%s \"$@\"", argv[0]);
264         }
265
266         argv_array_pushv(out, argv);
267         return out->argv;
268 }
269
270 #ifndef GIT_WINDOWS_NATIVE
271 static int child_notifier = -1;
272
273 enum child_errcode {
274         CHILD_ERR_CHDIR,
275         CHILD_ERR_DUP2,
276         CHILD_ERR_CLOSE,
277         CHILD_ERR_SIGPROCMASK,
278         CHILD_ERR_ENOENT,
279         CHILD_ERR_SILENT,
280         CHILD_ERR_ERRNO
281 };
282
283 struct child_err {
284         enum child_errcode err;
285         int syserr; /* errno */
286 };
287
288 static void child_die(enum child_errcode err)
289 {
290         struct child_err buf;
291
292         buf.err = err;
293         buf.syserr = errno;
294
295         /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
296         xwrite(child_notifier, &buf, sizeof(buf));
297         _exit(1);
298 }
299
300 static void child_dup2(int fd, int to)
301 {
302         if (dup2(fd, to) < 0)
303                 child_die(CHILD_ERR_DUP2);
304 }
305
306 static void child_close(int fd)
307 {
308         if (close(fd))
309                 child_die(CHILD_ERR_CLOSE);
310 }
311
312 static void child_close_pair(int fd[2])
313 {
314         child_close(fd[0]);
315         child_close(fd[1]);
316 }
317
318 /*
319  * parent will make it look like the child spewed a fatal error and died
320  * this is needed to prevent changes to t0061.
321  */
322 static void fake_fatal(const char *err, va_list params)
323 {
324         vreportf("fatal: ", err, params);
325 }
326
327 static void child_error_fn(const char *err, va_list params)
328 {
329         const char msg[] = "error() should not be called in child\n";
330         xwrite(2, msg, sizeof(msg) - 1);
331 }
332
333 static void child_warn_fn(const char *err, va_list params)
334 {
335         const char msg[] = "warn() should not be called in child\n";
336         xwrite(2, msg, sizeof(msg) - 1);
337 }
338
339 static void NORETURN child_die_fn(const char *err, va_list params)
340 {
341         const char msg[] = "die() should not be called in child\n";
342         xwrite(2, msg, sizeof(msg) - 1);
343         _exit(2);
344 }
345
346 /* this runs in the parent process */
347 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
348 {
349         static void (*old_errfn)(const char *err, va_list params);
350
351         old_errfn = get_error_routine();
352         set_error_routine(fake_fatal);
353         errno = cerr->syserr;
354
355         switch (cerr->err) {
356         case CHILD_ERR_CHDIR:
357                 error_errno("exec '%s': cd to '%s' failed",
358                             cmd->argv[0], cmd->dir);
359                 break;
360         case CHILD_ERR_DUP2:
361                 error_errno("dup2() in child failed");
362                 break;
363         case CHILD_ERR_CLOSE:
364                 error_errno("close() in child failed");
365                 break;
366         case CHILD_ERR_SIGPROCMASK:
367                 error_errno("sigprocmask failed restoring signals");
368                 break;
369         case CHILD_ERR_ENOENT:
370                 error_errno("cannot run %s", cmd->argv[0]);
371                 break;
372         case CHILD_ERR_SILENT:
373                 break;
374         case CHILD_ERR_ERRNO:
375                 error_errno("cannot exec '%s'", cmd->argv[0]);
376                 break;
377         }
378         set_error_routine(old_errfn);
379 }
380
381 static int prepare_cmd(struct argv_array *out, const struct child_process *cmd)
382 {
383         if (!cmd->argv[0])
384                 die("BUG: command is empty");
385
386         /*
387          * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
388          * attempt to interpret the command with 'sh'.
389          */
390         argv_array_push(out, SHELL_PATH);
391
392         if (cmd->git_cmd) {
393                 argv_array_push(out, "git");
394                 argv_array_pushv(out, cmd->argv);
395         } else if (cmd->use_shell) {
396                 prepare_shell_cmd(out, cmd->argv);
397         } else {
398                 argv_array_pushv(out, cmd->argv);
399         }
400
401         /*
402          * If there are no '/' characters in the command then perform a path
403          * lookup and use the resolved path as the command to exec.  If there
404          * are '/' characters, we have exec attempt to invoke the command
405          * directly.
406          */
407         if (!strchr(out->argv[1], '/')) {
408                 char *program = locate_in_PATH(out->argv[1]);
409                 if (program) {
410                         free((char *)out->argv[1]);
411                         out->argv[1] = program;
412                 } else {
413                         argv_array_clear(out);
414                         errno = ENOENT;
415                         return -1;
416                 }
417         }
418
419         return 0;
420 }
421
422 static char **prep_childenv(const char *const *deltaenv)
423 {
424         extern char **environ;
425         char **childenv;
426         struct string_list env = STRING_LIST_INIT_DUP;
427         struct strbuf key = STRBUF_INIT;
428         const char *const *p;
429         int i;
430
431         /* Construct a sorted string list consisting of the current environ */
432         for (p = (const char *const *) environ; p && *p; p++) {
433                 const char *equals = strchr(*p, '=');
434
435                 if (equals) {
436                         strbuf_reset(&key);
437                         strbuf_add(&key, *p, equals - *p);
438                         string_list_append(&env, key.buf)->util = (void *) *p;
439                 } else {
440                         string_list_append(&env, *p)->util = (void *) *p;
441                 }
442         }
443         string_list_sort(&env);
444
445         /* Merge in 'deltaenv' with the current environ */
446         for (p = deltaenv; p && *p; p++) {
447                 const char *equals = strchr(*p, '=');
448
449                 if (equals) {
450                         /* ('key=value'), insert or replace entry */
451                         strbuf_reset(&key);
452                         strbuf_add(&key, *p, equals - *p);
453                         string_list_insert(&env, key.buf)->util = (void *) *p;
454                 } else {
455                         /* otherwise ('key') remove existing entry */
456                         string_list_remove(&env, *p, 0);
457                 }
458         }
459
460         /* Create an array of 'char *' to be used as the childenv */
461         ALLOC_ARRAY(childenv, env.nr + 1);
462         for (i = 0; i < env.nr; i++)
463                 childenv[i] = env.items[i].util;
464         childenv[env.nr] = NULL;
465
466         string_list_clear(&env, 0);
467         strbuf_release(&key);
468         return childenv;
469 }
470
471 struct atfork_state {
472 #ifndef NO_PTHREADS
473         int cs;
474 #endif
475         sigset_t old;
476 };
477
478 #ifndef NO_PTHREADS
479 static void bug_die(int err, const char *msg)
480 {
481         if (err) {
482                 errno = err;
483                 die_errno("BUG: %s", msg);
484         }
485 }
486 #endif
487
488 static void atfork_prepare(struct atfork_state *as)
489 {
490         sigset_t all;
491
492         if (sigfillset(&all))
493                 die_errno("sigfillset");
494 #ifdef NO_PTHREADS
495         if (sigprocmask(SIG_SETMASK, &all, &as->old))
496                 die_errno("sigprocmask");
497 #else
498         bug_die(pthread_sigmask(SIG_SETMASK, &all, &as->old),
499                 "blocking all signals");
500         bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
501                 "disabling cancellation");
502 #endif
503 }
504
505 static void atfork_parent(struct atfork_state *as)
506 {
507 #ifdef NO_PTHREADS
508         if (sigprocmask(SIG_SETMASK, &as->old, NULL))
509                 die_errno("sigprocmask");
510 #else
511         bug_die(pthread_setcancelstate(as->cs, NULL),
512                 "re-enabling cancellation");
513         bug_die(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
514                 "restoring signal mask");
515 #endif
516 }
517 #endif /* GIT_WINDOWS_NATIVE */
518
519 static inline void set_cloexec(int fd)
520 {
521         int flags = fcntl(fd, F_GETFD);
522         if (flags >= 0)
523                 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
524 }
525
526 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
527 {
528         int status, code = -1;
529         pid_t waiting;
530         int failed_errno = 0;
531
532         while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
533                 ;       /* nothing */
534         if (in_signal)
535                 return 0;
536
537         if (waiting < 0) {
538                 failed_errno = errno;
539                 error_errno("waitpid for %s failed", argv0);
540         } else if (waiting != pid) {
541                 error("waitpid is confused (%s)", argv0);
542         } else if (WIFSIGNALED(status)) {
543                 code = WTERMSIG(status);
544                 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
545                         error("%s died of signal %d", argv0, code);
546                 /*
547                  * This return value is chosen so that code & 0xff
548                  * mimics the exit code that a POSIX shell would report for
549                  * a program that died from this signal.
550                  */
551                 code += 128;
552         } else if (WIFEXITED(status)) {
553                 code = WEXITSTATUS(status);
554         } else {
555                 error("waitpid is confused (%s)", argv0);
556         }
557
558         clear_child_for_cleanup(pid);
559
560         errno = failed_errno;
561         return code;
562 }
563
564 int start_command(struct child_process *cmd)
565 {
566         int need_in, need_out, need_err;
567         int fdin[2], fdout[2], fderr[2];
568         int failed_errno;
569         char *str;
570
571         if (!cmd->argv)
572                 cmd->argv = cmd->args.argv;
573         if (!cmd->env)
574                 cmd->env = cmd->env_array.argv;
575
576         /*
577          * In case of errors we must keep the promise to close FDs
578          * that have been passed in via ->in and ->out.
579          */
580
581         need_in = !cmd->no_stdin && cmd->in < 0;
582         if (need_in) {
583                 if (pipe(fdin) < 0) {
584                         failed_errno = errno;
585                         if (cmd->out > 0)
586                                 close(cmd->out);
587                         str = "standard input";
588                         goto fail_pipe;
589                 }
590                 cmd->in = fdin[1];
591         }
592
593         need_out = !cmd->no_stdout
594                 && !cmd->stdout_to_stderr
595                 && cmd->out < 0;
596         if (need_out) {
597                 if (pipe(fdout) < 0) {
598                         failed_errno = errno;
599                         if (need_in)
600                                 close_pair(fdin);
601                         else if (cmd->in)
602                                 close(cmd->in);
603                         str = "standard output";
604                         goto fail_pipe;
605                 }
606                 cmd->out = fdout[0];
607         }
608
609         need_err = !cmd->no_stderr && cmd->err < 0;
610         if (need_err) {
611                 if (pipe(fderr) < 0) {
612                         failed_errno = errno;
613                         if (need_in)
614                                 close_pair(fdin);
615                         else if (cmd->in)
616                                 close(cmd->in);
617                         if (need_out)
618                                 close_pair(fdout);
619                         else if (cmd->out)
620                                 close(cmd->out);
621                         str = "standard error";
622 fail_pipe:
623                         error("cannot create %s pipe for %s: %s",
624                                 str, cmd->argv[0], strerror(failed_errno));
625                         child_process_clear(cmd);
626                         errno = failed_errno;
627                         return -1;
628                 }
629                 cmd->err = fderr[0];
630         }
631
632         trace_argv_printf(cmd->argv, "trace: run_command:");
633         fflush(NULL);
634
635 #ifndef GIT_WINDOWS_NATIVE
636 {
637         int notify_pipe[2];
638         int null_fd = -1;
639         char **childenv;
640         struct argv_array argv = ARGV_ARRAY_INIT;
641         struct child_err cerr;
642         struct atfork_state as;
643
644         if (prepare_cmd(&argv, cmd) < 0) {
645                 failed_errno = errno;
646                 cmd->pid = -1;
647                 goto end_of_spawn;
648         }
649
650         if (pipe(notify_pipe))
651                 notify_pipe[0] = notify_pipe[1] = -1;
652
653         if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
654                 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
655                 if (null_fd < 0)
656                         die_errno(_("open /dev/null failed"));
657                 set_cloexec(null_fd);
658         }
659
660         childenv = prep_childenv(cmd->env);
661         atfork_prepare(&as);
662
663         /*
664          * NOTE: In order to prevent deadlocking when using threads special
665          * care should be taken with the function calls made in between the
666          * fork() and exec() calls.  No calls should be made to functions which
667          * require acquiring a lock (e.g. malloc) as the lock could have been
668          * held by another thread at the time of forking, causing the lock to
669          * never be released in the child process.  This means only
670          * Async-Signal-Safe functions are permitted in the child.
671          */
672         cmd->pid = fork();
673         failed_errno = errno;
674         if (!cmd->pid) {
675                 int sig;
676                 /*
677                  * Ensure the default die/error/warn routines do not get
678                  * called, they can take stdio locks and malloc.
679                  */
680                 set_die_routine(child_die_fn);
681                 set_error_routine(child_error_fn);
682                 set_warn_routine(child_warn_fn);
683
684                 close(notify_pipe[0]);
685                 set_cloexec(notify_pipe[1]);
686                 child_notifier = notify_pipe[1];
687
688                 if (cmd->no_stdin)
689                         child_dup2(null_fd, 0);
690                 else if (need_in) {
691                         child_dup2(fdin[0], 0);
692                         child_close_pair(fdin);
693                 } else if (cmd->in) {
694                         child_dup2(cmd->in, 0);
695                         child_close(cmd->in);
696                 }
697
698                 if (cmd->no_stderr)
699                         child_dup2(null_fd, 2);
700                 else if (need_err) {
701                         child_dup2(fderr[1], 2);
702                         child_close_pair(fderr);
703                 } else if (cmd->err > 1) {
704                         child_dup2(cmd->err, 2);
705                         child_close(cmd->err);
706                 }
707
708                 if (cmd->no_stdout)
709                         child_dup2(null_fd, 1);
710                 else if (cmd->stdout_to_stderr)
711                         child_dup2(2, 1);
712                 else if (need_out) {
713                         child_dup2(fdout[1], 1);
714                         child_close_pair(fdout);
715                 } else if (cmd->out > 1) {
716                         child_dup2(cmd->out, 1);
717                         child_close(cmd->out);
718                 }
719
720                 if (cmd->dir && chdir(cmd->dir))
721                         child_die(CHILD_ERR_CHDIR);
722
723                 /*
724                  * restore default signal handlers here, in case
725                  * we catch a signal right before execve below
726                  */
727                 for (sig = 1; sig < NSIG; sig++) {
728                         /* ignored signals get reset to SIG_DFL on execve */
729                         if (signal(sig, SIG_DFL) == SIG_IGN)
730                                 signal(sig, SIG_IGN);
731                 }
732
733                 if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
734                         child_die(CHILD_ERR_SIGPROCMASK);
735
736                 /*
737                  * Attempt to exec using the command and arguments starting at
738                  * argv.argv[1].  argv.argv[0] contains SHELL_PATH which will
739                  * be used in the event exec failed with ENOEXEC at which point
740                  * we will try to interpret the command using 'sh'.
741                  */
742                 execve(argv.argv[1], (char *const *) argv.argv + 1,
743                        (char *const *) childenv);
744                 if (errno == ENOEXEC)
745                         execve(argv.argv[0], (char *const *) argv.argv,
746                                (char *const *) childenv);
747
748                 if (errno == ENOENT) {
749                         if (cmd->silent_exec_failure)
750                                 child_die(CHILD_ERR_SILENT);
751                         child_die(CHILD_ERR_ENOENT);
752                 } else {
753                         child_die(CHILD_ERR_ERRNO);
754                 }
755         }
756         atfork_parent(&as);
757         if (cmd->pid < 0)
758                 error_errno("cannot fork() for %s", cmd->argv[0]);
759         else if (cmd->clean_on_exit)
760                 mark_child_for_cleanup(cmd->pid, cmd);
761
762         /*
763          * Wait for child's exec. If the exec succeeds (or if fork()
764          * failed), EOF is seen immediately by the parent. Otherwise, the
765          * child process sends a child_err struct.
766          * Note that use of this infrastructure is completely advisory,
767          * therefore, we keep error checks minimal.
768          */
769         close(notify_pipe[1]);
770         if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
771                 /*
772                  * At this point we know that fork() succeeded, but exec()
773                  * failed. Errors have been reported to our stderr.
774                  */
775                 wait_or_whine(cmd->pid, cmd->argv[0], 0);
776                 child_err_spew(cmd, &cerr);
777                 failed_errno = errno;
778                 cmd->pid = -1;
779         }
780         close(notify_pipe[0]);
781
782         if (null_fd >= 0)
783                 close(null_fd);
784         argv_array_clear(&argv);
785         free(childenv);
786 }
787 end_of_spawn:
788
789 #else
790 {
791         int fhin = 0, fhout = 1, fherr = 2;
792         const char **sargv = cmd->argv;
793         struct argv_array nargv = ARGV_ARRAY_INIT;
794
795         if (cmd->no_stdin)
796                 fhin = open("/dev/null", O_RDWR);
797         else if (need_in)
798                 fhin = dup(fdin[0]);
799         else if (cmd->in)
800                 fhin = dup(cmd->in);
801
802         if (cmd->no_stderr)
803                 fherr = open("/dev/null", O_RDWR);
804         else if (need_err)
805                 fherr = dup(fderr[1]);
806         else if (cmd->err > 2)
807                 fherr = dup(cmd->err);
808
809         if (cmd->no_stdout)
810                 fhout = open("/dev/null", O_RDWR);
811         else if (cmd->stdout_to_stderr)
812                 fhout = dup(fherr);
813         else if (need_out)
814                 fhout = dup(fdout[1]);
815         else if (cmd->out > 1)
816                 fhout = dup(cmd->out);
817
818         if (cmd->git_cmd)
819                 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
820         else if (cmd->use_shell)
821                 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
822
823         cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
824                         cmd->dir, fhin, fhout, fherr);
825         failed_errno = errno;
826         if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
827                 error_errno("cannot spawn %s", cmd->argv[0]);
828         if (cmd->clean_on_exit && cmd->pid >= 0)
829                 mark_child_for_cleanup(cmd->pid, cmd);
830
831         argv_array_clear(&nargv);
832         cmd->argv = sargv;
833         if (fhin != 0)
834                 close(fhin);
835         if (fhout != 1)
836                 close(fhout);
837         if (fherr != 2)
838                 close(fherr);
839 }
840 #endif
841
842         if (cmd->pid < 0) {
843                 if (need_in)
844                         close_pair(fdin);
845                 else if (cmd->in)
846                         close(cmd->in);
847                 if (need_out)
848                         close_pair(fdout);
849                 else if (cmd->out)
850                         close(cmd->out);
851                 if (need_err)
852                         close_pair(fderr);
853                 else if (cmd->err)
854                         close(cmd->err);
855                 child_process_clear(cmd);
856                 errno = failed_errno;
857                 return -1;
858         }
859
860         if (need_in)
861                 close(fdin[0]);
862         else if (cmd->in)
863                 close(cmd->in);
864
865         if (need_out)
866                 close(fdout[1]);
867         else if (cmd->out)
868                 close(cmd->out);
869
870         if (need_err)
871                 close(fderr[1]);
872         else if (cmd->err)
873                 close(cmd->err);
874
875         return 0;
876 }
877
878 int finish_command(struct child_process *cmd)
879 {
880         int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
881         child_process_clear(cmd);
882         return ret;
883 }
884
885 int finish_command_in_signal(struct child_process *cmd)
886 {
887         return wait_or_whine(cmd->pid, cmd->argv[0], 1);
888 }
889
890
891 int run_command(struct child_process *cmd)
892 {
893         int code;
894
895         if (cmd->out < 0 || cmd->err < 0)
896                 die("BUG: run_command with a pipe can cause deadlock");
897
898         code = start_command(cmd);
899         if (code)
900                 return code;
901         return finish_command(cmd);
902 }
903
904 int run_command_v_opt(const char **argv, int opt)
905 {
906         return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
907 }
908
909 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
910 {
911         struct child_process cmd = CHILD_PROCESS_INIT;
912         cmd.argv = argv;
913         cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
914         cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
915         cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
916         cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
917         cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
918         cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
919         cmd.dir = dir;
920         cmd.env = env;
921         return run_command(&cmd);
922 }
923
924 #ifndef NO_PTHREADS
925 static pthread_t main_thread;
926 static int main_thread_set;
927 static pthread_key_t async_key;
928 static pthread_key_t async_die_counter;
929
930 static void *run_thread(void *data)
931 {
932         struct async *async = data;
933         intptr_t ret;
934
935         if (async->isolate_sigpipe) {
936                 sigset_t mask;
937                 sigemptyset(&mask);
938                 sigaddset(&mask, SIGPIPE);
939                 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
940                         ret = error("unable to block SIGPIPE in async thread");
941                         return (void *)ret;
942                 }
943         }
944
945         pthread_setspecific(async_key, async);
946         ret = async->proc(async->proc_in, async->proc_out, async->data);
947         return (void *)ret;
948 }
949
950 static NORETURN void die_async(const char *err, va_list params)
951 {
952         vreportf("fatal: ", err, params);
953
954         if (in_async()) {
955                 struct async *async = pthread_getspecific(async_key);
956                 if (async->proc_in >= 0)
957                         close(async->proc_in);
958                 if (async->proc_out >= 0)
959                         close(async->proc_out);
960                 pthread_exit((void *)128);
961         }
962
963         exit(128);
964 }
965
966 static int async_die_is_recursing(void)
967 {
968         void *ret = pthread_getspecific(async_die_counter);
969         pthread_setspecific(async_die_counter, (void *)1);
970         return ret != NULL;
971 }
972
973 int in_async(void)
974 {
975         if (!main_thread_set)
976                 return 0; /* no asyncs started yet */
977         return !pthread_equal(main_thread, pthread_self());
978 }
979
980 static void NORETURN async_exit(int code)
981 {
982         pthread_exit((void *)(intptr_t)code);
983 }
984
985 #else
986
987 static struct {
988         void (**handlers)(void);
989         size_t nr;
990         size_t alloc;
991 } git_atexit_hdlrs;
992
993 static int git_atexit_installed;
994
995 static void git_atexit_dispatch(void)
996 {
997         size_t i;
998
999         for (i=git_atexit_hdlrs.nr ; i ; i--)
1000                 git_atexit_hdlrs.handlers[i-1]();
1001 }
1002
1003 static void git_atexit_clear(void)
1004 {
1005         free(git_atexit_hdlrs.handlers);
1006         memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
1007         git_atexit_installed = 0;
1008 }
1009
1010 #undef atexit
1011 int git_atexit(void (*handler)(void))
1012 {
1013         ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
1014         git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
1015         if (!git_atexit_installed) {
1016                 if (atexit(&git_atexit_dispatch))
1017                         return -1;
1018                 git_atexit_installed = 1;
1019         }
1020         return 0;
1021 }
1022 #define atexit git_atexit
1023
1024 static int process_is_async;
1025 int in_async(void)
1026 {
1027         return process_is_async;
1028 }
1029
1030 static void NORETURN async_exit(int code)
1031 {
1032         exit(code);
1033 }
1034
1035 #endif
1036
1037 void check_pipe(int err)
1038 {
1039         if (err == EPIPE) {
1040                 if (in_async())
1041                         async_exit(141);
1042
1043                 signal(SIGPIPE, SIG_DFL);
1044                 raise(SIGPIPE);
1045                 /* Should never happen, but just in case... */
1046                 exit(141);
1047         }
1048 }
1049
1050 int start_async(struct async *async)
1051 {
1052         int need_in, need_out;
1053         int fdin[2], fdout[2];
1054         int proc_in, proc_out;
1055
1056         need_in = async->in < 0;
1057         if (need_in) {
1058                 if (pipe(fdin) < 0) {
1059                         if (async->out > 0)
1060                                 close(async->out);
1061                         return error_errno("cannot create pipe");
1062                 }
1063                 async->in = fdin[1];
1064         }
1065
1066         need_out = async->out < 0;
1067         if (need_out) {
1068                 if (pipe(fdout) < 0) {
1069                         if (need_in)
1070                                 close_pair(fdin);
1071                         else if (async->in)
1072                                 close(async->in);
1073                         return error_errno("cannot create pipe");
1074                 }
1075                 async->out = fdout[0];
1076         }
1077
1078         if (need_in)
1079                 proc_in = fdin[0];
1080         else if (async->in)
1081                 proc_in = async->in;
1082         else
1083                 proc_in = -1;
1084
1085         if (need_out)
1086                 proc_out = fdout[1];
1087         else if (async->out)
1088                 proc_out = async->out;
1089         else
1090                 proc_out = -1;
1091
1092 #ifdef NO_PTHREADS
1093         /* Flush stdio before fork() to avoid cloning buffers */
1094         fflush(NULL);
1095
1096         async->pid = fork();
1097         if (async->pid < 0) {
1098                 error_errno("fork (async) failed");
1099                 goto error;
1100         }
1101         if (!async->pid) {
1102                 if (need_in)
1103                         close(fdin[1]);
1104                 if (need_out)
1105                         close(fdout[0]);
1106                 git_atexit_clear();
1107                 process_is_async = 1;
1108                 exit(!!async->proc(proc_in, proc_out, async->data));
1109         }
1110
1111         mark_child_for_cleanup(async->pid, NULL);
1112
1113         if (need_in)
1114                 close(fdin[0]);
1115         else if (async->in)
1116                 close(async->in);
1117
1118         if (need_out)
1119                 close(fdout[1]);
1120         else if (async->out)
1121                 close(async->out);
1122 #else
1123         if (!main_thread_set) {
1124                 /*
1125                  * We assume that the first time that start_async is called
1126                  * it is from the main thread.
1127                  */
1128                 main_thread_set = 1;
1129                 main_thread = pthread_self();
1130                 pthread_key_create(&async_key, NULL);
1131                 pthread_key_create(&async_die_counter, NULL);
1132                 set_die_routine(die_async);
1133                 set_die_is_recursing_routine(async_die_is_recursing);
1134         }
1135
1136         if (proc_in >= 0)
1137                 set_cloexec(proc_in);
1138         if (proc_out >= 0)
1139                 set_cloexec(proc_out);
1140         async->proc_in = proc_in;
1141         async->proc_out = proc_out;
1142         {
1143                 int err = pthread_create(&async->tid, NULL, run_thread, async);
1144                 if (err) {
1145                         error_errno("cannot create thread");
1146                         goto error;
1147                 }
1148         }
1149 #endif
1150         return 0;
1151
1152 error:
1153         if (need_in)
1154                 close_pair(fdin);
1155         else if (async->in)
1156                 close(async->in);
1157
1158         if (need_out)
1159                 close_pair(fdout);
1160         else if (async->out)
1161                 close(async->out);
1162         return -1;
1163 }
1164
1165 int finish_async(struct async *async)
1166 {
1167 #ifdef NO_PTHREADS
1168         return wait_or_whine(async->pid, "child process", 0);
1169 #else
1170         void *ret = (void *)(intptr_t)(-1);
1171
1172         if (pthread_join(async->tid, &ret))
1173                 error("pthread_join failed");
1174         return (int)(intptr_t)ret;
1175 #endif
1176 }
1177
1178 const char *find_hook(const char *name)
1179 {
1180         static struct strbuf path = STRBUF_INIT;
1181
1182         strbuf_reset(&path);
1183         strbuf_git_path(&path, "hooks/%s", name);
1184         if (access(path.buf, X_OK) < 0) {
1185 #ifdef STRIP_EXTENSION
1186                 strbuf_addstr(&path, STRIP_EXTENSION);
1187                 if (access(path.buf, X_OK) >= 0)
1188                         return path.buf;
1189 #endif
1190                 return NULL;
1191         }
1192         return path.buf;
1193 }
1194
1195 int run_hook_ve(const char *const *env, const char *name, va_list args)
1196 {
1197         struct child_process hook = CHILD_PROCESS_INIT;
1198         const char *p;
1199
1200         p = find_hook(name);
1201         if (!p)
1202                 return 0;
1203
1204         argv_array_push(&hook.args, p);
1205         while ((p = va_arg(args, const char *)))
1206                 argv_array_push(&hook.args, p);
1207         hook.env = env;
1208         hook.no_stdin = 1;
1209         hook.stdout_to_stderr = 1;
1210
1211         return run_command(&hook);
1212 }
1213
1214 int run_hook_le(const char *const *env, const char *name, ...)
1215 {
1216         va_list args;
1217         int ret;
1218
1219         va_start(args, name);
1220         ret = run_hook_ve(env, name, args);
1221         va_end(args);
1222
1223         return ret;
1224 }
1225
1226 struct io_pump {
1227         /* initialized by caller */
1228         int fd;
1229         int type; /* POLLOUT or POLLIN */
1230         union {
1231                 struct {
1232                         const char *buf;
1233                         size_t len;
1234                 } out;
1235                 struct {
1236                         struct strbuf *buf;
1237                         size_t hint;
1238                 } in;
1239         } u;
1240
1241         /* returned by pump_io */
1242         int error; /* 0 for success, otherwise errno */
1243
1244         /* internal use */
1245         struct pollfd *pfd;
1246 };
1247
1248 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1249 {
1250         int pollsize = 0;
1251         int i;
1252
1253         for (i = 0; i < nr; i++) {
1254                 struct io_pump *io = &slots[i];
1255                 if (io->fd < 0)
1256                         continue;
1257                 pfd[pollsize].fd = io->fd;
1258                 pfd[pollsize].events = io->type;
1259                 io->pfd = &pfd[pollsize++];
1260         }
1261
1262         if (!pollsize)
1263                 return 0;
1264
1265         if (poll(pfd, pollsize, -1) < 0) {
1266                 if (errno == EINTR)
1267                         return 1;
1268                 die_errno("poll failed");
1269         }
1270
1271         for (i = 0; i < nr; i++) {
1272                 struct io_pump *io = &slots[i];
1273
1274                 if (io->fd < 0)
1275                         continue;
1276
1277                 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1278                         continue;
1279
1280                 if (io->type == POLLOUT) {
1281                         ssize_t len = xwrite(io->fd,
1282                                              io->u.out.buf, io->u.out.len);
1283                         if (len < 0) {
1284                                 io->error = errno;
1285                                 close(io->fd);
1286                                 io->fd = -1;
1287                         } else {
1288                                 io->u.out.buf += len;
1289                                 io->u.out.len -= len;
1290                                 if (!io->u.out.len) {
1291                                         close(io->fd);
1292                                         io->fd = -1;
1293                                 }
1294                         }
1295                 }
1296
1297                 if (io->type == POLLIN) {
1298                         ssize_t len = strbuf_read_once(io->u.in.buf,
1299                                                        io->fd, io->u.in.hint);
1300                         if (len < 0)
1301                                 io->error = errno;
1302                         if (len <= 0) {
1303                                 close(io->fd);
1304                                 io->fd = -1;
1305                         }
1306                 }
1307         }
1308
1309         return 1;
1310 }
1311
1312 static int pump_io(struct io_pump *slots, int nr)
1313 {
1314         struct pollfd *pfd;
1315         int i;
1316
1317         for (i = 0; i < nr; i++)
1318                 slots[i].error = 0;
1319
1320         ALLOC_ARRAY(pfd, nr);
1321         while (pump_io_round(slots, nr, pfd))
1322                 ; /* nothing */
1323         free(pfd);
1324
1325         /* There may be multiple errno values, so just pick the first. */
1326         for (i = 0; i < nr; i++) {
1327                 if (slots[i].error) {
1328                         errno = slots[i].error;
1329                         return -1;
1330                 }
1331         }
1332         return 0;
1333 }
1334
1335
1336 int pipe_command(struct child_process *cmd,
1337                  const char *in, size_t in_len,
1338                  struct strbuf *out, size_t out_hint,
1339                  struct strbuf *err, size_t err_hint)
1340 {
1341         struct io_pump io[3];
1342         int nr = 0;
1343
1344         if (in)
1345                 cmd->in = -1;
1346         if (out)
1347                 cmd->out = -1;
1348         if (err)
1349                 cmd->err = -1;
1350
1351         if (start_command(cmd) < 0)
1352                 return -1;
1353
1354         if (in) {
1355                 io[nr].fd = cmd->in;
1356                 io[nr].type = POLLOUT;
1357                 io[nr].u.out.buf = in;
1358                 io[nr].u.out.len = in_len;
1359                 nr++;
1360         }
1361         if (out) {
1362                 io[nr].fd = cmd->out;
1363                 io[nr].type = POLLIN;
1364                 io[nr].u.in.buf = out;
1365                 io[nr].u.in.hint = out_hint;
1366                 nr++;
1367         }
1368         if (err) {
1369                 io[nr].fd = cmd->err;
1370                 io[nr].type = POLLIN;
1371                 io[nr].u.in.buf = err;
1372                 io[nr].u.in.hint = err_hint;
1373                 nr++;
1374         }
1375
1376         if (pump_io(io, nr) < 0) {
1377                 finish_command(cmd); /* throw away exit code */
1378                 return -1;
1379         }
1380
1381         return finish_command(cmd);
1382 }
1383
1384 enum child_state {
1385         GIT_CP_FREE,
1386         GIT_CP_WORKING,
1387         GIT_CP_WAIT_CLEANUP,
1388 };
1389
1390 struct parallel_processes {
1391         void *data;
1392
1393         int max_processes;
1394         int nr_processes;
1395
1396         get_next_task_fn get_next_task;
1397         start_failure_fn start_failure;
1398         task_finished_fn task_finished;
1399
1400         struct {
1401                 enum child_state state;
1402                 struct child_process process;
1403                 struct strbuf err;
1404                 void *data;
1405         } *children;
1406         /*
1407          * The struct pollfd is logically part of *children,
1408          * but the system call expects it as its own array.
1409          */
1410         struct pollfd *pfd;
1411
1412         unsigned shutdown : 1;
1413
1414         int output_owner;
1415         struct strbuf buffered_output; /* of finished children */
1416 };
1417
1418 static int default_start_failure(struct strbuf *out,
1419                                  void *pp_cb,
1420                                  void *pp_task_cb)
1421 {
1422         return 0;
1423 }
1424
1425 static int default_task_finished(int result,
1426                                  struct strbuf *out,
1427                                  void *pp_cb,
1428                                  void *pp_task_cb)
1429 {
1430         return 0;
1431 }
1432
1433 static void kill_children(struct parallel_processes *pp, int signo)
1434 {
1435         int i, n = pp->max_processes;
1436
1437         for (i = 0; i < n; i++)
1438                 if (pp->children[i].state == GIT_CP_WORKING)
1439                         kill(pp->children[i].process.pid, signo);
1440 }
1441
1442 static struct parallel_processes *pp_for_signal;
1443
1444 static void handle_children_on_signal(int signo)
1445 {
1446         kill_children(pp_for_signal, signo);
1447         sigchain_pop(signo);
1448         raise(signo);
1449 }
1450
1451 static void pp_init(struct parallel_processes *pp,
1452                     int n,
1453                     get_next_task_fn get_next_task,
1454                     start_failure_fn start_failure,
1455                     task_finished_fn task_finished,
1456                     void *data)
1457 {
1458         int i;
1459
1460         if (n < 1)
1461                 n = online_cpus();
1462
1463         pp->max_processes = n;
1464
1465         trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1466
1467         pp->data = data;
1468         if (!get_next_task)
1469                 die("BUG: you need to specify a get_next_task function");
1470         pp->get_next_task = get_next_task;
1471
1472         pp->start_failure = start_failure ? start_failure : default_start_failure;
1473         pp->task_finished = task_finished ? task_finished : default_task_finished;
1474
1475         pp->nr_processes = 0;
1476         pp->output_owner = 0;
1477         pp->shutdown = 0;
1478         pp->children = xcalloc(n, sizeof(*pp->children));
1479         pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1480         strbuf_init(&pp->buffered_output, 0);
1481
1482         for (i = 0; i < n; i++) {
1483                 strbuf_init(&pp->children[i].err, 0);
1484                 child_process_init(&pp->children[i].process);
1485                 pp->pfd[i].events = POLLIN | POLLHUP;
1486                 pp->pfd[i].fd = -1;
1487         }
1488
1489         pp_for_signal = pp;
1490         sigchain_push_common(handle_children_on_signal);
1491 }
1492
1493 static void pp_cleanup(struct parallel_processes *pp)
1494 {
1495         int i;
1496
1497         trace_printf("run_processes_parallel: done");
1498         for (i = 0; i < pp->max_processes; i++) {
1499                 strbuf_release(&pp->children[i].err);
1500                 child_process_clear(&pp->children[i].process);
1501         }
1502
1503         free(pp->children);
1504         free(pp->pfd);
1505
1506         /*
1507          * When get_next_task added messages to the buffer in its last
1508          * iteration, the buffered output is non empty.
1509          */
1510         strbuf_write(&pp->buffered_output, stderr);
1511         strbuf_release(&pp->buffered_output);
1512
1513         sigchain_pop_common();
1514 }
1515
1516 /* returns
1517  *  0 if a new task was started.
1518  *  1 if no new jobs was started (get_next_task ran out of work, non critical
1519  *    problem with starting a new command)
1520  * <0 no new job was started, user wishes to shutdown early. Use negative code
1521  *    to signal the children.
1522  */
1523 static int pp_start_one(struct parallel_processes *pp)
1524 {
1525         int i, code;
1526
1527         for (i = 0; i < pp->max_processes; i++)
1528                 if (pp->children[i].state == GIT_CP_FREE)
1529                         break;
1530         if (i == pp->max_processes)
1531                 die("BUG: bookkeeping is hard");
1532
1533         code = pp->get_next_task(&pp->children[i].process,
1534                                  &pp->children[i].err,
1535                                  pp->data,
1536                                  &pp->children[i].data);
1537         if (!code) {
1538                 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1539                 strbuf_reset(&pp->children[i].err);
1540                 return 1;
1541         }
1542         pp->children[i].process.err = -1;
1543         pp->children[i].process.stdout_to_stderr = 1;
1544         pp->children[i].process.no_stdin = 1;
1545
1546         if (start_command(&pp->children[i].process)) {
1547                 code = pp->start_failure(&pp->children[i].err,
1548                                          pp->data,
1549                                          pp->children[i].data);
1550                 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1551                 strbuf_reset(&pp->children[i].err);
1552                 if (code)
1553                         pp->shutdown = 1;
1554                 return code;
1555         }
1556
1557         pp->nr_processes++;
1558         pp->children[i].state = GIT_CP_WORKING;
1559         pp->pfd[i].fd = pp->children[i].process.err;
1560         return 0;
1561 }
1562
1563 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1564 {
1565         int i;
1566
1567         while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1568                 if (errno == EINTR)
1569                         continue;
1570                 pp_cleanup(pp);
1571                 die_errno("poll");
1572         }
1573
1574         /* Buffer output from all pipes. */
1575         for (i = 0; i < pp->max_processes; i++) {
1576                 if (pp->children[i].state == GIT_CP_WORKING &&
1577                     pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1578                         int n = strbuf_read_once(&pp->children[i].err,
1579                                                  pp->children[i].process.err, 0);
1580                         if (n == 0) {
1581                                 close(pp->children[i].process.err);
1582                                 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1583                         } else if (n < 0)
1584                                 if (errno != EAGAIN)
1585                                         die_errno("read");
1586                 }
1587         }
1588 }
1589
1590 static void pp_output(struct parallel_processes *pp)
1591 {
1592         int i = pp->output_owner;
1593         if (pp->children[i].state == GIT_CP_WORKING &&
1594             pp->children[i].err.len) {
1595                 strbuf_write(&pp->children[i].err, stderr);
1596                 strbuf_reset(&pp->children[i].err);
1597         }
1598 }
1599
1600 static int pp_collect_finished(struct parallel_processes *pp)
1601 {
1602         int i, code;
1603         int n = pp->max_processes;
1604         int result = 0;
1605
1606         while (pp->nr_processes > 0) {
1607                 for (i = 0; i < pp->max_processes; i++)
1608                         if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1609                                 break;
1610                 if (i == pp->max_processes)
1611                         break;
1612
1613                 code = finish_command(&pp->children[i].process);
1614
1615                 code = pp->task_finished(code,
1616                                          &pp->children[i].err, pp->data,
1617                                          pp->children[i].data);
1618
1619                 if (code)
1620                         result = code;
1621                 if (code < 0)
1622                         break;
1623
1624                 pp->nr_processes--;
1625                 pp->children[i].state = GIT_CP_FREE;
1626                 pp->pfd[i].fd = -1;
1627                 child_process_init(&pp->children[i].process);
1628
1629                 if (i != pp->output_owner) {
1630                         strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1631                         strbuf_reset(&pp->children[i].err);
1632                 } else {
1633                         strbuf_write(&pp->children[i].err, stderr);
1634                         strbuf_reset(&pp->children[i].err);
1635
1636                         /* Output all other finished child processes */
1637                         strbuf_write(&pp->buffered_output, stderr);
1638                         strbuf_reset(&pp->buffered_output);
1639
1640                         /*
1641                          * Pick next process to output live.
1642                          * NEEDSWORK:
1643                          * For now we pick it randomly by doing a round
1644                          * robin. Later we may want to pick the one with
1645                          * the most output or the longest or shortest
1646                          * running process time.
1647                          */
1648                         for (i = 0; i < n; i++)
1649                                 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1650                                         break;
1651                         pp->output_owner = (pp->output_owner + i) % n;
1652                 }
1653         }
1654         return result;
1655 }
1656
1657 int run_processes_parallel(int n,
1658                            get_next_task_fn get_next_task,
1659                            start_failure_fn start_failure,
1660                            task_finished_fn task_finished,
1661                            void *pp_cb)
1662 {
1663         int i, code;
1664         int output_timeout = 100;
1665         int spawn_cap = 4;
1666         struct parallel_processes pp;
1667
1668         pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1669         while (1) {
1670                 for (i = 0;
1671                     i < spawn_cap && !pp.shutdown &&
1672                     pp.nr_processes < pp.max_processes;
1673                     i++) {
1674                         code = pp_start_one(&pp);
1675                         if (!code)
1676                                 continue;
1677                         if (code < 0) {
1678                                 pp.shutdown = 1;
1679                                 kill_children(&pp, -code);
1680                         }
1681                         break;
1682                 }
1683                 if (!pp.nr_processes)
1684                         break;
1685                 pp_buffer_stderr(&pp, output_timeout);
1686                 pp_output(&pp);
1687                 code = pp_collect_finished(&pp);
1688                 if (code) {
1689                         pp.shutdown = 1;
1690                         if (code < 0)
1691                                 kill_children(&pp, -code);
1692                 }
1693         }
1694
1695         pp_cleanup(&pp);
1696         return 0;
1697 }