2af3e0fa520bcd87d241ed7a3601b14232ad94d5
   1#include "cache.h"
   2#include "run-command.h"
   3#include "exec_cmd.h"
   4#include "sigchain.h"
   5#include "argv-array.h"
   6
   7#ifndef SHELL_PATH
   8# define SHELL_PATH "/bin/sh"
   9#endif
  10
  11struct child_to_clean {
  12        pid_t pid;
  13        struct child_to_clean *next;
  14};
  15static struct child_to_clean *children_to_clean;
  16static int installed_child_cleanup_handler;
  17
  18static void cleanup_children(int sig)
  19{
  20        while (children_to_clean) {
  21                struct child_to_clean *p = children_to_clean;
  22                children_to_clean = p->next;
  23                kill(p->pid, sig);
  24                free(p);
  25        }
  26}
  27
  28static void cleanup_children_on_signal(int sig)
  29{
  30        cleanup_children(sig);
  31        sigchain_pop(sig);
  32        raise(sig);
  33}
  34
  35static void cleanup_children_on_exit(void)
  36{
  37        cleanup_children(SIGTERM);
  38}
  39
  40static void mark_child_for_cleanup(pid_t pid)
  41{
  42        struct child_to_clean *p = xmalloc(sizeof(*p));
  43        p->pid = pid;
  44        p->next = children_to_clean;
  45        children_to_clean = p;
  46
  47        if (!installed_child_cleanup_handler) {
  48                atexit(cleanup_children_on_exit);
  49                sigchain_push_common(cleanup_children_on_signal);
  50                installed_child_cleanup_handler = 1;
  51        }
  52}
  53
  54static void clear_child_for_cleanup(pid_t pid)
  55{
  56        struct child_to_clean **last, *p;
  57
  58        last = &children_to_clean;
  59        for (p = children_to_clean; p; p = p->next) {
  60                if (p->pid == pid) {
  61                        *last = p->next;
  62                        free(p);
  63                        return;
  64                }
  65        }
  66}
  67
  68static inline void close_pair(int fd[2])
  69{
  70        close(fd[0]);
  71        close(fd[1]);
  72}
  73
  74#ifndef WIN32
  75static inline void dup_devnull(int to)
  76{
  77        int fd = open("/dev/null", O_RDWR);
  78        dup2(fd, to);
  79        close(fd);
  80}
  81#endif
  82
  83static const char **prepare_shell_cmd(const char **argv)
  84{
  85        int argc, nargc = 0;
  86        const char **nargv;
  87
  88        for (argc = 0; argv[argc]; argc++)
  89                ; /* just counting */
  90        /* +1 for NULL, +3 for "sh -c" plus extra $0 */
  91        nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
  92
  93        if (argc < 1)
  94                die("BUG: shell command is empty");
  95
  96        if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
  97                nargv[nargc++] = SHELL_PATH;
  98                nargv[nargc++] = "-c";
  99
 100                if (argc < 2)
 101                        nargv[nargc++] = argv[0];
 102                else {
 103                        struct strbuf arg0 = STRBUF_INIT;
 104                        strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
 105                        nargv[nargc++] = strbuf_detach(&arg0, NULL);
 106                }
 107        }
 108
 109        for (argc = 0; argv[argc]; argc++)
 110                nargv[nargc++] = argv[argc];
 111        nargv[nargc] = NULL;
 112
 113        return nargv;
 114}
 115
 116#ifndef WIN32
 117static int execv_shell_cmd(const char **argv)
 118{
 119        const char **nargv = prepare_shell_cmd(argv);
 120        trace_argv_printf(nargv, "trace: exec:");
 121        execvp(nargv[0], (char **)nargv);
 122        free(nargv);
 123        return -1;
 124}
 125#endif
 126
 127#ifndef WIN32
 128static int child_err = 2;
 129static int child_notifier = -1;
 130
 131static void notify_parent(void)
 132{
 133        /*
 134         * execvp failed.  If possible, we'd like to let start_command
 135         * know, so failures like ENOENT can be handled right away; but
 136         * otherwise, finish_command will still report the error.
 137         */
 138        xwrite(child_notifier, "", 1);
 139}
 140
 141static NORETURN void die_child(const char *err, va_list params)
 142{
 143        vwritef(child_err, "fatal: ", err, params);
 144        exit(128);
 145}
 146
 147static void error_child(const char *err, va_list params)
 148{
 149        vwritef(child_err, "error: ", err, params);
 150}
 151#endif
 152
 153static inline void set_cloexec(int fd)
 154{
 155        int flags = fcntl(fd, F_GETFD);
 156        if (flags >= 0)
 157                fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
 158}
 159
 160static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
 161{
 162        int status, code = -1;
 163        pid_t waiting;
 164        int failed_errno = 0;
 165
 166        while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
 167                ;       /* nothing */
 168
 169        if (waiting < 0) {
 170                failed_errno = errno;
 171                error("waitpid for %s failed: %s", argv0, strerror(errno));
 172        } else if (waiting != pid) {
 173                error("waitpid is confused (%s)", argv0);
 174        } else if (WIFSIGNALED(status)) {
 175                code = WTERMSIG(status);
 176                error("%s died of signal %d", argv0, code);
 177                /*
 178                 * This return value is chosen so that code & 0xff
 179                 * mimics the exit code that a POSIX shell would report for
 180                 * a program that died from this signal.
 181                 */
 182                code -= 128;
 183        } else if (WIFEXITED(status)) {
 184                code = WEXITSTATUS(status);
 185                /*
 186                 * Convert special exit code when execvp failed.
 187                 */
 188                if (code == 127) {
 189                        code = -1;
 190                        failed_errno = ENOENT;
 191                }
 192        } else {
 193                error("waitpid is confused (%s)", argv0);
 194        }
 195
 196        clear_child_for_cleanup(pid);
 197
 198        errno = failed_errno;
 199        return code;
 200}
 201
 202int start_command(struct child_process *cmd)
 203{
 204        int need_in, need_out, need_err;
 205        int fdin[2], fdout[2], fderr[2];
 206        int failed_errno = failed_errno;
 207
 208        /*
 209         * In case of errors we must keep the promise to close FDs
 210         * that have been passed in via ->in and ->out.
 211         */
 212
 213        need_in = !cmd->no_stdin && cmd->in < 0;
 214        if (need_in) {
 215                if (pipe(fdin) < 0) {
 216                        failed_errno = errno;
 217                        if (cmd->out > 0)
 218                                close(cmd->out);
 219                        goto fail_pipe;
 220                }
 221                cmd->in = fdin[1];
 222        }
 223
 224        need_out = !cmd->no_stdout
 225                && !cmd->stdout_to_stderr
 226                && cmd->out < 0;
 227        if (need_out) {
 228                if (pipe(fdout) < 0) {
 229                        failed_errno = errno;
 230                        if (need_in)
 231                                close_pair(fdin);
 232                        else if (cmd->in)
 233                                close(cmd->in);
 234                        goto fail_pipe;
 235                }
 236                cmd->out = fdout[0];
 237        }
 238
 239        need_err = !cmd->no_stderr && cmd->err < 0;
 240        if (need_err) {
 241                if (pipe(fderr) < 0) {
 242                        failed_errno = errno;
 243                        if (need_in)
 244                                close_pair(fdin);
 245                        else if (cmd->in)
 246                                close(cmd->in);
 247                        if (need_out)
 248                                close_pair(fdout);
 249                        else if (cmd->out)
 250                                close(cmd->out);
 251fail_pipe:
 252                        error("cannot create pipe for %s: %s",
 253                                cmd->argv[0], strerror(failed_errno));
 254                        errno = failed_errno;
 255                        return -1;
 256                }
 257                cmd->err = fderr[0];
 258        }
 259
 260        trace_argv_printf(cmd->argv, "trace: run_command:");
 261        fflush(NULL);
 262
 263#ifndef WIN32
 264{
 265        int notify_pipe[2];
 266        if (pipe(notify_pipe))
 267                notify_pipe[0] = notify_pipe[1] = -1;
 268
 269        cmd->pid = fork();
 270        if (!cmd->pid) {
 271                /*
 272                 * Redirect the channel to write syscall error messages to
 273                 * before redirecting the process's stderr so that all die()
 274                 * in subsequent call paths use the parent's stderr.
 275                 */
 276                if (cmd->no_stderr || need_err) {
 277                        child_err = dup(2);
 278                        set_cloexec(child_err);
 279                }
 280                set_die_routine(die_child);
 281                set_error_routine(error_child);
 282
 283                close(notify_pipe[0]);
 284                set_cloexec(notify_pipe[1]);
 285                child_notifier = notify_pipe[1];
 286                atexit(notify_parent);
 287
 288                if (cmd->no_stdin)
 289                        dup_devnull(0);
 290                else if (need_in) {
 291                        dup2(fdin[0], 0);
 292                        close_pair(fdin);
 293                } else if (cmd->in) {
 294                        dup2(cmd->in, 0);
 295                        close(cmd->in);
 296                }
 297
 298                if (cmd->no_stderr)
 299                        dup_devnull(2);
 300                else if (need_err) {
 301                        dup2(fderr[1], 2);
 302                        close_pair(fderr);
 303                } else if (cmd->err > 1) {
 304                        dup2(cmd->err, 2);
 305                        close(cmd->err);
 306                }
 307
 308                if (cmd->no_stdout)
 309                        dup_devnull(1);
 310                else if (cmd->stdout_to_stderr)
 311                        dup2(2, 1);
 312                else if (need_out) {
 313                        dup2(fdout[1], 1);
 314                        close_pair(fdout);
 315                } else if (cmd->out > 1) {
 316                        dup2(cmd->out, 1);
 317                        close(cmd->out);
 318                }
 319
 320                if (cmd->dir && chdir(cmd->dir))
 321                        die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
 322                            cmd->dir);
 323                if (cmd->env) {
 324                        for (; *cmd->env; cmd->env++) {
 325                                if (strchr(*cmd->env, '='))
 326                                        putenv((char *)*cmd->env);
 327                                else
 328                                        unsetenv(*cmd->env);
 329                        }
 330                }
 331                if (cmd->preexec_cb) {
 332                        /*
 333                         * We cannot predict what the pre-exec callback does.
 334                         * Forgo parent notification.
 335                         */
 336                        close(child_notifier);
 337                        child_notifier = -1;
 338
 339                        cmd->preexec_cb();
 340                }
 341                if (cmd->git_cmd) {
 342                        execv_git_cmd(cmd->argv);
 343                } else if (cmd->use_shell) {
 344                        execv_shell_cmd(cmd->argv);
 345                } else {
 346                        execvp(cmd->argv[0], (char *const*) cmd->argv);
 347                }
 348                if (errno == ENOENT) {
 349                        if (!cmd->silent_exec_failure)
 350                                error("cannot run %s: %s", cmd->argv[0],
 351                                        strerror(ENOENT));
 352                        exit(127);
 353                } else {
 354                        die_errno("cannot exec '%s'", cmd->argv[0]);
 355                }
 356        }
 357        if (cmd->pid < 0)
 358                error("cannot fork() for %s: %s", cmd->argv[0],
 359                        strerror(failed_errno = errno));
 360        else if (cmd->clean_on_exit)
 361                mark_child_for_cleanup(cmd->pid);
 362
 363        /*
 364         * Wait for child's execvp. If the execvp succeeds (or if fork()
 365         * failed), EOF is seen immediately by the parent. Otherwise, the
 366         * child process sends a single byte.
 367         * Note that use of this infrastructure is completely advisory,
 368         * therefore, we keep error checks minimal.
 369         */
 370        close(notify_pipe[1]);
 371        if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
 372                /*
 373                 * At this point we know that fork() succeeded, but execvp()
 374                 * failed. Errors have been reported to our stderr.
 375                 */
 376                wait_or_whine(cmd->pid, cmd->argv[0],
 377                              cmd->silent_exec_failure);
 378                failed_errno = errno;
 379                cmd->pid = -1;
 380        }
 381        close(notify_pipe[0]);
 382
 383}
 384#else
 385{
 386        int fhin = 0, fhout = 1, fherr = 2;
 387        const char **sargv = cmd->argv;
 388        char **env = environ;
 389
 390        if (cmd->no_stdin)
 391                fhin = open("/dev/null", O_RDWR);
 392        else if (need_in)
 393                fhin = dup(fdin[0]);
 394        else if (cmd->in)
 395                fhin = dup(cmd->in);
 396
 397        if (cmd->no_stderr)
 398                fherr = open("/dev/null", O_RDWR);
 399        else if (need_err)
 400                fherr = dup(fderr[1]);
 401        else if (cmd->err > 2)
 402                fherr = dup(cmd->err);
 403
 404        if (cmd->no_stdout)
 405                fhout = open("/dev/null", O_RDWR);
 406        else if (cmd->stdout_to_stderr)
 407                fhout = dup(fherr);
 408        else if (need_out)
 409                fhout = dup(fdout[1]);
 410        else if (cmd->out > 1)
 411                fhout = dup(cmd->out);
 412
 413        if (cmd->env)
 414                env = make_augmented_environ(cmd->env);
 415
 416        if (cmd->git_cmd) {
 417                cmd->argv = prepare_git_cmd(cmd->argv);
 418        } else if (cmd->use_shell) {
 419                cmd->argv = prepare_shell_cmd(cmd->argv);
 420        }
 421
 422        cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
 423                                  fhin, fhout, fherr);
 424        failed_errno = errno;
 425        if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
 426                error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
 427        if (cmd->clean_on_exit && cmd->pid >= 0)
 428                mark_child_for_cleanup(cmd->pid);
 429
 430        if (cmd->env)
 431                free_environ(env);
 432        if (cmd->git_cmd)
 433                free(cmd->argv);
 434
 435        cmd->argv = sargv;
 436        if (fhin != 0)
 437                close(fhin);
 438        if (fhout != 1)
 439                close(fhout);
 440        if (fherr != 2)
 441                close(fherr);
 442}
 443#endif
 444
 445        if (cmd->pid < 0) {
 446                if (need_in)
 447                        close_pair(fdin);
 448                else if (cmd->in)
 449                        close(cmd->in);
 450                if (need_out)
 451                        close_pair(fdout);
 452                else if (cmd->out)
 453                        close(cmd->out);
 454                if (need_err)
 455                        close_pair(fderr);
 456                else if (cmd->err)
 457                        close(cmd->err);
 458                errno = failed_errno;
 459                return -1;
 460        }
 461
 462        if (need_in)
 463                close(fdin[0]);
 464        else if (cmd->in)
 465                close(cmd->in);
 466
 467        if (need_out)
 468                close(fdout[1]);
 469        else if (cmd->out)
 470                close(cmd->out);
 471
 472        if (need_err)
 473                close(fderr[1]);
 474        else if (cmd->err)
 475                close(cmd->err);
 476
 477        return 0;
 478}
 479
 480int finish_command(struct child_process *cmd)
 481{
 482        return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
 483}
 484
 485int run_command(struct child_process *cmd)
 486{
 487        int code = start_command(cmd);
 488        if (code)
 489                return code;
 490        return finish_command(cmd);
 491}
 492
 493static void prepare_run_command_v_opt(struct child_process *cmd,
 494                                      const char **argv,
 495                                      int opt)
 496{
 497        memset(cmd, 0, sizeof(*cmd));
 498        cmd->argv = argv;
 499        cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
 500        cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
 501        cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
 502        cmd->silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
 503        cmd->use_shell = opt & RUN_USING_SHELL ? 1 : 0;
 504        cmd->clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
 505}
 506
 507int run_command_v_opt(const char **argv, int opt)
 508{
 509        struct child_process cmd;
 510        prepare_run_command_v_opt(&cmd, argv, opt);
 511        return run_command(&cmd);
 512}
 513
 514int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
 515{
 516        struct child_process cmd;
 517        prepare_run_command_v_opt(&cmd, argv, opt);
 518        cmd.dir = dir;
 519        cmd.env = env;
 520        return run_command(&cmd);
 521}
 522
 523#ifndef NO_PTHREADS
 524static pthread_t main_thread;
 525static int main_thread_set;
 526static pthread_key_t async_key;
 527
 528static void *run_thread(void *data)
 529{
 530        struct async *async = data;
 531        intptr_t ret;
 532
 533        pthread_setspecific(async_key, async);
 534        ret = async->proc(async->proc_in, async->proc_out, async->data);
 535        return (void *)ret;
 536}
 537
 538static NORETURN void die_async(const char *err, va_list params)
 539{
 540        vreportf("fatal: ", err, params);
 541
 542        if (!pthread_equal(main_thread, pthread_self())) {
 543                struct async *async = pthread_getspecific(async_key);
 544                if (async->proc_in >= 0)
 545                        close(async->proc_in);
 546                if (async->proc_out >= 0)
 547                        close(async->proc_out);
 548                pthread_exit((void *)128);
 549        }
 550
 551        exit(128);
 552}
 553#endif
 554
 555int start_async(struct async *async)
 556{
 557        int need_in, need_out;
 558        int fdin[2], fdout[2];
 559        int proc_in, proc_out;
 560
 561        need_in = async->in < 0;
 562        if (need_in) {
 563                if (pipe(fdin) < 0) {
 564                        if (async->out > 0)
 565                                close(async->out);
 566                        return error("cannot create pipe: %s", strerror(errno));
 567                }
 568                async->in = fdin[1];
 569        }
 570
 571        need_out = async->out < 0;
 572        if (need_out) {
 573                if (pipe(fdout) < 0) {
 574                        if (need_in)
 575                                close_pair(fdin);
 576                        else if (async->in)
 577                                close(async->in);
 578                        return error("cannot create pipe: %s", strerror(errno));
 579                }
 580                async->out = fdout[0];
 581        }
 582
 583        if (need_in)
 584                proc_in = fdin[0];
 585        else if (async->in)
 586                proc_in = async->in;
 587        else
 588                proc_in = -1;
 589
 590        if (need_out)
 591                proc_out = fdout[1];
 592        else if (async->out)
 593                proc_out = async->out;
 594        else
 595                proc_out = -1;
 596
 597#ifdef NO_PTHREADS
 598        /* Flush stdio before fork() to avoid cloning buffers */
 599        fflush(NULL);
 600
 601        async->pid = fork();
 602        if (async->pid < 0) {
 603                error("fork (async) failed: %s", strerror(errno));
 604                goto error;
 605        }
 606        if (!async->pid) {
 607                if (need_in)
 608                        close(fdin[1]);
 609                if (need_out)
 610                        close(fdout[0]);
 611                exit(!!async->proc(proc_in, proc_out, async->data));
 612        }
 613
 614        mark_child_for_cleanup(async->pid);
 615
 616        if (need_in)
 617                close(fdin[0]);
 618        else if (async->in)
 619                close(async->in);
 620
 621        if (need_out)
 622                close(fdout[1]);
 623        else if (async->out)
 624                close(async->out);
 625#else
 626        if (!main_thread_set) {
 627                /*
 628                 * We assume that the first time that start_async is called
 629                 * it is from the main thread.
 630                 */
 631                main_thread_set = 1;
 632                main_thread = pthread_self();
 633                pthread_key_create(&async_key, NULL);
 634                set_die_routine(die_async);
 635        }
 636
 637        if (proc_in >= 0)
 638                set_cloexec(proc_in);
 639        if (proc_out >= 0)
 640                set_cloexec(proc_out);
 641        async->proc_in = proc_in;
 642        async->proc_out = proc_out;
 643        {
 644                int err = pthread_create(&async->tid, NULL, run_thread, async);
 645                if (err) {
 646                        error("cannot create thread: %s", strerror(err));
 647                        goto error;
 648                }
 649        }
 650#endif
 651        return 0;
 652
 653error:
 654        if (need_in)
 655                close_pair(fdin);
 656        else if (async->in)
 657                close(async->in);
 658
 659        if (need_out)
 660                close_pair(fdout);
 661        else if (async->out)
 662                close(async->out);
 663        return -1;
 664}
 665
 666int finish_async(struct async *async)
 667{
 668#ifdef NO_PTHREADS
 669        return wait_or_whine(async->pid, "child process", 0);
 670#else
 671        void *ret = (void *)(intptr_t)(-1);
 672
 673        if (pthread_join(async->tid, &ret))
 674                error("pthread_join failed");
 675        return (int)(intptr_t)ret;
 676#endif
 677}
 678
 679int run_hook(const char *index_file, const char *name, ...)
 680{
 681        struct child_process hook;
 682        struct argv_array argv = ARGV_ARRAY_INIT;
 683        const char *p, *env[2];
 684        char index[PATH_MAX];
 685        va_list args;
 686        int ret;
 687
 688        if (access(git_path("hooks/%s", name), X_OK) < 0)
 689                return 0;
 690
 691        va_start(args, name);
 692        argv_array_push(&argv, git_path("hooks/%s", name));
 693        while ((p = va_arg(args, const char *)))
 694                argv_array_push(&argv, p);
 695        va_end(args);
 696
 697        memset(&hook, 0, sizeof(hook));
 698        hook.argv = argv.argv;
 699        hook.no_stdin = 1;
 700        hook.stdout_to_stderr = 1;
 701        if (index_file) {
 702                snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 703                env[0] = index;
 704                env[1] = NULL;
 705                hook.env = env;
 706        }
 707
 708        ret = run_command(&hook);
 709        argv_array_clear(&argv);
 710        return ret;
 711}