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