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