2 #include "run-command.h"
5 #include "argv-array.h"
8 # define SHELL_PATH "/bin/sh"
11 void child_process_init(struct child_process *child)
13 memset(child, 0, sizeof(*child));
14 argv_array_init(&child->args);
17 struct child_to_clean {
19 struct child_to_clean *next;
21 static struct child_to_clean *children_to_clean;
22 static int installed_child_cleanup_handler;
24 static void cleanup_children(int sig)
26 while (children_to_clean) {
27 struct child_to_clean *p = children_to_clean;
28 children_to_clean = p->next;
34 static void cleanup_children_on_signal(int sig)
36 cleanup_children(sig);
41 static void cleanup_children_on_exit(void)
43 cleanup_children(SIGTERM);
46 static void mark_child_for_cleanup(pid_t pid)
48 struct child_to_clean *p = xmalloc(sizeof(*p));
50 p->next = children_to_clean;
51 children_to_clean = p;
53 if (!installed_child_cleanup_handler) {
54 atexit(cleanup_children_on_exit);
55 sigchain_push_common(cleanup_children_on_signal);
56 installed_child_cleanup_handler = 1;
60 static void clear_child_for_cleanup(pid_t pid)
62 struct child_to_clean **pp;
64 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
65 struct child_to_clean *clean_me = *pp;
67 if (clean_me->pid == pid) {
75 static inline void close_pair(int fd[2])
81 #ifndef GIT_WINDOWS_NATIVE
82 static inline void dup_devnull(int to)
84 int fd = open("/dev/null", O_RDWR);
86 die_errno(_("open /dev/null failed"));
88 die_errno(_("dup2(%d,%d) failed"), fd, to);
93 static char *locate_in_PATH(const char *file)
95 const char *p = getenv("PATH");
96 struct strbuf buf = STRBUF_INIT;
102 const char *end = strchrnul(p, ':');
106 /* POSIX specifies an empty entry as the current directory. */
108 strbuf_add(&buf, p, end - p);
109 strbuf_addch(&buf, '/');
111 strbuf_addstr(&buf, file);
113 if (!access(buf.buf, F_OK))
114 return strbuf_detach(&buf, NULL);
121 strbuf_release(&buf);
125 static int exists_in_PATH(const char *file)
127 char *r = locate_in_PATH(file);
132 int sane_execvp(const char *file, char * const argv[])
134 if (!execvp(file, argv))
135 return 0; /* cannot happen ;-) */
138 * When a command can't be found because one of the directories
139 * listed in $PATH is unsearchable, execvp reports EACCES, but
140 * careful usability testing (read: analysis of occasional bug
141 * reports) reveals that "No such file or directory" is more
144 * We avoid commands with "/", because execvp will not do $PATH
145 * lookups in that case.
147 * The reassignment of EACCES to errno looks like a no-op below,
148 * but we need to protect against exists_in_PATH overwriting errno.
150 if (errno == EACCES && !strchr(file, '/'))
151 errno = exists_in_PATH(file) ? EACCES : ENOENT;
152 else if (errno == ENOTDIR && !strchr(file, '/'))
157 static const char **prepare_shell_cmd(const char **argv)
162 for (argc = 0; argv[argc]; argc++)
163 ; /* just counting */
164 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
165 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
168 die("BUG: shell command is empty");
170 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
171 #ifndef GIT_WINDOWS_NATIVE
172 nargv[nargc++] = SHELL_PATH;
174 nargv[nargc++] = "sh";
176 nargv[nargc++] = "-c";
179 nargv[nargc++] = argv[0];
181 struct strbuf arg0 = STRBUF_INIT;
182 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
183 nargv[nargc++] = strbuf_detach(&arg0, NULL);
187 for (argc = 0; argv[argc]; argc++)
188 nargv[nargc++] = argv[argc];
194 #ifndef GIT_WINDOWS_NATIVE
195 static int execv_shell_cmd(const char **argv)
197 const char **nargv = prepare_shell_cmd(argv);
198 trace_argv_printf(nargv, "trace: exec:");
199 sane_execvp(nargv[0], (char **)nargv);
205 #ifndef GIT_WINDOWS_NATIVE
206 static int child_err = 2;
207 static int child_notifier = -1;
209 static void notify_parent(void)
212 * execvp failed. If possible, we'd like to let start_command
213 * know, so failures like ENOENT can be handled right away; but
214 * otherwise, finish_command will still report the error.
216 xwrite(child_notifier, "", 1);
219 static NORETURN void die_child(const char *err, va_list params)
221 vwritef(child_err, "fatal: ", err, params);
225 static void error_child(const char *err, va_list params)
227 vwritef(child_err, "error: ", err, params);
231 static inline void set_cloexec(int fd)
233 int flags = fcntl(fd, F_GETFD);
235 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
238 static int wait_or_whine(pid_t pid, const char *argv0)
240 int status, code = -1;
242 int failed_errno = 0;
244 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;
292 * In case of errors we must keep the promise to close FDs
293 * that have been passed in via ->in and ->out.
296 need_in = !cmd->no_stdin && cmd->in < 0;
298 if (pipe(fdin) < 0) {
299 failed_errno = errno;
302 str = "standard input";
308 need_out = !cmd->no_stdout
309 && !cmd->stdout_to_stderr
312 if (pipe(fdout) < 0) {
313 failed_errno = errno;
318 str = "standard output";
324 need_err = !cmd->no_stderr && cmd->err < 0;
326 if (pipe(fderr) < 0) {
327 failed_errno = errno;
336 str = "standard error";
338 error("cannot create %s pipe for %s: %s",
339 str, cmd->argv[0], strerror(failed_errno));
340 argv_array_clear(&cmd->args);
341 errno = failed_errno;
347 trace_argv_printf(cmd->argv, "trace: run_command:");
350 #ifndef GIT_WINDOWS_NATIVE
353 if (pipe(notify_pipe))
354 notify_pipe[0] = notify_pipe[1] = -1;
357 failed_errno = errno;
360 * Redirect the channel to write syscall error messages to
361 * before redirecting the process's stderr so that all die()
362 * in subsequent call paths use the parent's stderr.
364 if (cmd->no_stderr || need_err) {
366 set_cloexec(child_err);
368 set_die_routine(die_child);
369 set_error_routine(error_child);
371 close(notify_pipe[0]);
372 set_cloexec(notify_pipe[1]);
373 child_notifier = notify_pipe[1];
374 atexit(notify_parent);
381 } else if (cmd->in) {
391 } else if (cmd->err > 1) {
398 else if (cmd->stdout_to_stderr)
403 } else if (cmd->out > 1) {
408 if (cmd->dir && chdir(cmd->dir))
409 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
412 for (; *cmd->env; cmd->env++) {
413 if (strchr(*cmd->env, '='))
414 putenv((char *)*cmd->env);
420 execv_git_cmd(cmd->argv);
421 else if (cmd->use_shell)
422 execv_shell_cmd(cmd->argv);
424 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
425 if (errno == ENOENT) {
426 if (!cmd->silent_exec_failure)
427 error("cannot run %s: %s", cmd->argv[0],
431 die_errno("cannot exec '%s'", cmd->argv[0]);
435 error("cannot fork() for %s: %s", cmd->argv[0],
437 else if (cmd->clean_on_exit)
438 mark_child_for_cleanup(cmd->pid);
441 * Wait for child's execvp. If the execvp succeeds (or if fork()
442 * failed), EOF is seen immediately by the parent. Otherwise, the
443 * child process sends a single byte.
444 * Note that use of this infrastructure is completely advisory,
445 * therefore, we keep error checks minimal.
447 close(notify_pipe[1]);
448 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
450 * At this point we know that fork() succeeded, but execvp()
451 * failed. Errors have been reported to our stderr.
453 wait_or_whine(cmd->pid, cmd->argv[0]);
454 failed_errno = errno;
457 close(notify_pipe[0]);
461 int fhin = 0, fhout = 1, fherr = 2;
462 const char **sargv = cmd->argv;
465 fhin = open("/dev/null", O_RDWR);
472 fherr = open("/dev/null", O_RDWR);
474 fherr = dup(fderr[1]);
475 else if (cmd->err > 2)
476 fherr = dup(cmd->err);
479 fhout = open("/dev/null", O_RDWR);
480 else if (cmd->stdout_to_stderr)
483 fhout = dup(fdout[1]);
484 else if (cmd->out > 1)
485 fhout = dup(cmd->out);
488 cmd->argv = prepare_git_cmd(cmd->argv);
489 else if (cmd->use_shell)
490 cmd->argv = prepare_shell_cmd(cmd->argv);
492 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
493 cmd->dir, fhin, fhout, fherr);
494 failed_errno = errno;
495 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
496 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
497 if (cmd->clean_on_exit && cmd->pid >= 0)
498 mark_child_for_cleanup(cmd->pid);
526 argv_array_clear(&cmd->args);
527 errno = failed_errno;
549 int finish_command(struct child_process *cmd)
551 int ret = wait_or_whine(cmd->pid, cmd->argv[0]);
552 argv_array_clear(&cmd->args);
556 int run_command(struct child_process *cmd)
558 int code = start_command(cmd);
561 return finish_command(cmd);
564 int run_command_v_opt(const char **argv, int opt)
566 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
569 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
571 struct child_process cmd = CHILD_PROCESS_INIT;
573 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
574 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
575 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
576 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
577 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
578 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
581 return run_command(&cmd);
585 static pthread_t main_thread;
586 static int main_thread_set;
587 static pthread_key_t async_key;
588 static pthread_key_t async_die_counter;
590 static void *run_thread(void *data)
592 struct async *async = data;
595 pthread_setspecific(async_key, async);
596 ret = async->proc(async->proc_in, async->proc_out, async->data);
600 static NORETURN void die_async(const char *err, va_list params)
602 vreportf("fatal: ", err, params);
604 if (!pthread_equal(main_thread, pthread_self())) {
605 struct async *async = pthread_getspecific(async_key);
606 if (async->proc_in >= 0)
607 close(async->proc_in);
608 if (async->proc_out >= 0)
609 close(async->proc_out);
610 pthread_exit((void *)128);
616 static int async_die_is_recursing(void)
618 void *ret = pthread_getspecific(async_die_counter);
619 pthread_setspecific(async_die_counter, (void *)1);
625 int start_async(struct async *async)
627 int need_in, need_out;
628 int fdin[2], fdout[2];
629 int proc_in, proc_out;
631 need_in = async->in < 0;
633 if (pipe(fdin) < 0) {
636 return error("cannot create pipe: %s", strerror(errno));
641 need_out = async->out < 0;
643 if (pipe(fdout) < 0) {
648 return error("cannot create pipe: %s", strerror(errno));
650 async->out = fdout[0];
663 proc_out = async->out;
668 /* Flush stdio before fork() to avoid cloning buffers */
672 if (async->pid < 0) {
673 error("fork (async) failed: %s", strerror(errno));
681 exit(!!async->proc(proc_in, proc_out, async->data));
684 mark_child_for_cleanup(async->pid);
696 if (!main_thread_set) {
698 * We assume that the first time that start_async is called
699 * it is from the main thread.
702 main_thread = pthread_self();
703 pthread_key_create(&async_key, NULL);
704 pthread_key_create(&async_die_counter, NULL);
705 set_die_routine(die_async);
706 set_die_is_recursing_routine(async_die_is_recursing);
710 set_cloexec(proc_in);
712 set_cloexec(proc_out);
713 async->proc_in = proc_in;
714 async->proc_out = proc_out;
716 int err = pthread_create(&async->tid, NULL, run_thread, async);
718 error("cannot create thread: %s", strerror(err));
738 int finish_async(struct async *async)
741 return wait_or_whine(async->pid, "child process");
743 void *ret = (void *)(intptr_t)(-1);
745 if (pthread_join(async->tid, &ret))
746 error("pthread_join failed");
747 return (int)(intptr_t)ret;
751 char *find_hook(const char *name)
753 char *path = git_path("hooks/%s", name);
754 if (access(path, X_OK) < 0)
760 int run_hook_ve(const char *const *env, const char *name, va_list args)
762 struct child_process hook = CHILD_PROCESS_INIT;
769 argv_array_push(&hook.args, p);
770 while ((p = va_arg(args, const char *)))
771 argv_array_push(&hook.args, p);
774 hook.stdout_to_stderr = 1;
776 return run_command(&hook);
779 int run_hook_le(const char *const *env, const char *name, ...)
784 va_start(args, name);
785 ret = run_hook_ve(env, name, args);
791 int run_hook_with_custom_index(const char *index_file, const char *name, ...)
793 const char *hook_env[3] = { NULL };
794 char index[PATH_MAX];
798 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
801 va_start(args, name);
802 ret = run_hook_ve(hook_env, name, args);