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