2 #include "run-command.h"
5 #include "argv-array.h"
8 # define SHELL_PATH "/bin/sh"
11 struct child_to_clean {
13 struct child_to_clean *next;
15 static struct child_to_clean *children_to_clean;
16 static int installed_child_cleanup_handler;
18 static void cleanup_children(int sig)
20 while (children_to_clean) {
21 struct child_to_clean *p = children_to_clean;
22 children_to_clean = p->next;
28 static void cleanup_children_on_signal(int sig)
30 cleanup_children(sig);
35 static void cleanup_children_on_exit(void)
37 cleanup_children(SIGTERM);
40 static void mark_child_for_cleanup(pid_t pid)
42 struct child_to_clean *p = xmalloc(sizeof(*p));
44 p->next = children_to_clean;
45 children_to_clean = p;
47 if (!installed_child_cleanup_handler) {
48 atexit(cleanup_children_on_exit);
49 sigchain_push_common(cleanup_children_on_signal);
50 installed_child_cleanup_handler = 1;
54 static void clear_child_for_cleanup(pid_t pid)
56 struct child_to_clean **last, *p;
58 last = &children_to_clean;
59 for (p = children_to_clean; p; p = p->next) {
68 static inline void close_pair(int fd[2])
75 static inline void dup_devnull(int to)
77 int fd = open("/dev/null", O_RDWR);
83 static char *locate_in_PATH(const char *file)
85 const char *p = getenv("PATH");
86 struct strbuf buf = STRBUF_INIT;
92 const char *end = strchrnul(p, ':');
96 /* POSIX specifies an empty entry as the current directory. */
98 strbuf_add(&buf, p, end - p);
99 strbuf_addch(&buf, '/');
101 strbuf_addstr(&buf, file);
103 if (!access(buf.buf, F_OK))
104 return strbuf_detach(&buf, NULL);
111 strbuf_release(&buf);
115 static int exists_in_PATH(const char *file)
117 char *r = locate_in_PATH(file);
122 int sane_execvp(const char *file, char * const argv[])
124 if (!execvp(file, argv))
125 return 0; /* cannot happen ;-) */
128 * When a command can't be found because one of the directories
129 * listed in $PATH is unsearchable, execvp reports EACCES, but
130 * careful usability testing (read: analysis of occasional bug
131 * reports) reveals that "No such file or directory" is more
134 * We avoid commands with "/", because execvp will not do $PATH
135 * lookups in that case.
137 * The reassignment of EACCES to errno looks like a no-op below,
138 * but we need to protect against exists_in_PATH overwriting errno.
140 if (errno == EACCES && !strchr(file, '/'))
141 errno = exists_in_PATH(file) ? EACCES : ENOENT;
142 else if (errno == ENOTDIR && !strchr(file, '/'))
147 static const char **prepare_shell_cmd(const char **argv)
152 for (argc = 0; argv[argc]; argc++)
153 ; /* just counting */
154 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
155 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
158 die("BUG: shell command is empty");
160 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
162 nargv[nargc++] = SHELL_PATH;
164 nargv[nargc++] = "sh";
166 nargv[nargc++] = "-c";
169 nargv[nargc++] = argv[0];
171 struct strbuf arg0 = STRBUF_INIT;
172 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
173 nargv[nargc++] = strbuf_detach(&arg0, NULL);
177 for (argc = 0; argv[argc]; argc++)
178 nargv[nargc++] = argv[argc];
185 static int execv_shell_cmd(const char **argv)
187 const char **nargv = prepare_shell_cmd(argv);
188 trace_argv_printf(nargv, "trace: exec:");
189 sane_execvp(nargv[0], (char **)nargv);
196 static int child_err = 2;
197 static int child_notifier = -1;
199 static void notify_parent(void)
202 * execvp failed. If possible, we'd like to let start_command
203 * know, so failures like ENOENT can be handled right away; but
204 * otherwise, finish_command will still report the error.
206 xwrite(child_notifier, "", 1);
209 static NORETURN void die_child(const char *err, va_list params)
211 vwritef(child_err, "fatal: ", err, params);
215 static void error_child(const char *err, va_list params)
217 vwritef(child_err, "error: ", err, params);
221 static inline void set_cloexec(int fd)
223 int flags = fcntl(fd, F_GETFD);
225 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
228 static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
230 int status, code = -1;
232 int failed_errno = 0;
234 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
238 failed_errno = errno;
239 error("waitpid for %s failed: %s", argv0, strerror(errno));
240 } else if (waiting != pid) {
241 error("waitpid is confused (%s)", argv0);
242 } else if (WIFSIGNALED(status)) {
243 code = WTERMSIG(status);
244 error("%s died of signal %d", argv0, code);
246 * This return value is chosen so that code & 0xff
247 * mimics the exit code that a POSIX shell would report for
248 * a program that died from this signal.
251 } else if (WIFEXITED(status)) {
252 code = WEXITSTATUS(status);
254 * Convert special exit code when execvp failed.
258 failed_errno = ENOENT;
261 error("waitpid is confused (%s)", argv0);
264 clear_child_for_cleanup(pid);
266 errno = failed_errno;
270 int start_command(struct child_process *cmd)
272 int need_in, need_out, need_err;
273 int fdin[2], fdout[2], fderr[2];
274 int failed_errno = failed_errno;
277 * In case of errors we must keep the promise to close FDs
278 * that have been passed in via ->in and ->out.
281 need_in = !cmd->no_stdin && cmd->in < 0;
283 if (pipe(fdin) < 0) {
284 failed_errno = errno;
292 need_out = !cmd->no_stdout
293 && !cmd->stdout_to_stderr
296 if (pipe(fdout) < 0) {
297 failed_errno = errno;
307 need_err = !cmd->no_stderr && cmd->err < 0;
309 if (pipe(fderr) < 0) {
310 failed_errno = errno;
320 error("cannot create pipe for %s: %s",
321 cmd->argv[0], strerror(failed_errno));
322 errno = failed_errno;
328 trace_argv_printf(cmd->argv, "trace: run_command:");
334 if (pipe(notify_pipe))
335 notify_pipe[0] = notify_pipe[1] = -1;
340 * Redirect the channel to write syscall error messages to
341 * before redirecting the process's stderr so that all die()
342 * in subsequent call paths use the parent's stderr.
344 if (cmd->no_stderr || need_err) {
346 set_cloexec(child_err);
348 set_die_routine(die_child);
349 set_error_routine(error_child);
351 close(notify_pipe[0]);
352 set_cloexec(notify_pipe[1]);
353 child_notifier = notify_pipe[1];
354 atexit(notify_parent);
361 } else if (cmd->in) {
371 } else if (cmd->err > 1) {
378 else if (cmd->stdout_to_stderr)
383 } else if (cmd->out > 1) {
388 if (cmd->dir && chdir(cmd->dir))
389 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
392 for (; *cmd->env; cmd->env++) {
393 if (strchr(*cmd->env, '='))
394 putenv((char *)*cmd->env);
399 if (cmd->preexec_cb) {
401 * We cannot predict what the pre-exec callback does.
402 * Forgo parent notification.
404 close(child_notifier);
410 execv_git_cmd(cmd->argv);
411 } else if (cmd->use_shell) {
412 execv_shell_cmd(cmd->argv);
414 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
416 if (errno == ENOENT) {
417 if (!cmd->silent_exec_failure)
418 error("cannot run %s: %s", cmd->argv[0],
422 die_errno("cannot exec '%s'", cmd->argv[0]);
426 error("cannot fork() for %s: %s", cmd->argv[0],
427 strerror(failed_errno = errno));
428 else if (cmd->clean_on_exit)
429 mark_child_for_cleanup(cmd->pid);
432 * Wait for child's execvp. If the execvp succeeds (or if fork()
433 * failed), EOF is seen immediately by the parent. Otherwise, the
434 * child process sends a single byte.
435 * Note that use of this infrastructure is completely advisory,
436 * therefore, we keep error checks minimal.
438 close(notify_pipe[1]);
439 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
441 * At this point we know that fork() succeeded, but execvp()
442 * failed. Errors have been reported to our stderr.
444 wait_or_whine(cmd->pid, cmd->argv[0],
445 cmd->silent_exec_failure);
446 failed_errno = errno;
449 close(notify_pipe[0]);
454 int fhin = 0, fhout = 1, fherr = 2;
455 const char **sargv = cmd->argv;
456 char **env = environ;
459 fhin = open("/dev/null", O_RDWR);
466 fherr = open("/dev/null", O_RDWR);
468 fherr = dup(fderr[1]);
469 else if (cmd->err > 2)
470 fherr = dup(cmd->err);
473 fhout = open("/dev/null", O_RDWR);
474 else if (cmd->stdout_to_stderr)
477 fhout = dup(fdout[1]);
478 else if (cmd->out > 1)
479 fhout = dup(cmd->out);
482 env = make_augmented_environ(cmd->env);
485 cmd->argv = prepare_git_cmd(cmd->argv);
486 } else if (cmd->use_shell) {
487 cmd->argv = prepare_shell_cmd(cmd->argv);
490 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
492 failed_errno = errno;
493 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
494 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
495 if (cmd->clean_on_exit && cmd->pid >= 0)
496 mark_child_for_cleanup(cmd->pid);
526 errno = failed_errno;
548 int finish_command(struct child_process *cmd)
550 return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
553 int run_command(struct child_process *cmd)
555 int code = start_command(cmd);
558 return finish_command(cmd);
561 static void prepare_run_command_v_opt(struct child_process *cmd,
565 memset(cmd, 0, sizeof(*cmd));
567 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
568 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
569 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
570 cmd->silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
571 cmd->use_shell = opt & RUN_USING_SHELL ? 1 : 0;
572 cmd->clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
575 int run_command_v_opt(const char **argv, int opt)
577 struct child_process cmd;
578 prepare_run_command_v_opt(&cmd, argv, opt);
579 return run_command(&cmd);
582 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
584 struct child_process cmd;
585 prepare_run_command_v_opt(&cmd, argv, opt);
588 return run_command(&cmd);
592 static pthread_t main_thread;
593 static int main_thread_set;
594 static pthread_key_t async_key;
596 static void *run_thread(void *data)
598 struct async *async = data;
601 pthread_setspecific(async_key, async);
602 ret = async->proc(async->proc_in, async->proc_out, async->data);
606 static NORETURN void die_async(const char *err, va_list params)
608 vreportf("fatal: ", err, params);
610 if (!pthread_equal(main_thread, pthread_self())) {
611 struct async *async = pthread_getspecific(async_key);
612 if (async->proc_in >= 0)
613 close(async->proc_in);
614 if (async->proc_out >= 0)
615 close(async->proc_out);
616 pthread_exit((void *)128);
623 int start_async(struct async *async)
625 int need_in, need_out;
626 int fdin[2], fdout[2];
627 int proc_in, proc_out;
629 need_in = async->in < 0;
631 if (pipe(fdin) < 0) {
634 return error("cannot create pipe: %s", strerror(errno));
639 need_out = async->out < 0;
641 if (pipe(fdout) < 0) {
646 return error("cannot create pipe: %s", strerror(errno));
648 async->out = fdout[0];
661 proc_out = async->out;
666 /* Flush stdio before fork() to avoid cloning buffers */
670 if (async->pid < 0) {
671 error("fork (async) failed: %s", strerror(errno));
679 exit(!!async->proc(proc_in, proc_out, async->data));
682 mark_child_for_cleanup(async->pid);
694 if (!main_thread_set) {
696 * We assume that the first time that start_async is called
697 * it is from the main thread.
700 main_thread = pthread_self();
701 pthread_key_create(&async_key, NULL);
702 set_die_routine(die_async);
706 set_cloexec(proc_in);
708 set_cloexec(proc_out);
709 async->proc_in = proc_in;
710 async->proc_out = proc_out;
712 int err = pthread_create(&async->tid, NULL, run_thread, async);
714 error("cannot create thread: %s", strerror(err));
734 int finish_async(struct async *async)
737 return wait_or_whine(async->pid, "child process", 0);
739 void *ret = (void *)(intptr_t)(-1);
741 if (pthread_join(async->tid, &ret))
742 error("pthread_join failed");
743 return (int)(intptr_t)ret;
747 int run_hook(const char *index_file, const char *name, ...)
749 struct child_process hook;
750 struct argv_array argv = ARGV_ARRAY_INIT;
751 const char *p, *env[2];
752 char index[PATH_MAX];
756 if (access(git_path("hooks/%s", name), X_OK) < 0)
759 va_start(args, name);
760 argv_array_push(&argv, git_path("hooks/%s", name));
761 while ((p = va_arg(args, const char *)))
762 argv_array_push(&argv, p);
765 memset(&hook, 0, sizeof(hook));
766 hook.argv = argv.argv;
768 hook.stdout_to_stderr = 1;
770 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
776 ret = run_command(&hook);
777 argv_array_clear(&argv);