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 void child_process_clear(struct child_process *child)
16 argv_array_clear(&child->args);
17 argv_array_clear(&child->env_array);
20 struct child_to_clean {
22 struct child_to_clean *next;
24 static struct child_to_clean *children_to_clean;
25 static int installed_child_cleanup_handler;
27 static void cleanup_children(int sig)
29 while (children_to_clean) {
30 struct child_to_clean *p = children_to_clean;
31 children_to_clean = p->next;
37 static void cleanup_children_on_signal(int sig)
39 cleanup_children(sig);
44 static void cleanup_children_on_exit(void)
46 cleanup_children(SIGTERM);
49 static void mark_child_for_cleanup(pid_t pid)
51 struct child_to_clean *p = xmalloc(sizeof(*p));
53 p->next = children_to_clean;
54 children_to_clean = p;
56 if (!installed_child_cleanup_handler) {
57 atexit(cleanup_children_on_exit);
58 sigchain_push_common(cleanup_children_on_signal);
59 installed_child_cleanup_handler = 1;
63 static void clear_child_for_cleanup(pid_t pid)
65 struct child_to_clean **pp;
67 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
68 struct child_to_clean *clean_me = *pp;
70 if (clean_me->pid == pid) {
78 static inline void close_pair(int fd[2])
84 #ifndef GIT_WINDOWS_NATIVE
85 static inline void dup_devnull(int to)
87 int fd = open("/dev/null", O_RDWR);
89 die_errno(_("open /dev/null failed"));
91 die_errno(_("dup2(%d,%d) failed"), fd, to);
96 static char *locate_in_PATH(const char *file)
98 const char *p = getenv("PATH");
99 struct strbuf buf = STRBUF_INIT;
105 const char *end = strchrnul(p, ':');
109 /* POSIX specifies an empty entry as the current directory. */
111 strbuf_add(&buf, p, end - p);
112 strbuf_addch(&buf, '/');
114 strbuf_addstr(&buf, file);
116 if (!access(buf.buf, F_OK))
117 return strbuf_detach(&buf, NULL);
124 strbuf_release(&buf);
128 static int exists_in_PATH(const char *file)
130 char *r = locate_in_PATH(file);
135 int sane_execvp(const char *file, char * const argv[])
137 if (!execvp(file, argv))
138 return 0; /* cannot happen ;-) */
141 * When a command can't be found because one of the directories
142 * listed in $PATH is unsearchable, execvp reports EACCES, but
143 * careful usability testing (read: analysis of occasional bug
144 * reports) reveals that "No such file or directory" is more
147 * We avoid commands with "/", because execvp will not do $PATH
148 * lookups in that case.
150 * The reassignment of EACCES to errno looks like a no-op below,
151 * but we need to protect against exists_in_PATH overwriting errno.
153 if (errno == EACCES && !strchr(file, '/'))
154 errno = exists_in_PATH(file) ? EACCES : ENOENT;
155 else if (errno == ENOTDIR && !strchr(file, '/'))
160 static const char **prepare_shell_cmd(const char **argv)
165 for (argc = 0; argv[argc]; argc++)
166 ; /* just counting */
167 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
168 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
171 die("BUG: shell command is empty");
173 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
174 #ifndef GIT_WINDOWS_NATIVE
175 nargv[nargc++] = SHELL_PATH;
177 nargv[nargc++] = "sh";
179 nargv[nargc++] = "-c";
182 nargv[nargc++] = argv[0];
184 struct strbuf arg0 = STRBUF_INIT;
185 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
186 nargv[nargc++] = strbuf_detach(&arg0, NULL);
190 for (argc = 0; argv[argc]; argc++)
191 nargv[nargc++] = argv[argc];
197 #ifndef GIT_WINDOWS_NATIVE
198 static int execv_shell_cmd(const char **argv)
200 const char **nargv = prepare_shell_cmd(argv);
201 trace_argv_printf(nargv, "trace: exec:");
202 sane_execvp(nargv[0], (char **)nargv);
208 #ifndef GIT_WINDOWS_NATIVE
209 static int child_err = 2;
210 static int child_notifier = -1;
212 static void notify_parent(void)
215 * execvp failed. If possible, we'd like to let start_command
216 * know, so failures like ENOENT can be handled right away; but
217 * otherwise, finish_command will still report the error.
219 xwrite(child_notifier, "", 1);
222 static NORETURN void die_child(const char *err, va_list params)
224 vwritef(child_err, "fatal: ", err, params);
228 static void error_child(const char *err, va_list params)
230 vwritef(child_err, "error: ", err, params);
234 static inline void set_cloexec(int fd)
236 int flags = fcntl(fd, F_GETFD);
238 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
241 static int wait_or_whine(pid_t pid, const char *argv0)
243 int status, code = -1;
245 int failed_errno = 0;
247 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
251 failed_errno = errno;
252 error("waitpid for %s failed: %s", argv0, strerror(errno));
253 } else if (waiting != pid) {
254 error("waitpid is confused (%s)", argv0);
255 } else if (WIFSIGNALED(status)) {
256 code = WTERMSIG(status);
257 if (code != SIGINT && code != SIGQUIT)
258 error("%s died of signal %d", argv0, code);
260 * This return value is chosen so that code & 0xff
261 * mimics the exit code that a POSIX shell would report for
262 * a program that died from this signal.
265 } else if (WIFEXITED(status)) {
266 code = WEXITSTATUS(status);
268 * Convert special exit code when execvp failed.
272 failed_errno = ENOENT;
275 error("waitpid is confused (%s)", argv0);
278 clear_child_for_cleanup(pid);
280 errno = failed_errno;
284 int start_command(struct child_process *cmd)
286 int need_in, need_out, need_err;
287 int fdin[2], fdout[2], fderr[2];
292 cmd->argv = cmd->args.argv;
294 cmd->env = cmd->env_array.argv;
297 * In case of errors we must keep the promise to close FDs
298 * that have been passed in via ->in and ->out.
301 need_in = !cmd->no_stdin && cmd->in < 0;
303 if (pipe(fdin) < 0) {
304 failed_errno = errno;
307 str = "standard input";
313 need_out = !cmd->no_stdout
314 && !cmd->stdout_to_stderr
317 if (pipe(fdout) < 0) {
318 failed_errno = errno;
323 str = "standard output";
329 need_err = !cmd->no_stderr && cmd->err < 0;
331 if (pipe(fderr) < 0) {
332 failed_errno = errno;
341 str = "standard error";
343 error("cannot create %s pipe for %s: %s",
344 str, cmd->argv[0], strerror(failed_errno));
345 child_process_clear(cmd);
346 errno = failed_errno;
352 trace_argv_printf(cmd->argv, "trace: run_command:");
355 #ifndef GIT_WINDOWS_NATIVE
358 if (pipe(notify_pipe))
359 notify_pipe[0] = notify_pipe[1] = -1;
362 failed_errno = errno;
365 * Redirect the channel to write syscall error messages to
366 * before redirecting the process's stderr so that all die()
367 * in subsequent call paths use the parent's stderr.
369 if (cmd->no_stderr || need_err) {
371 set_cloexec(child_err);
373 set_die_routine(die_child);
374 set_error_routine(error_child);
376 close(notify_pipe[0]);
377 set_cloexec(notify_pipe[1]);
378 child_notifier = notify_pipe[1];
379 atexit(notify_parent);
386 } else if (cmd->in) {
396 } else if (cmd->err > 1) {
403 else if (cmd->stdout_to_stderr)
408 } else if (cmd->out > 1) {
413 if (cmd->dir && chdir(cmd->dir))
414 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
417 for (; *cmd->env; cmd->env++) {
418 if (strchr(*cmd->env, '='))
419 putenv((char *)*cmd->env);
425 execv_git_cmd(cmd->argv);
426 else if (cmd->use_shell)
427 execv_shell_cmd(cmd->argv);
429 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
430 if (errno == ENOENT) {
431 if (!cmd->silent_exec_failure)
432 error("cannot run %s: %s", cmd->argv[0],
436 die_errno("cannot exec '%s'", cmd->argv[0]);
440 error("cannot fork() for %s: %s", cmd->argv[0],
442 else if (cmd->clean_on_exit)
443 mark_child_for_cleanup(cmd->pid);
446 * Wait for child's execvp. If the execvp succeeds (or if fork()
447 * failed), EOF is seen immediately by the parent. Otherwise, the
448 * child process sends a single byte.
449 * Note that use of this infrastructure is completely advisory,
450 * therefore, we keep error checks minimal.
452 close(notify_pipe[1]);
453 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
455 * At this point we know that fork() succeeded, but execvp()
456 * failed. Errors have been reported to our stderr.
458 wait_or_whine(cmd->pid, cmd->argv[0]);
459 failed_errno = errno;
462 close(notify_pipe[0]);
466 int fhin = 0, fhout = 1, fherr = 2;
467 const char **sargv = cmd->argv;
470 fhin = open("/dev/null", O_RDWR);
477 fherr = open("/dev/null", O_RDWR);
479 fherr = dup(fderr[1]);
480 else if (cmd->err > 2)
481 fherr = dup(cmd->err);
484 fhout = open("/dev/null", O_RDWR);
485 else if (cmd->stdout_to_stderr)
488 fhout = dup(fdout[1]);
489 else if (cmd->out > 1)
490 fhout = dup(cmd->out);
493 cmd->argv = prepare_git_cmd(cmd->argv);
494 else if (cmd->use_shell)
495 cmd->argv = prepare_shell_cmd(cmd->argv);
497 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
498 cmd->dir, fhin, fhout, fherr);
499 failed_errno = errno;
500 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
501 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
502 if (cmd->clean_on_exit && cmd->pid >= 0)
503 mark_child_for_cleanup(cmd->pid);
531 child_process_clear(cmd);
532 errno = failed_errno;
554 int finish_command(struct child_process *cmd)
556 int ret = wait_or_whine(cmd->pid, cmd->argv[0]);
557 child_process_clear(cmd);
561 int run_command(struct child_process *cmd)
565 if (cmd->out < 0 || cmd->err < 0)
566 die("BUG: run_command with a pipe can cause deadlock");
568 code = start_command(cmd);
571 return finish_command(cmd);
574 int run_command_v_opt(const char **argv, int opt)
576 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
579 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
581 struct child_process cmd = CHILD_PROCESS_INIT;
583 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
584 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
585 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
586 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
587 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
588 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
591 return run_command(&cmd);
595 static pthread_t main_thread;
596 static int main_thread_set;
597 static pthread_key_t async_key;
598 static pthread_key_t async_die_counter;
600 static void *run_thread(void *data)
602 struct async *async = data;
605 pthread_setspecific(async_key, async);
606 ret = async->proc(async->proc_in, async->proc_out, async->data);
610 static NORETURN void die_async(const char *err, va_list params)
612 vreportf("fatal: ", err, params);
614 if (!pthread_equal(main_thread, pthread_self())) {
615 struct async *async = pthread_getspecific(async_key);
616 if (async->proc_in >= 0)
617 close(async->proc_in);
618 if (async->proc_out >= 0)
619 close(async->proc_out);
620 pthread_exit((void *)128);
626 static int async_die_is_recursing(void)
628 void *ret = pthread_getspecific(async_die_counter);
629 pthread_setspecific(async_die_counter, (void *)1);
636 void (**handlers)(void);
641 static int git_atexit_installed;
643 static void git_atexit_dispatch(void)
647 for (i=git_atexit_hdlrs.nr ; i ; i--)
648 git_atexit_hdlrs.handlers[i-1]();
651 static void git_atexit_clear(void)
653 free(git_atexit_hdlrs.handlers);
654 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
655 git_atexit_installed = 0;
659 int git_atexit(void (*handler)(void))
661 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
662 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
663 if (!git_atexit_installed) {
664 if (atexit(&git_atexit_dispatch))
666 git_atexit_installed = 1;
670 #define atexit git_atexit
674 int start_async(struct async *async)
676 int need_in, need_out;
677 int fdin[2], fdout[2];
678 int proc_in, proc_out;
680 need_in = async->in < 0;
682 if (pipe(fdin) < 0) {
685 return error("cannot create pipe: %s", strerror(errno));
690 need_out = async->out < 0;
692 if (pipe(fdout) < 0) {
697 return error("cannot create pipe: %s", strerror(errno));
699 async->out = fdout[0];
712 proc_out = async->out;
717 /* Flush stdio before fork() to avoid cloning buffers */
721 if (async->pid < 0) {
722 error("fork (async) failed: %s", strerror(errno));
731 exit(!!async->proc(proc_in, proc_out, async->data));
734 mark_child_for_cleanup(async->pid);
746 if (!main_thread_set) {
748 * We assume that the first time that start_async is called
749 * it is from the main thread.
752 main_thread = pthread_self();
753 pthread_key_create(&async_key, NULL);
754 pthread_key_create(&async_die_counter, NULL);
755 set_die_routine(die_async);
756 set_die_is_recursing_routine(async_die_is_recursing);
760 set_cloexec(proc_in);
762 set_cloexec(proc_out);
763 async->proc_in = proc_in;
764 async->proc_out = proc_out;
766 int err = pthread_create(&async->tid, NULL, run_thread, async);
768 error("cannot create thread: %s", strerror(err));
788 int finish_async(struct async *async)
791 return wait_or_whine(async->pid, "child process");
793 void *ret = (void *)(intptr_t)(-1);
795 if (pthread_join(async->tid, &ret))
796 error("pthread_join failed");
797 return (int)(intptr_t)ret;
801 char *find_hook(const char *name)
803 char *path = git_path("hooks/%s", name);
804 if (access(path, X_OK) < 0)
810 int run_hook_ve(const char *const *env, const char *name, va_list args)
812 struct child_process hook = CHILD_PROCESS_INIT;
819 argv_array_push(&hook.args, p);
820 while ((p = va_arg(args, const char *)))
821 argv_array_push(&hook.args, p);
824 hook.stdout_to_stderr = 1;
826 return run_command(&hook);
829 int run_hook_le(const char *const *env, const char *name, ...)
834 va_start(args, name);
835 ret = run_hook_ve(env, name, args);
841 int capture_command(struct child_process *cmd, struct strbuf *buf, size_t hint)
844 if (start_command(cmd) < 0)
847 if (strbuf_read(buf, cmd->out, hint) < 0) {
849 finish_command(cmd); /* throw away exit code */
854 return finish_command(cmd);