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