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