run-command: handle dup2 and close errors in child
[git/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,
79319b19
BW
218 CHILD_ERR_ENOENT,
219 CHILD_ERR_SILENT,
220 CHILD_ERR_ERRNO
221};
222
223struct child_err {
224 enum child_errcode err;
225 int syserr; /* errno */
226};
227
228static void child_die(enum child_errcode err)
2b541bf8 229{
79319b19
BW
230 struct child_err buf;
231
232 buf.err = err;
233 buf.syserr = errno;
234
235 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
236 xwrite(child_notifier, &buf, sizeof(buf));
237 _exit(1);
238}
239
53fa6753
BW
240static void child_dup2(int fd, int to)
241{
242 if (dup2(fd, to) < 0)
243 child_die(CHILD_ERR_DUP2);
244}
245
246static void child_close(int fd)
247{
248 if (close(fd))
249 child_die(CHILD_ERR_CLOSE);
250}
251
252static void child_close_pair(int fd[2])
253{
254 child_close(fd[0]);
255 child_close(fd[1]);
256}
257
79319b19
BW
258/*
259 * parent will make it look like the child spewed a fatal error and died
260 * this is needed to prevent changes to t0061.
261 */
262static void fake_fatal(const char *err, va_list params)
263{
264 vreportf("fatal: ", err, params);
265}
266
267static void child_error_fn(const char *err, va_list params)
268{
269 const char msg[] = "error() should not be called in child\n";
270 xwrite(2, msg, sizeof(msg) - 1);
271}
272
273static void child_warn_fn(const char *err, va_list params)
274{
275 const char msg[] = "warn() should not be called in child\n";
276 xwrite(2, msg, sizeof(msg) - 1);
277}
278
279static void NORETURN child_die_fn(const char *err, va_list params)
280{
281 const char msg[] = "die() should not be called in child\n";
282 xwrite(2, msg, sizeof(msg) - 1);
283 _exit(2);
284}
285
286/* this runs in the parent process */
287static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
288{
289 static void (*old_errfn)(const char *err, va_list params);
290
291 old_errfn = get_error_routine();
292 set_error_routine(fake_fatal);
293 errno = cerr->syserr;
294
295 switch (cerr->err) {
296 case CHILD_ERR_CHDIR:
297 error_errno("exec '%s': cd to '%s' failed",
298 cmd->argv[0], cmd->dir);
299 break;
53fa6753
BW
300 case CHILD_ERR_DUP2:
301 error_errno("dup2() in child failed");
302 break;
303 case CHILD_ERR_CLOSE:
304 error_errno("close() in child failed");
305 break;
79319b19
BW
306 case CHILD_ERR_ENOENT:
307 error_errno("cannot run %s", cmd->argv[0]);
308 break;
309 case CHILD_ERR_SILENT:
310 break;
311 case CHILD_ERR_ERRNO:
312 error_errno("cannot exec '%s'", cmd->argv[0]);
313 break;
314 }
315 set_error_routine(old_errfn);
2b541bf8 316}
3967e25b
BW
317
318static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
319{
320 if (!cmd->argv[0])
321 die("BUG: command is empty");
322
e3a43446
BW
323 /*
324 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
325 * attempt to interpret the command with 'sh'.
326 */
327 argv_array_push(out, SHELL_PATH);
328
3967e25b
BW
329 if (cmd->git_cmd) {
330 argv_array_push(out, "git");
331 argv_array_pushv(out, cmd->argv);
332 } else if (cmd->use_shell) {
333 prepare_shell_cmd(out, cmd->argv);
334 } else {
335 argv_array_pushv(out, cmd->argv);
336 }
e3a43446
BW
337
338 /*
339 * If there are no '/' characters in the command then perform a path
340 * lookup and use the resolved path as the command to exec. If there
341 * are no '/' characters or if the command wasn't found in the path,
342 * have exec attempt to invoke the command directly.
343 */
344 if (!strchr(out->argv[1], '/')) {
345 char *program = locate_in_PATH(out->argv[1]);
346 if (program) {
347 free((char *)out->argv[1]);
348 out->argv[1] = program;
349 }
350 }
3967e25b 351}
ae25394b
BW
352
353static char **prep_childenv(const char *const *deltaenv)
354{
355 extern char **environ;
356 char **childenv;
357 struct string_list env = STRING_LIST_INIT_DUP;
358 struct strbuf key = STRBUF_INIT;
359 const char *const *p;
360 int i;
361
362 /* Construct a sorted string list consisting of the current environ */
363 for (p = (const char *const *) environ; p && *p; p++) {
364 const char *equals = strchr(*p, '=');
365
366 if (equals) {
367 strbuf_reset(&key);
368 strbuf_add(&key, *p, equals - *p);
369 string_list_append(&env, key.buf)->util = (void *) *p;
370 } else {
371 string_list_append(&env, *p)->util = (void *) *p;
372 }
373 }
374 string_list_sort(&env);
375
376 /* Merge in 'deltaenv' with the current environ */
377 for (p = deltaenv; p && *p; p++) {
378 const char *equals = strchr(*p, '=');
379
380 if (equals) {
381 /* ('key=value'), insert or replace entry */
382 strbuf_reset(&key);
383 strbuf_add(&key, *p, equals - *p);
384 string_list_insert(&env, key.buf)->util = (void *) *p;
385 } else {
386 /* otherwise ('key') remove existing entry */
387 string_list_remove(&env, *p, 0);
388 }
389 }
390
391 /* Create an array of 'char *' to be used as the childenv */
392 childenv = xmalloc((env.nr + 1) * sizeof(char *));
393 for (i = 0; i < env.nr; i++)
394 childenv[i] = env.items[i].util;
395 childenv[env.nr] = NULL;
396
397 string_list_clear(&env, 0);
398 strbuf_release(&key);
399 return childenv;
400}
200a76b7 401#endif
a5487ddf
JS
402
403static inline void set_cloexec(int fd)
404{
405 int flags = fcntl(fd, F_GETFD);
406 if (flags >= 0)
407 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
408}
a5487ddf 409
507d7804 410static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
ab0b41da
JS
411{
412 int status, code = -1;
413 pid_t waiting;
414 int failed_errno = 0;
415
416 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
417 ; /* nothing */
507d7804
TI
418 if (in_signal)
419 return 0;
ab0b41da
JS
420
421 if (waiting < 0) {
422 failed_errno = errno;
fbcb0e06 423 error_errno("waitpid for %s failed", argv0);
ab0b41da
JS
424 } else if (waiting != pid) {
425 error("waitpid is confused (%s)", argv0);
426 } else if (WIFSIGNALED(status)) {
427 code = WTERMSIG(status);
ac78663b 428 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
a2767c5c 429 error("%s died of signal %d", argv0, code);
ab0b41da
JS
430 /*
431 * This return value is chosen so that code & 0xff
432 * mimics the exit code that a POSIX shell would report for
433 * a program that died from this signal.
434 */
709ca730 435 code += 128;
ab0b41da
JS
436 } else if (WIFEXITED(status)) {
437 code = WEXITSTATUS(status);
ab0b41da
JS
438 } else {
439 error("waitpid is confused (%s)", argv0);
440 }
afe19ff7
JK
441
442 clear_child_for_cleanup(pid);
443
ab0b41da
JS
444 errno = failed_errno;
445 return code;
446}
447
ebcb5d16 448int start_command(struct child_process *cmd)
b1bf95bb 449{
f3b33f1d
JS
450 int need_in, need_out, need_err;
451 int fdin[2], fdout[2], fderr[2];
25043d8a 452 int failed_errno;
939296c4 453 char *str;
4919bf03 454
c460c0ec
JK
455 if (!cmd->argv)
456 cmd->argv = cmd->args.argv;
19a583dc
RS
457 if (!cmd->env)
458 cmd->env = cmd->env_array.argv;
c460c0ec 459
c20181e3
JS
460 /*
461 * In case of errors we must keep the promise to close FDs
462 * that have been passed in via ->in and ->out.
463 */
464
e4507ae8 465 need_in = !cmd->no_stdin && cmd->in < 0;
4919bf03 466 if (need_in) {
c20181e3 467 if (pipe(fdin) < 0) {
0ac77ec3 468 failed_errno = errno;
c20181e3
JS
469 if (cmd->out > 0)
470 close(cmd->out);
939296c4 471 str = "standard input";
0ac77ec3 472 goto fail_pipe;
c20181e3 473 }
4919bf03 474 cmd->in = fdin[1];
4919bf03
SP
475 }
476
e4507ae8
SP
477 need_out = !cmd->no_stdout
478 && !cmd->stdout_to_stderr
479 && cmd->out < 0;
f4bba25b
SP
480 if (need_out) {
481 if (pipe(fdout) < 0) {
0ac77ec3 482 failed_errno = errno;
f4bba25b
SP
483 if (need_in)
484 close_pair(fdin);
c20181e3
JS
485 else if (cmd->in)
486 close(cmd->in);
939296c4 487 str = "standard output";
0ac77ec3 488 goto fail_pipe;
f4bba25b
SP
489 }
490 cmd->out = fdout[0];
f4bba25b
SP
491 }
492
b73a4397 493 need_err = !cmd->no_stderr && cmd->err < 0;
f3b33f1d
JS
494 if (need_err) {
495 if (pipe(fderr) < 0) {
0ac77ec3 496 failed_errno = errno;
f3b33f1d
JS
497 if (need_in)
498 close_pair(fdin);
c20181e3
JS
499 else if (cmd->in)
500 close(cmd->in);
f3b33f1d
JS
501 if (need_out)
502 close_pair(fdout);
c20181e3
JS
503 else if (cmd->out)
504 close(cmd->out);
939296c4 505 str = "standard error";
0ac77ec3 506fail_pipe:
939296c4
SB
507 error("cannot create %s pipe for %s: %s",
508 str, cmd->argv[0], strerror(failed_errno));
2d71608e 509 child_process_clear(cmd);
0ac77ec3
JS
510 errno = failed_errno;
511 return -1;
f3b33f1d
JS
512 }
513 cmd->err = fderr[0];
514 }
515
8852f5d7 516 trace_argv_printf(cmd->argv, "trace: run_command:");
13af8cbd 517 fflush(NULL);
8852f5d7 518
380395d0 519#ifndef GIT_WINDOWS_NATIVE
2b541bf8
JS
520{
521 int notify_pipe[2];
db015a28 522 int null_fd = -1;
ae25394b 523 char **childenv;
3967e25b 524 struct argv_array argv = ARGV_ARRAY_INIT;
79319b19 525 struct child_err cerr;
3967e25b 526
2b541bf8
JS
527 if (pipe(notify_pipe))
528 notify_pipe[0] = notify_pipe[1] = -1;
529
db015a28
BW
530 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
531 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
532 if (null_fd < 0)
533 die_errno(_("open /dev/null failed"));
534 set_cloexec(null_fd);
535 }
536
3967e25b 537 prepare_cmd(&argv, cmd);
ae25394b 538 childenv = prep_childenv(cmd->env);
3967e25b 539
ebcb5d16 540 cmd->pid = fork();
25043d8a 541 failed_errno = errno;
ebcb5d16 542 if (!cmd->pid) {
a5487ddf 543 /*
79319b19
BW
544 * Ensure the default die/error/warn routines do not get
545 * called, they can take stdio locks and malloc.
a5487ddf 546 */
79319b19
BW
547 set_die_routine(child_die_fn);
548 set_error_routine(child_error_fn);
549 set_warn_routine(child_warn_fn);
a5487ddf 550
2b541bf8
JS
551 close(notify_pipe[0]);
552 set_cloexec(notify_pipe[1]);
553 child_notifier = notify_pipe[1];
2b541bf8 554
e4507ae8 555 if (cmd->no_stdin)
53fa6753 556 child_dup2(null_fd, 0);
e4507ae8 557 else if (need_in) {
53fa6753
BW
558 child_dup2(fdin[0], 0);
559 child_close_pair(fdin);
4919bf03 560 } else if (cmd->in) {
53fa6753
BW
561 child_dup2(cmd->in, 0);
562 child_close(cmd->in);
95d3c4f5 563 }
4919bf03 564
ce2cf27a 565 if (cmd->no_stderr)
53fa6753 566 child_dup2(null_fd, 2);
ce2cf27a 567 else if (need_err) {
53fa6753
BW
568 child_dup2(fderr[1], 2);
569 child_close_pair(fderr);
4f41b611 570 } else if (cmd->err > 1) {
53fa6753
BW
571 child_dup2(cmd->err, 2);
572 child_close(cmd->err);
ce2cf27a
CC
573 }
574
e4507ae8 575 if (cmd->no_stdout)
53fa6753 576 child_dup2(null_fd, 1);
e4507ae8 577 else if (cmd->stdout_to_stderr)
53fa6753 578 child_dup2(2, 1);
f4bba25b 579 else if (need_out) {
53fa6753
BW
580 child_dup2(fdout[1], 1);
581 child_close_pair(fdout);
f4bba25b 582 } else if (cmd->out > 1) {
53fa6753
BW
583 child_dup2(cmd->out, 1);
584 child_close(cmd->out);
f4bba25b
SP
585 }
586
1568fea0 587 if (cmd->dir && chdir(cmd->dir))
79319b19 588 child_die(CHILD_ERR_CHDIR);
3967e25b 589
e3a43446
BW
590 /*
591 * Attempt to exec using the command and arguments starting at
592 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
593 * be used in the event exec failed with ENOEXEC at which point
594 * we will try to interpret the command using 'sh'.
595 */
ae25394b
BW
596 execve(argv.argv[1], (char *const *) argv.argv + 1,
597 (char *const *) childenv);
e3a43446 598 if (errno == ENOEXEC)
ae25394b
BW
599 execve(argv.argv[0], (char *const *) argv.argv,
600 (char *const *) childenv);
3967e25b 601
fc1b56f0 602 if (errno == ENOENT) {
79319b19
BW
603 if (cmd->silent_exec_failure)
604 child_die(CHILD_ERR_SILENT);
605 child_die(CHILD_ERR_ENOENT);
fc1b56f0 606 } else {
79319b19 607 child_die(CHILD_ERR_ERRNO);
fc1b56f0 608 }
b1bf95bb 609 }
0ac77ec3 610 if (cmd->pid < 0)
fbcb0e06 611 error_errno("cannot fork() for %s", cmd->argv[0]);
afe19ff7 612 else if (cmd->clean_on_exit)
ac2fbaa6 613 mark_child_for_cleanup(cmd->pid, cmd);
2b541bf8
JS
614
615 /*
3967e25b 616 * Wait for child's exec. If the exec succeeds (or if fork()
2b541bf8 617 * failed), EOF is seen immediately by the parent. Otherwise, the
79319b19 618 * child process sends a child_err struct.
2b541bf8
JS
619 * Note that use of this infrastructure is completely advisory,
620 * therefore, we keep error checks minimal.
621 */
622 close(notify_pipe[1]);
79319b19 623 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
2b541bf8 624 /*
3967e25b 625 * At this point we know that fork() succeeded, but exec()
2b541bf8
JS
626 * failed. Errors have been reported to our stderr.
627 */
507d7804 628 wait_or_whine(cmd->pid, cmd->argv[0], 0);
79319b19 629 child_err_spew(cmd, &cerr);
2b541bf8
JS
630 failed_errno = errno;
631 cmd->pid = -1;
632 }
633 close(notify_pipe[0]);
3967e25b 634
db015a28
BW
635 if (null_fd >= 0)
636 close(null_fd);
3967e25b 637 argv_array_clear(&argv);
ae25394b 638 free(childenv);
2b541bf8 639}
ba26f296 640#else
0d30ad71 641{
75301f90 642 int fhin = 0, fhout = 1, fherr = 2;
108ac313 643 const char **sargv = cmd->argv;
20574f55 644 struct argv_array nargv = ARGV_ARRAY_INIT;
ba26f296 645
75301f90
JS
646 if (cmd->no_stdin)
647 fhin = open("/dev/null", O_RDWR);
648 else if (need_in)
649 fhin = dup(fdin[0]);
650 else if (cmd->in)
651 fhin = dup(cmd->in);
652
653 if (cmd->no_stderr)
654 fherr = open("/dev/null", O_RDWR);
655 else if (need_err)
656 fherr = dup(fderr[1]);
76d44c8c
JH
657 else if (cmd->err > 2)
658 fherr = dup(cmd->err);
75301f90
JS
659
660 if (cmd->no_stdout)
661 fhout = open("/dev/null", O_RDWR);
662 else if (cmd->stdout_to_stderr)
663 fhout = dup(fherr);
664 else if (need_out)
665 fhout = dup(fdout[1]);
666 else if (cmd->out > 1)
667 fhout = dup(cmd->out);
ba26f296 668
5a50085c 669 if (cmd->git_cmd)
20574f55 670 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
5a50085c 671 else if (cmd->use_shell)
20574f55 672 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
ba26f296 673
77734da2
KB
674 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
675 cmd->dir, fhin, fhout, fherr);
0ac77ec3 676 failed_errno = errno;
c024beb5 677 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
fbcb0e06 678 error_errno("cannot spawn %s", cmd->argv[0]);
afe19ff7 679 if (cmd->clean_on_exit && cmd->pid >= 0)
ac2fbaa6 680 mark_child_for_cleanup(cmd->pid, cmd);
ba26f296 681
20574f55 682 argv_array_clear(&nargv);
108ac313 683 cmd->argv = sargv;
75301f90
JS
684 if (fhin != 0)
685 close(fhin);
686 if (fhout != 1)
687 close(fhout);
688 if (fherr != 2)
689 close(fherr);
0d30ad71 690}
ba26f296
JS
691#endif
692
693 if (cmd->pid < 0) {
694 if (need_in)
695 close_pair(fdin);
696 else if (cmd->in)
697 close(cmd->in);
698 if (need_out)
699 close_pair(fdout);
700 else if (cmd->out)
701 close(cmd->out);
702 if (need_err)
703 close_pair(fderr);
fc012c28
D
704 else if (cmd->err)
705 close(cmd->err);
2d71608e 706 child_process_clear(cmd);
0ac77ec3
JS
707 errno = failed_errno;
708 return -1;
ba26f296 709 }
4919bf03
SP
710
711 if (need_in)
712 close(fdin[0]);
713 else if (cmd->in)
714 close(cmd->in);
715
f4bba25b
SP
716 if (need_out)
717 close(fdout[1]);
c20181e3 718 else if (cmd->out)
f4bba25b
SP
719 close(cmd->out);
720
f3b33f1d
JS
721 if (need_err)
722 close(fderr[1]);
4f41b611
SP
723 else if (cmd->err)
724 close(cmd->err);
f3b33f1d 725
ebcb5d16
SP
726 return 0;
727}
728
2d22c208
JS
729int finish_command(struct child_process *cmd)
730{
507d7804 731 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
2d71608e 732 child_process_clear(cmd);
c460c0ec 733 return ret;
2d22c208
JS
734}
735
507d7804
TI
736int finish_command_in_signal(struct child_process *cmd)
737{
738 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
739}
740
741
ebcb5d16
SP
742int run_command(struct child_process *cmd)
743{
c29b3962
JK
744 int code;
745
746 if (cmd->out < 0 || cmd->err < 0)
747 die("BUG: run_command with a pipe can cause deadlock");
748
749 code = start_command(cmd);
ebcb5d16
SP
750 if (code)
751 return code;
752 return finish_command(cmd);
753}
754
f1000898
SP
755int run_command_v_opt(const char **argv, int opt)
756{
41e9bad7 757 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
1568fea0
AR
758}
759
ee493148
AR
760int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
761{
1f87293d
RS
762 struct child_process cmd = CHILD_PROCESS_INIT;
763 cmd.argv = argv;
764 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
765 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
766 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
767 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
768 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
769 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
ee493148
AR
770 cmd.dir = dir;
771 cmd.env = env;
772 return run_command(&cmd);
773}
2d22c208 774
f6b60983 775#ifndef NO_PTHREADS
0ea1c89b
JS
776static pthread_t main_thread;
777static int main_thread_set;
778static pthread_key_t async_key;
1ece66bc 779static pthread_key_t async_die_counter;
0ea1c89b 780
200a76b7 781static void *run_thread(void *data)
618ebe9f
JS
782{
783 struct async *async = data;
f6b60983 784 intptr_t ret;
0ea1c89b 785
c792d7b6
JK
786 if (async->isolate_sigpipe) {
787 sigset_t mask;
788 sigemptyset(&mask);
789 sigaddset(&mask, SIGPIPE);
790 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
791 ret = error("unable to block SIGPIPE in async thread");
792 return (void *)ret;
793 }
794 }
795
0ea1c89b 796 pthread_setspecific(async_key, async);
f6b60983 797 ret = async->proc(async->proc_in, async->proc_out, async->data);
200a76b7 798 return (void *)ret;
618ebe9f 799}
0ea1c89b
JS
800
801static NORETURN void die_async(const char *err, va_list params)
802{
803 vreportf("fatal: ", err, params);
804
661a8cf4 805 if (in_async()) {
0ea1c89b
JS
806 struct async *async = pthread_getspecific(async_key);
807 if (async->proc_in >= 0)
808 close(async->proc_in);
809 if (async->proc_out >= 0)
810 close(async->proc_out);
811 pthread_exit((void *)128);
812 }
813
814 exit(128);
618ebe9f 815}
1ece66bc
JK
816
817static int async_die_is_recursing(void)
818{
819 void *ret = pthread_getspecific(async_die_counter);
820 pthread_setspecific(async_die_counter, (void *)1);
821 return ret != NULL;
822}
823
661a8cf4
JK
824int in_async(void)
825{
826 if (!main_thread_set)
827 return 0; /* no asyncs started yet */
828 return !pthread_equal(main_thread, pthread_self());
829}
830
b992fe10 831static void NORETURN async_exit(int code)
9658846c
JK
832{
833 pthread_exit((void *)(intptr_t)code);
834}
835
0f4b6db3
EB
836#else
837
838static struct {
839 void (**handlers)(void);
840 size_t nr;
841 size_t alloc;
842} git_atexit_hdlrs;
843
844static int git_atexit_installed;
845
6066a7ea 846static void git_atexit_dispatch(void)
0f4b6db3
EB
847{
848 size_t i;
849
850 for (i=git_atexit_hdlrs.nr ; i ; i--)
851 git_atexit_hdlrs.handlers[i-1]();
852}
853
6066a7ea 854static void git_atexit_clear(void)
0f4b6db3
EB
855{
856 free(git_atexit_hdlrs.handlers);
857 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
858 git_atexit_installed = 0;
859}
860
861#undef atexit
862int git_atexit(void (*handler)(void))
863{
864 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
865 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
866 if (!git_atexit_installed) {
867 if (atexit(&git_atexit_dispatch))
868 return -1;
869 git_atexit_installed = 1;
870 }
871 return 0;
872}
873#define atexit git_atexit
874
661a8cf4
JK
875static int process_is_async;
876int in_async(void)
877{
878 return process_is_async;
879}
880
b992fe10 881static void NORETURN async_exit(int code)
9658846c
JK
882{
883 exit(code);
884}
885
618ebe9f
JS
886#endif
887
b992fe10
LS
888void check_pipe(int err)
889{
890 if (err == EPIPE) {
891 if (in_async())
892 async_exit(141);
893
894 signal(SIGPIPE, SIG_DFL);
895 raise(SIGPIPE);
896 /* Should never happen, but just in case... */
897 exit(141);
898 }
899}
900
2d22c208
JS
901int start_async(struct async *async)
902{
ae6a5609
EFL
903 int need_in, need_out;
904 int fdin[2], fdout[2];
905 int proc_in, proc_out;
2d22c208 906
ae6a5609
EFL
907 need_in = async->in < 0;
908 if (need_in) {
909 if (pipe(fdin) < 0) {
910 if (async->out > 0)
911 close(async->out);
fbcb0e06 912 return error_errno("cannot create pipe");
ae6a5609
EFL
913 }
914 async->in = fdin[1];
915 }
916
917 need_out = async->out < 0;
918 if (need_out) {
919 if (pipe(fdout) < 0) {
920 if (need_in)
921 close_pair(fdin);
922 else if (async->in)
923 close(async->in);
fbcb0e06 924 return error_errno("cannot create pipe");
ae6a5609
EFL
925 }
926 async->out = fdout[0];
927 }
928
929 if (need_in)
930 proc_in = fdin[0];
931 else if (async->in)
932 proc_in = async->in;
933 else
934 proc_in = -1;
935
936 if (need_out)
937 proc_out = fdout[1];
938 else if (async->out)
939 proc_out = async->out;
940 else
941 proc_out = -1;
2d22c208 942
f6b60983 943#ifdef NO_PTHREADS
2c3766f0
AM
944 /* Flush stdio before fork() to avoid cloning buffers */
945 fflush(NULL);
946
2d22c208
JS
947 async->pid = fork();
948 if (async->pid < 0) {
fbcb0e06 949 error_errno("fork (async) failed");
ae6a5609 950 goto error;
2d22c208
JS
951 }
952 if (!async->pid) {
ae6a5609
EFL
953 if (need_in)
954 close(fdin[1]);
955 if (need_out)
956 close(fdout[0]);
0f4b6db3 957 git_atexit_clear();
661a8cf4 958 process_is_async = 1;
ae6a5609 959 exit(!!async->proc(proc_in, proc_out, async->data));
2d22c208 960 }
ae6a5609 961
ac2fbaa6 962 mark_child_for_cleanup(async->pid, NULL);
afe19ff7 963
ae6a5609
EFL
964 if (need_in)
965 close(fdin[0]);
966 else if (async->in)
967 close(async->in);
968
969 if (need_out)
970 close(fdout[1]);
971 else if (async->out)
972 close(async->out);
618ebe9f 973#else
0ea1c89b
JS
974 if (!main_thread_set) {
975 /*
976 * We assume that the first time that start_async is called
977 * it is from the main thread.
978 */
979 main_thread_set = 1;
980 main_thread = pthread_self();
981 pthread_key_create(&async_key, NULL);
1ece66bc 982 pthread_key_create(&async_die_counter, NULL);
0ea1c89b 983 set_die_routine(die_async);
1ece66bc 984 set_die_is_recursing_routine(async_die_is_recursing);
0ea1c89b
JS
985 }
986
200a76b7
JS
987 if (proc_in >= 0)
988 set_cloexec(proc_in);
989 if (proc_out >= 0)
990 set_cloexec(proc_out);
ae6a5609
EFL
991 async->proc_in = proc_in;
992 async->proc_out = proc_out;
200a76b7
JS
993 {
994 int err = pthread_create(&async->tid, NULL, run_thread, async);
995 if (err) {
fbcb0e06 996 error_errno("cannot create thread");
200a76b7
JS
997 goto error;
998 }
618ebe9f
JS
999 }
1000#endif
2d22c208 1001 return 0;
ae6a5609
EFL
1002
1003error:
1004 if (need_in)
1005 close_pair(fdin);
1006 else if (async->in)
1007 close(async->in);
1008
1009 if (need_out)
1010 close_pair(fdout);
1011 else if (async->out)
1012 close(async->out);
1013 return -1;
2d22c208
JS
1014}
1015
1016int finish_async(struct async *async)
1017{
f6b60983 1018#ifdef NO_PTHREADS
507d7804 1019 return wait_or_whine(async->pid, "child process", 0);
618ebe9f 1020#else
200a76b7
JS
1021 void *ret = (void *)(intptr_t)(-1);
1022
1023 if (pthread_join(async->tid, &ret))
1024 error("pthread_join failed");
1025 return (int)(intptr_t)ret;
618ebe9f 1026#endif
2d22c208 1027}
ae98a008 1028
dcf69262 1029const char *find_hook(const char *name)
5a7da2dc 1030{
03f2c773 1031 static struct strbuf path = STRBUF_INIT;
5a7da2dc 1032
03f2c773 1033 strbuf_reset(&path);
9445b492 1034 strbuf_git_path(&path, "hooks/%s", name);
235be51f
JS
1035 if (access(path.buf, X_OK) < 0) {
1036#ifdef STRIP_EXTENSION
1037 strbuf_addstr(&path, STRIP_EXTENSION);
1038 if (access(path.buf, X_OK) >= 0)
1039 return path.buf;
1040#endif
03f2c773 1041 return NULL;
235be51f 1042 }
03f2c773 1043 return path.buf;
5a7da2dc
AS
1044}
1045
15048f8a 1046int run_hook_ve(const char *const *env, const char *name, va_list args)
ae98a008 1047{
d3180279 1048 struct child_process hook = CHILD_PROCESS_INIT;
15048f8a 1049 const char *p;
ae98a008 1050
5a7da2dc
AS
1051 p = find_hook(name);
1052 if (!p)
cf94ca8e
SB
1053 return 0;
1054
d1d09456
RS
1055 argv_array_push(&hook.args, p);
1056 while ((p = va_arg(args, const char *)))
1057 argv_array_push(&hook.args, p);
15048f8a 1058 hook.env = env;
ae98a008
SB
1059 hook.no_stdin = 1;
1060 hook.stdout_to_stderr = 1;
ae98a008 1061
d1d09456 1062 return run_command(&hook);
ae98a008 1063}
15048f8a
BP
1064
1065int run_hook_le(const char *const *env, const char *name, ...)
1066{
1067 va_list args;
1068 int ret;
1069
1070 va_start(args, name);
1071 ret = run_hook_ve(env, name, args);
1072 va_end(args);
1073
1074 return ret;
1075}
911ec99b 1076
96335bcf
JK
1077struct io_pump {
1078 /* initialized by caller */
1079 int fd;
1080 int type; /* POLLOUT or POLLIN */
1081 union {
1082 struct {
1083 const char *buf;
1084 size_t len;
1085 } out;
1086 struct {
1087 struct strbuf *buf;
1088 size_t hint;
1089 } in;
1090 } u;
1091
1092 /* returned by pump_io */
1093 int error; /* 0 for success, otherwise errno */
1094
1095 /* internal use */
1096 struct pollfd *pfd;
1097};
1098
1099static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1100{
1101 int pollsize = 0;
1102 int i;
1103
1104 for (i = 0; i < nr; i++) {
1105 struct io_pump *io = &slots[i];
1106 if (io->fd < 0)
1107 continue;
1108 pfd[pollsize].fd = io->fd;
1109 pfd[pollsize].events = io->type;
1110 io->pfd = &pfd[pollsize++];
1111 }
1112
1113 if (!pollsize)
1114 return 0;
1115
1116 if (poll(pfd, pollsize, -1) < 0) {
1117 if (errno == EINTR)
1118 return 1;
1119 die_errno("poll failed");
1120 }
1121
1122 for (i = 0; i < nr; i++) {
1123 struct io_pump *io = &slots[i];
1124
1125 if (io->fd < 0)
1126 continue;
1127
1128 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1129 continue;
1130
1131 if (io->type == POLLOUT) {
1132 ssize_t len = xwrite(io->fd,
1133 io->u.out.buf, io->u.out.len);
1134 if (len < 0) {
1135 io->error = errno;
1136 close(io->fd);
1137 io->fd = -1;
1138 } else {
1139 io->u.out.buf += len;
1140 io->u.out.len -= len;
1141 if (!io->u.out.len) {
1142 close(io->fd);
1143 io->fd = -1;
1144 }
1145 }
1146 }
1147
1148 if (io->type == POLLIN) {
1149 ssize_t len = strbuf_read_once(io->u.in.buf,
1150 io->fd, io->u.in.hint);
1151 if (len < 0)
1152 io->error = errno;
1153 if (len <= 0) {
1154 close(io->fd);
1155 io->fd = -1;
1156 }
1157 }
1158 }
1159
1160 return 1;
1161}
1162
1163static int pump_io(struct io_pump *slots, int nr)
911ec99b 1164{
96335bcf
JK
1165 struct pollfd *pfd;
1166 int i;
1167
1168 for (i = 0; i < nr; i++)
1169 slots[i].error = 0;
1170
1171 ALLOC_ARRAY(pfd, nr);
1172 while (pump_io_round(slots, nr, pfd))
1173 ; /* nothing */
1174 free(pfd);
1175
1176 /* There may be multiple errno values, so just pick the first. */
1177 for (i = 0; i < nr; i++) {
1178 if (slots[i].error) {
1179 errno = slots[i].error;
1180 return -1;
1181 }
1182 }
1183 return 0;
1184}
1185
1186
1187int pipe_command(struct child_process *cmd,
1188 const char *in, size_t in_len,
1189 struct strbuf *out, size_t out_hint,
1190 struct strbuf *err, size_t err_hint)
1191{
1192 struct io_pump io[3];
1193 int nr = 0;
1194
1195 if (in)
1196 cmd->in = -1;
1197 if (out)
1198 cmd->out = -1;
1199 if (err)
1200 cmd->err = -1;
1201
911ec99b
JK
1202 if (start_command(cmd) < 0)
1203 return -1;
1204
96335bcf
JK
1205 if (in) {
1206 io[nr].fd = cmd->in;
1207 io[nr].type = POLLOUT;
1208 io[nr].u.out.buf = in;
1209 io[nr].u.out.len = in_len;
1210 nr++;
1211 }
1212 if (out) {
1213 io[nr].fd = cmd->out;
1214 io[nr].type = POLLIN;
1215 io[nr].u.in.buf = out;
1216 io[nr].u.in.hint = out_hint;
1217 nr++;
1218 }
1219 if (err) {
1220 io[nr].fd = cmd->err;
1221 io[nr].type = POLLIN;
1222 io[nr].u.in.buf = err;
1223 io[nr].u.in.hint = err_hint;
1224 nr++;
1225 }
1226
1227 if (pump_io(io, nr) < 0) {
911ec99b
JK
1228 finish_command(cmd); /* throw away exit code */
1229 return -1;
1230 }
1231
911ec99b
JK
1232 return finish_command(cmd);
1233}
c553c72e
SB
1234
1235enum child_state {
1236 GIT_CP_FREE,
1237 GIT_CP_WORKING,
1238 GIT_CP_WAIT_CLEANUP,
1239};
1240
1241struct parallel_processes {
1242 void *data;
1243
1244 int max_processes;
1245 int nr_processes;
1246
1247 get_next_task_fn get_next_task;
1248 start_failure_fn start_failure;
1249 task_finished_fn task_finished;
1250
1251 struct {
1252 enum child_state state;
1253 struct child_process process;
1254 struct strbuf err;
1255 void *data;
1256 } *children;
1257 /*
1258 * The struct pollfd is logically part of *children,
1259 * but the system call expects it as its own array.
1260 */
1261 struct pollfd *pfd;
1262
1263 unsigned shutdown : 1;
1264
1265 int output_owner;
1266 struct strbuf buffered_output; /* of finished children */
1267};
1268
aa710494 1269static int default_start_failure(struct strbuf *out,
c553c72e
SB
1270 void *pp_cb,
1271 void *pp_task_cb)
1272{
c553c72e
SB
1273 return 0;
1274}
1275
1276static int default_task_finished(int result,
aa710494 1277 struct strbuf *out,
c553c72e
SB
1278 void *pp_cb,
1279 void *pp_task_cb)
1280{
c553c72e
SB
1281 return 0;
1282}
1283
1284static void kill_children(struct parallel_processes *pp, int signo)
1285{
1286 int i, n = pp->max_processes;
1287
1288 for (i = 0; i < n; i++)
1289 if (pp->children[i].state == GIT_CP_WORKING)
1290 kill(pp->children[i].process.pid, signo);
1291}
1292
1293static struct parallel_processes *pp_for_signal;
1294
1295static void handle_children_on_signal(int signo)
1296{
1297 kill_children(pp_for_signal, signo);
1298 sigchain_pop(signo);
1299 raise(signo);
1300}
1301
1302static void pp_init(struct parallel_processes *pp,
1303 int n,
1304 get_next_task_fn get_next_task,
1305 start_failure_fn start_failure,
1306 task_finished_fn task_finished,
1307 void *data)
1308{
1309 int i;
1310
1311 if (n < 1)
1312 n = online_cpus();
1313
1314 pp->max_processes = n;
1315
1316 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1317
1318 pp->data = data;
1319 if (!get_next_task)
1320 die("BUG: you need to specify a get_next_task function");
1321 pp->get_next_task = get_next_task;
1322
1323 pp->start_failure = start_failure ? start_failure : default_start_failure;
1324 pp->task_finished = task_finished ? task_finished : default_task_finished;
1325
1326 pp->nr_processes = 0;
1327 pp->output_owner = 0;
1328 pp->shutdown = 0;
1329 pp->children = xcalloc(n, sizeof(*pp->children));
1330 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1331 strbuf_init(&pp->buffered_output, 0);
1332
1333 for (i = 0; i < n; i++) {
1334 strbuf_init(&pp->children[i].err, 0);
1335 child_process_init(&pp->children[i].process);
1336 pp->pfd[i].events = POLLIN | POLLHUP;
1337 pp->pfd[i].fd = -1;
1338 }
1339
1340 pp_for_signal = pp;
1341 sigchain_push_common(handle_children_on_signal);
1342}
1343
1344static void pp_cleanup(struct parallel_processes *pp)
1345{
1346 int i;
1347
1348 trace_printf("run_processes_parallel: done");
1349 for (i = 0; i < pp->max_processes; i++) {
1350 strbuf_release(&pp->children[i].err);
1351 child_process_clear(&pp->children[i].process);
1352 }
1353
1354 free(pp->children);
1355 free(pp->pfd);
1356
1357 /*
1358 * When get_next_task added messages to the buffer in its last
1359 * iteration, the buffered output is non empty.
1360 */
2dac9b56 1361 strbuf_write(&pp->buffered_output, stderr);
c553c72e
SB
1362 strbuf_release(&pp->buffered_output);
1363
1364 sigchain_pop_common();
1365}
1366
1367/* returns
1368 * 0 if a new task was started.
1369 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1370 * problem with starting a new command)
1371 * <0 no new job was started, user wishes to shutdown early. Use negative code
1372 * to signal the children.
1373 */
1374static int pp_start_one(struct parallel_processes *pp)
1375{
1376 int i, code;
1377
1378 for (i = 0; i < pp->max_processes; i++)
1379 if (pp->children[i].state == GIT_CP_FREE)
1380 break;
1381 if (i == pp->max_processes)
1382 die("BUG: bookkeeping is hard");
1383
1384 code = pp->get_next_task(&pp->children[i].process,
1385 &pp->children[i].err,
1386 pp->data,
1387 &pp->children[i].data);
1388 if (!code) {
1389 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1390 strbuf_reset(&pp->children[i].err);
1391 return 1;
1392 }
1393 pp->children[i].process.err = -1;
1394 pp->children[i].process.stdout_to_stderr = 1;
1395 pp->children[i].process.no_stdin = 1;
1396
1397 if (start_command(&pp->children[i].process)) {
2a73b3da 1398 code = pp->start_failure(&pp->children[i].err,
c553c72e
SB
1399 pp->data,
1400 &pp->children[i].data);
1401 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1402 strbuf_reset(&pp->children[i].err);
1403 if (code)
1404 pp->shutdown = 1;
1405 return code;
1406 }
1407
1408 pp->nr_processes++;
1409 pp->children[i].state = GIT_CP_WORKING;
1410 pp->pfd[i].fd = pp->children[i].process.err;
1411 return 0;
1412}
1413
1414static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1415{
1416 int i;
1417
1418 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1419 if (errno == EINTR)
1420 continue;
1421 pp_cleanup(pp);
1422 die_errno("poll");
1423 }
1424
1425 /* Buffer output from all pipes. */
1426 for (i = 0; i < pp->max_processes; i++) {
1427 if (pp->children[i].state == GIT_CP_WORKING &&
1428 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1429 int n = strbuf_read_once(&pp->children[i].err,
1430 pp->children[i].process.err, 0);
1431 if (n == 0) {
1432 close(pp->children[i].process.err);
1433 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1434 } else if (n < 0)
1435 if (errno != EAGAIN)
1436 die_errno("read");
1437 }
1438 }
1439}
1440
1441static void pp_output(struct parallel_processes *pp)
1442{
1443 int i = pp->output_owner;
1444 if (pp->children[i].state == GIT_CP_WORKING &&
1445 pp->children[i].err.len) {
2dac9b56 1446 strbuf_write(&pp->children[i].err, stderr);
c553c72e
SB
1447 strbuf_reset(&pp->children[i].err);
1448 }
1449}
1450
1451static int pp_collect_finished(struct parallel_processes *pp)
1452{
1453 int i, code;
1454 int n = pp->max_processes;
1455 int result = 0;
1456
1457 while (pp->nr_processes > 0) {
1458 for (i = 0; i < pp->max_processes; i++)
1459 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1460 break;
1461 if (i == pp->max_processes)
1462 break;
1463
1464 code = finish_command(&pp->children[i].process);
1465
2a73b3da 1466 code = pp->task_finished(code,
c553c72e
SB
1467 &pp->children[i].err, pp->data,
1468 &pp->children[i].data);
1469
1470 if (code)
1471 result = code;
1472 if (code < 0)
1473 break;
1474
1475 pp->nr_processes--;
1476 pp->children[i].state = GIT_CP_FREE;
1477 pp->pfd[i].fd = -1;
1478 child_process_init(&pp->children[i].process);
1479
1480 if (i != pp->output_owner) {
1481 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1482 strbuf_reset(&pp->children[i].err);
1483 } else {
2dac9b56 1484 strbuf_write(&pp->children[i].err, stderr);
c553c72e
SB
1485 strbuf_reset(&pp->children[i].err);
1486
1487 /* Output all other finished child processes */
2dac9b56 1488 strbuf_write(&pp->buffered_output, stderr);
c553c72e
SB
1489 strbuf_reset(&pp->buffered_output);
1490
1491 /*
1492 * Pick next process to output live.
1493 * NEEDSWORK:
1494 * For now we pick it randomly by doing a round
1495 * robin. Later we may want to pick the one with
1496 * the most output or the longest or shortest
1497 * running process time.
1498 */
1499 for (i = 0; i < n; i++)
1500 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1501 break;
1502 pp->output_owner = (pp->output_owner + i) % n;
1503 }
1504 }
1505 return result;
1506}
1507
1508int run_processes_parallel(int n,
1509 get_next_task_fn get_next_task,
1510 start_failure_fn start_failure,
1511 task_finished_fn task_finished,
1512 void *pp_cb)
1513{
1514 int i, code;
1515 int output_timeout = 100;
1516 int spawn_cap = 4;
1517 struct parallel_processes pp;
1518
1519 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1520 while (1) {
1521 for (i = 0;
1522 i < spawn_cap && !pp.shutdown &&
1523 pp.nr_processes < pp.max_processes;
1524 i++) {
1525 code = pp_start_one(&pp);
1526 if (!code)
1527 continue;
1528 if (code < 0) {
1529 pp.shutdown = 1;
1530 kill_children(&pp, -code);
1531 }
1532 break;
1533 }
1534 if (!pp.nr_processes)
1535 break;
1536 pp_buffer_stderr(&pp, output_timeout);
1537 pp_output(&pp);
1538 code = pp_collect_finished(&pp);
1539 if (code) {
1540 pp.shutdown = 1;
1541 if (code < 0)
1542 kill_children(&pp, -code);
1543 }
1544 }
1545
1546 pp_cleanup(&pp);
1547 return 0;
1548}