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