2 #include "run-command.h"
5 #include "argv-array.h"
7 void child_process_init(struct child_process *child)
9 memset(child, 0, sizeof(*child));
10 argv_array_init(&child->args);
11 argv_array_init(&child->env_array);
14 struct child_to_clean {
16 struct child_to_clean *next;
18 static struct child_to_clean *children_to_clean;
19 static int installed_child_cleanup_handler;
21 static void cleanup_children(int sig, int in_signal)
23 while (children_to_clean) {
24 struct child_to_clean *p = children_to_clean;
25 children_to_clean = p->next;
32 static void cleanup_children_on_signal(int sig)
34 cleanup_children(sig, 1);
39 static void cleanup_children_on_exit(void)
41 cleanup_children(SIGTERM, 0);
44 static void mark_child_for_cleanup(pid_t pid)
46 struct child_to_clean *p = xmalloc(sizeof(*p));
48 p->next = children_to_clean;
49 children_to_clean = p;
51 if (!installed_child_cleanup_handler) {
52 atexit(cleanup_children_on_exit);
53 sigchain_push_common(cleanup_children_on_signal);
54 installed_child_cleanup_handler = 1;
58 static void clear_child_for_cleanup(pid_t pid)
60 struct child_to_clean **pp;
62 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
63 struct child_to_clean *clean_me = *pp;
65 if (clean_me->pid == pid) {
73 static inline void close_pair(int fd[2])
79 #ifndef GIT_WINDOWS_NATIVE
80 static inline void dup_devnull(int to)
82 int fd = open("/dev/null", O_RDWR);
84 die_errno(_("open /dev/null failed"));
86 die_errno(_("dup2(%d,%d) failed"), fd, to);
91 static char *locate_in_PATH(const char *file)
93 const char *p = getenv("PATH");
94 struct strbuf buf = STRBUF_INIT;
100 const char *end = strchrnul(p, ':');
104 /* POSIX specifies an empty entry as the current directory. */
106 strbuf_add(&buf, p, end - p);
107 strbuf_addch(&buf, '/');
109 strbuf_addstr(&buf, file);
111 if (!access(buf.buf, F_OK))
112 return strbuf_detach(&buf, NULL);
119 strbuf_release(&buf);
123 static int exists_in_PATH(const char *file)
125 char *r = locate_in_PATH(file);
130 int sane_execvp(const char *file, char * const argv[])
132 if (!execvp(file, argv))
133 return 0; /* cannot happen ;-) */
136 * When a command can't be found because one of the directories
137 * listed in $PATH is unsearchable, execvp reports EACCES, but
138 * careful usability testing (read: analysis of occasional bug
139 * reports) reveals that "No such file or directory" is more
142 * We avoid commands with "/", because execvp will not do $PATH
143 * lookups in that case.
145 * The reassignment of EACCES to errno looks like a no-op below,
146 * but we need to protect against exists_in_PATH overwriting errno.
148 if (errno == EACCES && !strchr(file, '/'))
149 errno = exists_in_PATH(file) ? EACCES : ENOENT;
150 else if (errno == ENOTDIR && !strchr(file, '/'))
155 static const char **prepare_shell_cmd(const char **argv)
160 for (argc = 0; argv[argc]; argc++)
161 ; /* just counting */
162 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
163 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
166 die("BUG: shell command is empty");
168 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
169 #ifndef GIT_WINDOWS_NATIVE
170 nargv[nargc++] = SHELL_PATH;
172 nargv[nargc++] = "sh";
174 nargv[nargc++] = "-c";
177 nargv[nargc++] = argv[0];
179 struct strbuf arg0 = STRBUF_INIT;
180 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
181 nargv[nargc++] = strbuf_detach(&arg0, NULL);
185 for (argc = 0; argv[argc]; argc++)
186 nargv[nargc++] = argv[argc];
192 #ifndef GIT_WINDOWS_NATIVE
193 static int execv_shell_cmd(const char **argv)
195 const char **nargv = prepare_shell_cmd(argv);
196 trace_argv_printf(nargv, "trace: exec:");
197 sane_execvp(nargv[0], (char **)nargv);
203 #ifndef GIT_WINDOWS_NATIVE
204 static int child_err = 2;
205 static int child_notifier = -1;
207 static void notify_parent(void)
210 * execvp failed. If possible, we'd like to let start_command
211 * know, so failures like ENOENT can be handled right away; but
212 * otherwise, finish_command will still report the error.
214 xwrite(child_notifier, "", 1);
217 static NORETURN void die_child(const char *err, va_list params)
219 vwritef(child_err, "fatal: ", err, params);
223 static void error_child(const char *err, va_list params)
225 vwritef(child_err, "error: ", err, params);
229 static inline void set_cloexec(int fd)
231 int flags = fcntl(fd, F_GETFD);
233 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
236 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
238 int status, code = -1;
240 int failed_errno = 0;
242 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
248 failed_errno = errno;
249 error("waitpid for %s failed: %s", argv0, strerror(errno));
250 } else if (waiting != pid) {
251 error("waitpid is confused (%s)", argv0);
252 } else if (WIFSIGNALED(status)) {
253 code = WTERMSIG(status);
254 if (code != SIGINT && code != SIGQUIT)
255 error("%s died of signal %d", argv0, code);
257 * This return value is chosen so that code & 0xff
258 * mimics the exit code that a POSIX shell would report for
259 * a program that died from this signal.
262 } else if (WIFEXITED(status)) {
263 code = WEXITSTATUS(status);
265 * Convert special exit code when execvp failed.
269 failed_errno = ENOENT;
272 error("waitpid is confused (%s)", argv0);
275 clear_child_for_cleanup(pid);
277 errno = failed_errno;
281 int start_command(struct child_process *cmd)
283 int need_in, need_out, need_err;
284 int fdin[2], fdout[2], fderr[2];
289 cmd->argv = cmd->args.argv;
291 cmd->env = cmd->env_array.argv;
294 * In case of errors we must keep the promise to close FDs
295 * that have been passed in via ->in and ->out.
298 need_in = !cmd->no_stdin && cmd->in < 0;
300 if (pipe(fdin) < 0) {
301 failed_errno = errno;
304 str = "standard input";
310 need_out = !cmd->no_stdout
311 && !cmd->stdout_to_stderr
314 if (pipe(fdout) < 0) {
315 failed_errno = errno;
320 str = "standard output";
326 need_err = !cmd->no_stderr && cmd->err < 0;
328 if (pipe(fderr) < 0) {
329 failed_errno = errno;
338 str = "standard error";
340 error("cannot create %s pipe for %s: %s",
341 str, cmd->argv[0], strerror(failed_errno));
342 argv_array_clear(&cmd->args);
343 argv_array_clear(&cmd->env_array);
344 errno = failed_errno;
350 trace_argv_printf(cmd->argv, "trace: run_command:");
353 #ifndef GIT_WINDOWS_NATIVE
356 if (pipe(notify_pipe))
357 notify_pipe[0] = notify_pipe[1] = -1;
360 failed_errno = errno;
363 * Redirect the channel to write syscall error messages to
364 * before redirecting the process's stderr so that all die()
365 * in subsequent call paths use the parent's stderr.
367 if (cmd->no_stderr || need_err) {
369 set_cloexec(child_err);
371 set_die_routine(die_child);
372 set_error_routine(error_child);
374 close(notify_pipe[0]);
375 set_cloexec(notify_pipe[1]);
376 child_notifier = notify_pipe[1];
377 atexit(notify_parent);
384 } else if (cmd->in) {
394 } else if (cmd->err > 1) {
401 else if (cmd->stdout_to_stderr)
406 } else if (cmd->out > 1) {
411 if (cmd->dir && chdir(cmd->dir))
412 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
415 for (; *cmd->env; cmd->env++) {
416 if (strchr(*cmd->env, '='))
417 putenv((char *)*cmd->env);
423 execv_git_cmd(cmd->argv);
424 else if (cmd->use_shell)
425 execv_shell_cmd(cmd->argv);
427 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
428 if (errno == ENOENT) {
429 if (!cmd->silent_exec_failure)
430 error("cannot run %s: %s", cmd->argv[0],
434 die_errno("cannot exec '%s'", cmd->argv[0]);
438 error("cannot fork() for %s: %s", cmd->argv[0],
440 else if (cmd->clean_on_exit)
441 mark_child_for_cleanup(cmd->pid);
444 * Wait for child's execvp. If the execvp succeeds (or if fork()
445 * failed), EOF is seen immediately by the parent. Otherwise, the
446 * child process sends a single byte.
447 * Note that use of this infrastructure is completely advisory,
448 * therefore, we keep error checks minimal.
450 close(notify_pipe[1]);
451 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
453 * At this point we know that fork() succeeded, but execvp()
454 * failed. Errors have been reported to our stderr.
456 wait_or_whine(cmd->pid, cmd->argv[0], 0);
457 failed_errno = errno;
460 close(notify_pipe[0]);
464 int fhin = 0, fhout = 1, fherr = 2;
465 const char **sargv = cmd->argv;
468 fhin = open("/dev/null", O_RDWR);
475 fherr = open("/dev/null", O_RDWR);
477 fherr = dup(fderr[1]);
478 else if (cmd->err > 2)
479 fherr = dup(cmd->err);
482 fhout = open("/dev/null", O_RDWR);
483 else if (cmd->stdout_to_stderr)
486 fhout = dup(fdout[1]);
487 else if (cmd->out > 1)
488 fhout = dup(cmd->out);
491 cmd->argv = prepare_git_cmd(cmd->argv);
492 else if (cmd->use_shell)
493 cmd->argv = prepare_shell_cmd(cmd->argv);
495 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
496 cmd->dir, fhin, fhout, fherr);
497 failed_errno = errno;
498 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
499 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
500 if (cmd->clean_on_exit && cmd->pid >= 0)
501 mark_child_for_cleanup(cmd->pid);
529 argv_array_clear(&cmd->args);
530 argv_array_clear(&cmd->env_array);
531 errno = failed_errno;
553 int finish_command(struct child_process *cmd)
555 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
556 argv_array_clear(&cmd->args);
557 argv_array_clear(&cmd->env_array);
561 int finish_command_in_signal(struct child_process *cmd)
563 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
567 int run_command(struct child_process *cmd)
571 if (cmd->out < 0 || cmd->err < 0)
572 die("BUG: run_command with a pipe can cause deadlock");
574 code = start_command(cmd);
577 return finish_command(cmd);
580 int run_command_v_opt(const char **argv, int opt)
582 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
585 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
587 struct child_process cmd = CHILD_PROCESS_INIT;
589 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
590 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
591 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
592 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
593 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
594 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
597 return run_command(&cmd);
601 static pthread_t main_thread;
602 static int main_thread_set;
603 static pthread_key_t async_key;
604 static pthread_key_t async_die_counter;
606 static void *run_thread(void *data)
608 struct async *async = data;
611 pthread_setspecific(async_key, async);
612 ret = async->proc(async->proc_in, async->proc_out, async->data);
616 static NORETURN void die_async(const char *err, va_list params)
618 vreportf("fatal: ", err, params);
620 if (!pthread_equal(main_thread, pthread_self())) {
621 struct async *async = pthread_getspecific(async_key);
622 if (async->proc_in >= 0)
623 close(async->proc_in);
624 if (async->proc_out >= 0)
625 close(async->proc_out);
626 pthread_exit((void *)128);
632 static int async_die_is_recursing(void)
634 void *ret = pthread_getspecific(async_die_counter);
635 pthread_setspecific(async_die_counter, (void *)1);
642 void (**handlers)(void);
647 static int git_atexit_installed;
649 static void git_atexit_dispatch(void)
653 for (i=git_atexit_hdlrs.nr ; i ; i--)
654 git_atexit_hdlrs.handlers[i-1]();
657 static void git_atexit_clear(void)
659 free(git_atexit_hdlrs.handlers);
660 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
661 git_atexit_installed = 0;
665 int git_atexit(void (*handler)(void))
667 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
668 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
669 if (!git_atexit_installed) {
670 if (atexit(&git_atexit_dispatch))
672 git_atexit_installed = 1;
676 #define atexit git_atexit
680 int start_async(struct async *async)
682 int need_in, need_out;
683 int fdin[2], fdout[2];
684 int proc_in, proc_out;
686 need_in = async->in < 0;
688 if (pipe(fdin) < 0) {
691 return error("cannot create pipe: %s", strerror(errno));
696 need_out = async->out < 0;
698 if (pipe(fdout) < 0) {
703 return error("cannot create pipe: %s", strerror(errno));
705 async->out = fdout[0];
718 proc_out = async->out;
723 /* Flush stdio before fork() to avoid cloning buffers */
727 if (async->pid < 0) {
728 error("fork (async) failed: %s", strerror(errno));
737 exit(!!async->proc(proc_in, proc_out, async->data));
740 mark_child_for_cleanup(async->pid);
752 if (!main_thread_set) {
754 * We assume that the first time that start_async is called
755 * it is from the main thread.
758 main_thread = pthread_self();
759 pthread_key_create(&async_key, NULL);
760 pthread_key_create(&async_die_counter, NULL);
761 set_die_routine(die_async);
762 set_die_is_recursing_routine(async_die_is_recursing);
766 set_cloexec(proc_in);
768 set_cloexec(proc_out);
769 async->proc_in = proc_in;
770 async->proc_out = proc_out;
772 int err = pthread_create(&async->tid, NULL, run_thread, async);
774 error("cannot create thread: %s", strerror(err));
794 int finish_async(struct async *async)
797 return wait_or_whine(async->pid, "child process", 0);
799 void *ret = (void *)(intptr_t)(-1);
801 if (pthread_join(async->tid, &ret))
802 error("pthread_join failed");
803 return (int)(intptr_t)ret;
807 const char *find_hook(const char *name)
809 const char *path = git_path("hooks/%s", name);
810 if (access(path, X_OK) < 0)
816 int run_hook_ve(const char *const *env, const char *name, va_list args)
818 struct child_process hook = CHILD_PROCESS_INIT;
825 argv_array_push(&hook.args, p);
826 while ((p = va_arg(args, const char *)))
827 argv_array_push(&hook.args, p);
830 hook.stdout_to_stderr = 1;
832 return run_command(&hook);
835 int run_hook_le(const char *const *env, const char *name, ...)
840 va_start(args, name);
841 ret = run_hook_ve(env, name, args);
847 int capture_command(struct child_process *cmd, struct strbuf *buf, size_t hint)
850 if (start_command(cmd) < 0)
853 if (strbuf_read(buf, cmd->out, hint) < 0) {
855 finish_command(cmd); /* throw away exit code */
860 return finish_command(cmd);