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