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