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