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