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