]> git.ipfire.org Git - thirdparty/git.git/blame - run-command.c
run-command: block signals between fork and execve
[thirdparty/git.git] / run-command.c
CommitLineData
b1bf95bb
JW
1#include "cache.h"
2#include "run-command.h"
77cb17e9 3#include "exec_cmd.h"
afe19ff7 4#include "sigchain.h"
5d40a179 5#include "argv-array.h"
c553c72e
SB
6#include "thread-utils.h"
7#include "strbuf.h"
b1bf95bb 8
483bbd4e
RS
9void child_process_init(struct child_process *child)
10{
11 memset(child, 0, sizeof(*child));
12 argv_array_init(&child->args);
19a583dc 13 argv_array_init(&child->env_array);
483bbd4e
RS
14}
15
2d71608e
RS
16void child_process_clear(struct child_process *child)
17{
18 argv_array_clear(&child->args);
19 argv_array_clear(&child->env_array);
20}
21
afe19ff7
JK
22struct child_to_clean {
23 pid_t pid;
ac2fbaa6 24 struct child_process *process;
afe19ff7
JK
25 struct child_to_clean *next;
26};
27static struct child_to_clean *children_to_clean;
28static int installed_child_cleanup_handler;
29
507d7804 30static void cleanup_children(int sig, int in_signal)
afe19ff7 31{
46df6906
JK
32 struct child_to_clean *children_to_wait_for = NULL;
33
afe19ff7
JK
34 while (children_to_clean) {
35 struct child_to_clean *p = children_to_clean;
36 children_to_clean = p->next;
ac2fbaa6
LS
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
afe19ff7 49 kill(p->pid, sig);
46df6906 50
7b91929b 51 if (p->process && p->process->wait_after_clean) {
46df6906
JK
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
507d7804
TI
67 if (!in_signal)
68 free(p);
afe19ff7
JK
69 }
70}
71
72static void cleanup_children_on_signal(int sig)
73{
507d7804 74 cleanup_children(sig, 1);
afe19ff7
JK
75 sigchain_pop(sig);
76 raise(sig);
77}
78
79static void cleanup_children_on_exit(void)
80{
507d7804 81 cleanup_children(SIGTERM, 0);
afe19ff7
JK
82}
83
ac2fbaa6 84static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
afe19ff7
JK
85{
86 struct child_to_clean *p = xmalloc(sizeof(*p));
87 p->pid = pid;
ac2fbaa6 88 p->process = process;
afe19ff7
JK
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{
bdee397d 101 struct child_to_clean **pp;
afe19ff7 102
bdee397d
DG
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);
afe19ff7
JK
109 return;
110 }
111 }
112}
113
9dc09c76
SP
114static inline void close_pair(int fd[2])
115{
116 close(fd[0]);
117 close(fd[1]);
118}
119
38f865c2
JK
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;
a7855083
JH
179 else if (errno == ENOTDIR && !strchr(file, '/'))
180 errno = ENOENT;
38f865c2
JK
181 return -1;
182}
183
20574f55 184static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
8dba1e63 185{
20574f55 186 if (!argv[0])
8dba1e63
JK
187 die("BUG: shell command is empty");
188
f445644f 189 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
380395d0 190#ifndef GIT_WINDOWS_NATIVE
20574f55 191 argv_array_push(out, SHELL_PATH);
77629754 192#else
20574f55 193 argv_array_push(out, "sh");
77629754 194#endif
20574f55 195 argv_array_push(out, "-c");
8dba1e63 196
20574f55
JK
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 }
8dba1e63 206
20574f55
JK
207 argv_array_pushv(out, argv);
208 return out->argv;
8dba1e63
JK
209}
210
380395d0 211#ifndef GIT_WINDOWS_NATIVE
2b541bf8
JS
212static int child_notifier = -1;
213
79319b19
BW
214enum child_errcode {
215 CHILD_ERR_CHDIR,
53fa6753
BW
216 CHILD_ERR_DUP2,
217 CHILD_ERR_CLOSE,
45afb1ca 218 CHILD_ERR_SIGPROCMASK,
79319b19
BW
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)
2b541bf8 230{
79319b19
BW
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
53fa6753
BW
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
79319b19
BW
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;
53fa6753
BW
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;
45afb1ca
EW
307 case CHILD_ERR_SIGPROCMASK:
308 error_errno("sigprocmask failed restoring signals");
309 break;
79319b19
BW
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);
2b541bf8 320}
3967e25b
BW
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
e3a43446
BW
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
3967e25b
BW
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 }
e3a43446
BW
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 }
3967e25b 355}
ae25394b
BW
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}
45afb1ca
EW
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");
200a76b7 450#endif
45afb1ca
EW
451}
452#endif /* GIT_WINDOWS_NATIVE */
a5487ddf
JS
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}
a5487ddf 460
507d7804 461static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
ab0b41da
JS
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 */
507d7804
TI
469 if (in_signal)
470 return 0;
ab0b41da
JS
471
472 if (waiting < 0) {
473 failed_errno = errno;
fbcb0e06 474 error_errno("waitpid for %s failed", argv0);
ab0b41da
JS
475 } else if (waiting != pid) {
476 error("waitpid is confused (%s)", argv0);
477 } else if (WIFSIGNALED(status)) {
478 code = WTERMSIG(status);
ac78663b 479 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
a2767c5c 480 error("%s died of signal %d", argv0, code);
ab0b41da
JS
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 */
709ca730 486 code += 128;
ab0b41da
JS
487 } else if (WIFEXITED(status)) {
488 code = WEXITSTATUS(status);
ab0b41da
JS
489 } else {
490 error("waitpid is confused (%s)", argv0);
491 }
afe19ff7
JK
492
493 clear_child_for_cleanup(pid);
494
ab0b41da
JS
495 errno = failed_errno;
496 return code;
497}
498
ebcb5d16 499int start_command(struct child_process *cmd)
b1bf95bb 500{
f3b33f1d
JS
501 int need_in, need_out, need_err;
502 int fdin[2], fdout[2], fderr[2];
25043d8a 503 int failed_errno;
939296c4 504 char *str;
4919bf03 505
c460c0ec
JK
506 if (!cmd->argv)
507 cmd->argv = cmd->args.argv;
19a583dc
RS
508 if (!cmd->env)
509 cmd->env = cmd->env_array.argv;
c460c0ec 510
c20181e3
JS
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
e4507ae8 516 need_in = !cmd->no_stdin && cmd->in < 0;
4919bf03 517 if (need_in) {
c20181e3 518 if (pipe(fdin) < 0) {
0ac77ec3 519 failed_errno = errno;
c20181e3
JS
520 if (cmd->out > 0)
521 close(cmd->out);
939296c4 522 str = "standard input";
0ac77ec3 523 goto fail_pipe;
c20181e3 524 }
4919bf03 525 cmd->in = fdin[1];
4919bf03
SP
526 }
527
e4507ae8
SP
528 need_out = !cmd->no_stdout
529 && !cmd->stdout_to_stderr
530 && cmd->out < 0;
f4bba25b
SP
531 if (need_out) {
532 if (pipe(fdout) < 0) {
0ac77ec3 533 failed_errno = errno;
f4bba25b
SP
534 if (need_in)
535 close_pair(fdin);
c20181e3
JS
536 else if (cmd->in)
537 close(cmd->in);
939296c4 538 str = "standard output";
0ac77ec3 539 goto fail_pipe;
f4bba25b
SP
540 }
541 cmd->out = fdout[0];
f4bba25b
SP
542 }
543
b73a4397 544 need_err = !cmd->no_stderr && cmd->err < 0;
f3b33f1d
JS
545 if (need_err) {
546 if (pipe(fderr) < 0) {
0ac77ec3 547 failed_errno = errno;
f3b33f1d
JS
548 if (need_in)
549 close_pair(fdin);
c20181e3
JS
550 else if (cmd->in)
551 close(cmd->in);
f3b33f1d
JS
552 if (need_out)
553 close_pair(fdout);
c20181e3
JS
554 else if (cmd->out)
555 close(cmd->out);
939296c4 556 str = "standard error";
0ac77ec3 557fail_pipe:
939296c4
SB
558 error("cannot create %s pipe for %s: %s",
559 str, cmd->argv[0], strerror(failed_errno));
2d71608e 560 child_process_clear(cmd);
0ac77ec3
JS
561 errno = failed_errno;
562 return -1;
f3b33f1d
JS
563 }
564 cmd->err = fderr[0];
565 }
566
8852f5d7 567 trace_argv_printf(cmd->argv, "trace: run_command:");
13af8cbd 568 fflush(NULL);
8852f5d7 569
380395d0 570#ifndef GIT_WINDOWS_NATIVE
2b541bf8
JS
571{
572 int notify_pipe[2];
db015a28 573 int null_fd = -1;
ae25394b 574 char **childenv;
3967e25b 575 struct argv_array argv = ARGV_ARRAY_INIT;
79319b19 576 struct child_err cerr;
45afb1ca 577 struct atfork_state as;
3967e25b 578
2b541bf8
JS
579 if (pipe(notify_pipe))
580 notify_pipe[0] = notify_pipe[1] = -1;
581
db015a28
BW
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
3967e25b 589 prepare_cmd(&argv, cmd);
ae25394b 590 childenv = prep_childenv(cmd->env);
45afb1ca 591 atfork_prepare(&as);
3967e25b 592
e503cd6e
BW
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 */
ebcb5d16 602 cmd->pid = fork();
25043d8a 603 failed_errno = errno;
ebcb5d16 604 if (!cmd->pid) {
45afb1ca 605 int sig;
a5487ddf 606 /*
79319b19
BW
607 * Ensure the default die/error/warn routines do not get
608 * called, they can take stdio locks and malloc.
a5487ddf 609 */
79319b19
BW
610 set_die_routine(child_die_fn);
611 set_error_routine(child_error_fn);
612 set_warn_routine(child_warn_fn);
a5487ddf 613
2b541bf8
JS
614 close(notify_pipe[0]);
615 set_cloexec(notify_pipe[1]);
616 child_notifier = notify_pipe[1];
2b541bf8 617
e4507ae8 618 if (cmd->no_stdin)
53fa6753 619 child_dup2(null_fd, 0);
e4507ae8 620 else if (need_in) {
53fa6753
BW
621 child_dup2(fdin[0], 0);
622 child_close_pair(fdin);
4919bf03 623 } else if (cmd->in) {
53fa6753
BW
624 child_dup2(cmd->in, 0);
625 child_close(cmd->in);
95d3c4f5 626 }
4919bf03 627
ce2cf27a 628 if (cmd->no_stderr)
53fa6753 629 child_dup2(null_fd, 2);
ce2cf27a 630 else if (need_err) {
53fa6753
BW
631 child_dup2(fderr[1], 2);
632 child_close_pair(fderr);
4f41b611 633 } else if (cmd->err > 1) {
53fa6753
BW
634 child_dup2(cmd->err, 2);
635 child_close(cmd->err);
ce2cf27a
CC
636 }
637
e4507ae8 638 if (cmd->no_stdout)
53fa6753 639 child_dup2(null_fd, 1);
e4507ae8 640 else if (cmd->stdout_to_stderr)
53fa6753 641 child_dup2(2, 1);
f4bba25b 642 else if (need_out) {
53fa6753
BW
643 child_dup2(fdout[1], 1);
644 child_close_pair(fdout);
f4bba25b 645 } else if (cmd->out > 1) {
53fa6753
BW
646 child_dup2(cmd->out, 1);
647 child_close(cmd->out);
f4bba25b
SP
648 }
649
1568fea0 650 if (cmd->dir && chdir(cmd->dir))
79319b19 651 child_die(CHILD_ERR_CHDIR);
3967e25b 652
45afb1ca
EW
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
e3a43446
BW
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 */
ae25394b
BW
672 execve(argv.argv[1], (char *const *) argv.argv + 1,
673 (char *const *) childenv);
e3a43446 674 if (errno == ENOEXEC)
ae25394b
BW
675 execve(argv.argv[0], (char *const *) argv.argv,
676 (char *const *) childenv);
3967e25b 677
fc1b56f0 678 if (errno == ENOENT) {
79319b19
BW
679 if (cmd->silent_exec_failure)
680 child_die(CHILD_ERR_SILENT);
681 child_die(CHILD_ERR_ENOENT);
fc1b56f0 682 } else {
79319b19 683 child_die(CHILD_ERR_ERRNO);
fc1b56f0 684 }
b1bf95bb 685 }
45afb1ca 686 atfork_parent(&as);
0ac77ec3 687 if (cmd->pid < 0)
fbcb0e06 688 error_errno("cannot fork() for %s", cmd->argv[0]);
afe19ff7 689 else if (cmd->clean_on_exit)
ac2fbaa6 690 mark_child_for_cleanup(cmd->pid, cmd);
2b541bf8
JS
691
692 /*
3967e25b 693 * Wait for child's exec. If the exec succeeds (or if fork()
2b541bf8 694 * failed), EOF is seen immediately by the parent. Otherwise, the
79319b19 695 * child process sends a child_err struct.
2b541bf8
JS
696 * Note that use of this infrastructure is completely advisory,
697 * therefore, we keep error checks minimal.
698 */
699 close(notify_pipe[1]);
79319b19 700 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
2b541bf8 701 /*
3967e25b 702 * At this point we know that fork() succeeded, but exec()
2b541bf8
JS
703 * failed. Errors have been reported to our stderr.
704 */
507d7804 705 wait_or_whine(cmd->pid, cmd->argv[0], 0);
79319b19 706 child_err_spew(cmd, &cerr);
2b541bf8
JS
707 failed_errno = errno;
708 cmd->pid = -1;
709 }
710 close(notify_pipe[0]);
3967e25b 711
db015a28
BW
712 if (null_fd >= 0)
713 close(null_fd);
3967e25b 714 argv_array_clear(&argv);
ae25394b 715 free(childenv);
2b541bf8 716}
ba26f296 717#else
0d30ad71 718{
75301f90 719 int fhin = 0, fhout = 1, fherr = 2;
108ac313 720 const char **sargv = cmd->argv;
20574f55 721 struct argv_array nargv = ARGV_ARRAY_INIT;
ba26f296 722
75301f90
JS
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]);
76d44c8c
JH
734 else if (cmd->err > 2)
735 fherr = dup(cmd->err);
75301f90
JS
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);
ba26f296 745
5a50085c 746 if (cmd->git_cmd)
20574f55 747 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
5a50085c 748 else if (cmd->use_shell)
20574f55 749 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
ba26f296 750
77734da2
KB
751 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
752 cmd->dir, fhin, fhout, fherr);
0ac77ec3 753 failed_errno = errno;
c024beb5 754 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
fbcb0e06 755 error_errno("cannot spawn %s", cmd->argv[0]);
afe19ff7 756 if (cmd->clean_on_exit && cmd->pid >= 0)
ac2fbaa6 757 mark_child_for_cleanup(cmd->pid, cmd);
ba26f296 758
20574f55 759 argv_array_clear(&nargv);
108ac313 760 cmd->argv = sargv;
75301f90
JS
761 if (fhin != 0)
762 close(fhin);
763 if (fhout != 1)
764 close(fhout);
765 if (fherr != 2)
766 close(fherr);
0d30ad71 767}
ba26f296
JS
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);
fc012c28
D
781 else if (cmd->err)
782 close(cmd->err);
2d71608e 783 child_process_clear(cmd);
0ac77ec3
JS
784 errno = failed_errno;
785 return -1;
ba26f296 786 }
4919bf03
SP
787
788 if (need_in)
789 close(fdin[0]);
790 else if (cmd->in)
791 close(cmd->in);
792
f4bba25b
SP
793 if (need_out)
794 close(fdout[1]);
c20181e3 795 else if (cmd->out)
f4bba25b
SP
796 close(cmd->out);
797
f3b33f1d
JS
798 if (need_err)
799 close(fderr[1]);
4f41b611
SP
800 else if (cmd->err)
801 close(cmd->err);
f3b33f1d 802
ebcb5d16
SP
803 return 0;
804}
805
2d22c208
JS
806int finish_command(struct child_process *cmd)
807{
507d7804 808 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
2d71608e 809 child_process_clear(cmd);
c460c0ec 810 return ret;
2d22c208
JS
811}
812
507d7804
TI
813int finish_command_in_signal(struct child_process *cmd)
814{
815 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
816}
817
818
ebcb5d16
SP
819int run_command(struct child_process *cmd)
820{
c29b3962
JK
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);
ebcb5d16
SP
827 if (code)
828 return code;
829 return finish_command(cmd);
830}
831
f1000898
SP
832int run_command_v_opt(const char **argv, int opt)
833{
41e9bad7 834 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
1568fea0
AR
835}
836
ee493148
AR
837int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
838{
1f87293d
RS
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;
ee493148
AR
847 cmd.dir = dir;
848 cmd.env = env;
849 return run_command(&cmd);
850}
2d22c208 851
f6b60983 852#ifndef NO_PTHREADS
0ea1c89b
JS
853static pthread_t main_thread;
854static int main_thread_set;
855static pthread_key_t async_key;
1ece66bc 856static pthread_key_t async_die_counter;
0ea1c89b 857
200a76b7 858static void *run_thread(void *data)
618ebe9f
JS
859{
860 struct async *async = data;
f6b60983 861 intptr_t ret;
0ea1c89b 862
c792d7b6
JK
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
0ea1c89b 873 pthread_setspecific(async_key, async);
f6b60983 874 ret = async->proc(async->proc_in, async->proc_out, async->data);
200a76b7 875 return (void *)ret;
618ebe9f 876}
0ea1c89b
JS
877
878static NORETURN void die_async(const char *err, va_list params)
879{
880 vreportf("fatal: ", err, params);
881
661a8cf4 882 if (in_async()) {
0ea1c89b
JS
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);
618ebe9f 892}
1ece66bc
JK
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
661a8cf4
JK
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
b992fe10 908static void NORETURN async_exit(int code)
9658846c
JK
909{
910 pthread_exit((void *)(intptr_t)code);
911}
912
0f4b6db3
EB
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
6066a7ea 923static void git_atexit_dispatch(void)
0f4b6db3
EB
924{
925 size_t i;
926
927 for (i=git_atexit_hdlrs.nr ; i ; i--)
928 git_atexit_hdlrs.handlers[i-1]();
929}
930
6066a7ea 931static void git_atexit_clear(void)
0f4b6db3
EB
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
661a8cf4
JK
952static int process_is_async;
953int in_async(void)
954{
955 return process_is_async;
956}
957
b992fe10 958static void NORETURN async_exit(int code)
9658846c
JK
959{
960 exit(code);
961}
962
618ebe9f
JS
963#endif
964
b992fe10
LS
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
2d22c208
JS
978int start_async(struct async *async)
979{
ae6a5609
EFL
980 int need_in, need_out;
981 int fdin[2], fdout[2];
982 int proc_in, proc_out;
2d22c208 983
ae6a5609
EFL
984 need_in = async->in < 0;
985 if (need_in) {
986 if (pipe(fdin) < 0) {
987 if (async->out > 0)
988 close(async->out);
fbcb0e06 989 return error_errno("cannot create pipe");
ae6a5609
EFL
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);
fbcb0e06 1001 return error_errno("cannot create pipe");
ae6a5609
EFL
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;
2d22c208 1019
f6b60983 1020#ifdef NO_PTHREADS
2c3766f0
AM
1021 /* Flush stdio before fork() to avoid cloning buffers */
1022 fflush(NULL);
1023
2d22c208
JS
1024 async->pid = fork();
1025 if (async->pid < 0) {
fbcb0e06 1026 error_errno("fork (async) failed");
ae6a5609 1027 goto error;
2d22c208
JS
1028 }
1029 if (!async->pid) {
ae6a5609
EFL
1030 if (need_in)
1031 close(fdin[1]);
1032 if (need_out)
1033 close(fdout[0]);
0f4b6db3 1034 git_atexit_clear();
661a8cf4 1035 process_is_async = 1;
ae6a5609 1036 exit(!!async->proc(proc_in, proc_out, async->data));
2d22c208 1037 }
ae6a5609 1038
ac2fbaa6 1039 mark_child_for_cleanup(async->pid, NULL);
afe19ff7 1040
ae6a5609
EFL
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);
618ebe9f 1050#else
0ea1c89b
JS
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);
1ece66bc 1059 pthread_key_create(&async_die_counter, NULL);
0ea1c89b 1060 set_die_routine(die_async);
1ece66bc 1061 set_die_is_recursing_routine(async_die_is_recursing);
0ea1c89b
JS
1062 }
1063
200a76b7
JS
1064 if (proc_in >= 0)
1065 set_cloexec(proc_in);
1066 if (proc_out >= 0)
1067 set_cloexec(proc_out);
ae6a5609
EFL
1068 async->proc_in = proc_in;
1069 async->proc_out = proc_out;
200a76b7
JS
1070 {
1071 int err = pthread_create(&async->tid, NULL, run_thread, async);
1072 if (err) {
fbcb0e06 1073 error_errno("cannot create thread");
200a76b7
JS
1074 goto error;
1075 }
618ebe9f
JS
1076 }
1077#endif
2d22c208 1078 return 0;
ae6a5609
EFL
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;
2d22c208
JS
1091}
1092
1093int finish_async(struct async *async)
1094{
f6b60983 1095#ifdef NO_PTHREADS
507d7804 1096 return wait_or_whine(async->pid, "child process", 0);
618ebe9f 1097#else
200a76b7
JS
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;
618ebe9f 1103#endif
2d22c208 1104}
ae98a008 1105
dcf69262 1106const char *find_hook(const char *name)
5a7da2dc 1107{
03f2c773 1108 static struct strbuf path = STRBUF_INIT;
5a7da2dc 1109
03f2c773 1110 strbuf_reset(&path);
9445b492 1111 strbuf_git_path(&path, "hooks/%s", name);
235be51f
JS
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
03f2c773 1118 return NULL;
235be51f 1119 }
03f2c773 1120 return path.buf;
5a7da2dc
AS
1121}
1122
15048f8a 1123int run_hook_ve(const char *const *env, const char *name, va_list args)
ae98a008 1124{
d3180279 1125 struct child_process hook = CHILD_PROCESS_INIT;
15048f8a 1126 const char *p;
ae98a008 1127
5a7da2dc
AS
1128 p = find_hook(name);
1129 if (!p)
cf94ca8e
SB
1130 return 0;
1131
d1d09456
RS
1132 argv_array_push(&hook.args, p);
1133 while ((p = va_arg(args, const char *)))
1134 argv_array_push(&hook.args, p);
15048f8a 1135 hook.env = env;
ae98a008
SB
1136 hook.no_stdin = 1;
1137 hook.stdout_to_stderr = 1;
ae98a008 1138
d1d09456 1139 return run_command(&hook);
ae98a008 1140}
15048f8a
BP
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}
911ec99b 1153
96335bcf
JK
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)
911ec99b 1241{
96335bcf
JK
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
911ec99b
JK
1279 if (start_command(cmd) < 0)
1280 return -1;
1281
96335bcf
JK
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) {
911ec99b
JK
1305 finish_command(cmd); /* throw away exit code */
1306 return -1;
1307 }
1308
911ec99b
JK
1309 return finish_command(cmd);
1310}
c553c72e
SB
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
aa710494 1346static int default_start_failure(struct strbuf *out,
c553c72e
SB
1347 void *pp_cb,
1348 void *pp_task_cb)
1349{
c553c72e
SB
1350 return 0;
1351}
1352
1353static int default_task_finished(int result,
aa710494 1354 struct strbuf *out,
c553c72e
SB
1355 void *pp_cb,
1356 void *pp_task_cb)
1357{
c553c72e
SB
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 */
2dac9b56 1438 strbuf_write(&pp->buffered_output, stderr);
c553c72e
SB
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)) {
2a73b3da 1475 code = pp->start_failure(&pp->children[i].err,
c553c72e
SB
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) {
2dac9b56 1523 strbuf_write(&pp->children[i].err, stderr);
c553c72e
SB
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
2a73b3da 1543 code = pp->task_finished(code,
c553c72e
SB
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 {
2dac9b56 1561 strbuf_write(&pp->children[i].err, stderr);
c553c72e
SB
1562 strbuf_reset(&pp->children[i].err);
1563
1564 /* Output all other finished child processes */
2dac9b56 1565 strbuf_write(&pp->buffered_output, stderr);
c553c72e
SB
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}