Merge branch 'dj/log-graph-with-no-walk'
[git/mingw.git] / run-command.c
blob3afb124c79dcb234344e17795205153d4a2e0643
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec_cmd.h"
4 #include "sigchain.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 {
15 pid_t pid;
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)
23 while (children_to_clean) {
24 struct child_to_clean *p = children_to_clean;
25 children_to_clean = p->next;
26 kill(p->pid, sig);
27 free(p);
31 static void cleanup_children_on_signal(int sig)
33 cleanup_children(sig);
34 sigchain_pop(sig);
35 raise(sig);
38 static void cleanup_children_on_exit(void)
40 cleanup_children(SIGTERM);
43 static void mark_child_for_cleanup(pid_t pid)
45 struct child_to_clean *p = xmalloc(sizeof(*p));
46 p->pid = pid;
47 p->next = children_to_clean;
48 children_to_clean = p;
50 if (!installed_child_cleanup_handler) {
51 atexit(cleanup_children_on_exit);
52 sigchain_push_common(cleanup_children_on_signal);
53 installed_child_cleanup_handler = 1;
57 static void clear_child_for_cleanup(pid_t pid)
59 struct child_to_clean **pp;
61 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
62 struct child_to_clean *clean_me = *pp;
64 if (clean_me->pid == pid) {
65 *pp = clean_me->next;
66 free(clean_me);
67 return;
72 static inline void close_pair(int fd[2])
74 close(fd[0]);
75 close(fd[1]);
78 #ifndef GIT_WINDOWS_NATIVE
79 static inline void dup_devnull(int to)
81 int fd = open("/dev/null", O_RDWR);
82 if (fd < 0)
83 die_errno(_("open /dev/null failed"));
84 if (dup2(fd, to) < 0)
85 die_errno(_("dup2(%d,%d) failed"), fd, to);
86 close(fd);
88 #endif
90 static char *locate_in_PATH(const char *file)
92 const char *p = getenv("PATH");
93 struct strbuf buf = STRBUF_INIT;
95 if (!p || !*p)
96 return NULL;
98 while (1) {
99 const char *end = strchrnul(p, ':');
101 strbuf_reset(&buf);
103 /* POSIX specifies an empty entry as the current directory. */
104 if (end != p) {
105 strbuf_add(&buf, p, end - p);
106 strbuf_addch(&buf, '/');
108 strbuf_addstr(&buf, file);
110 if (!access(buf.buf, F_OK))
111 return strbuf_detach(&buf, NULL);
113 if (!*end)
114 break;
115 p = end + 1;
118 strbuf_release(&buf);
119 return NULL;
122 static int exists_in_PATH(const char *file)
124 char *r = locate_in_PATH(file);
125 free(r);
126 return r != NULL;
129 int sane_execvp(const char *file, char * const argv[])
131 if (!execvp(file, argv))
132 return 0; /* cannot happen ;-) */
135 * When a command can't be found because one of the directories
136 * listed in $PATH is unsearchable, execvp reports EACCES, but
137 * careful usability testing (read: analysis of occasional bug
138 * reports) reveals that "No such file or directory" is more
139 * intuitive.
141 * We avoid commands with "/", because execvp will not do $PATH
142 * lookups in that case.
144 * The reassignment of EACCES to errno looks like a no-op below,
145 * but we need to protect against exists_in_PATH overwriting errno.
147 if (errno == EACCES && !strchr(file, '/'))
148 errno = exists_in_PATH(file) ? EACCES : ENOENT;
149 else if (errno == ENOTDIR && !strchr(file, '/'))
150 errno = ENOENT;
151 return -1;
154 static const char **prepare_shell_cmd(const char **argv)
156 int argc, nargc = 0;
157 const char **nargv;
159 for (argc = 0; argv[argc]; argc++)
160 ; /* just counting */
161 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
162 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
164 if (argc < 1)
165 die("BUG: shell command is empty");
167 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
168 #ifndef GIT_WINDOWS_NATIVE
169 nargv[nargc++] = SHELL_PATH;
170 #else
171 nargv[nargc++] = "sh";
172 #endif
173 nargv[nargc++] = "-c";
175 if (argc < 2)
176 nargv[nargc++] = argv[0];
177 else {
178 struct strbuf arg0 = STRBUF_INIT;
179 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
180 nargv[nargc++] = strbuf_detach(&arg0, NULL);
184 for (argc = 0; argv[argc]; argc++)
185 nargv[nargc++] = argv[argc];
186 nargv[nargc] = NULL;
188 return nargv;
191 #ifndef GIT_WINDOWS_NATIVE
192 static int execv_shell_cmd(const char **argv)
194 const char **nargv = prepare_shell_cmd(argv);
195 trace_argv_printf(nargv, "trace: exec:");
196 sane_execvp(nargv[0], (char **)nargv);
197 free(nargv);
198 return -1;
200 #endif
202 #ifndef GIT_WINDOWS_NATIVE
203 static int child_err = 2;
204 static int child_notifier = -1;
206 static void notify_parent(void)
209 * execvp failed. If possible, we'd like to let start_command
210 * know, so failures like ENOENT can be handled right away; but
211 * otherwise, finish_command will still report the error.
213 xwrite(child_notifier, "", 1);
216 static NORETURN void die_child(const char *err, va_list params)
218 vwritef(child_err, "fatal: ", err, params);
219 exit(128);
222 static void error_child(const char *err, va_list params)
224 vwritef(child_err, "error: ", err, params);
226 #endif
228 static inline void set_cloexec(int fd)
230 int flags = fcntl(fd, F_GETFD);
231 if (flags >= 0)
232 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
235 static int wait_or_whine(pid_t pid, const char *argv0)
237 int status, code = -1;
238 pid_t waiting;
239 int failed_errno = 0;
241 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
242 ; /* nothing */
244 if (waiting < 0) {
245 failed_errno = errno;
246 error("waitpid for %s failed: %s", argv0, strerror(errno));
247 } else if (waiting != pid) {
248 error("waitpid is confused (%s)", argv0);
249 } else if (WIFSIGNALED(status)) {
250 code = WTERMSIG(status);
251 if (code != SIGINT && code != SIGQUIT)
252 error("%s died of signal %d", argv0, code);
254 * This return value is chosen so that code & 0xff
255 * mimics the exit code that a POSIX shell would report for
256 * a program that died from this signal.
258 code += 128;
259 } else if (WIFEXITED(status)) {
260 code = WEXITSTATUS(status);
262 * Convert special exit code when execvp failed.
264 if (code == 127) {
265 code = -1;
266 failed_errno = ENOENT;
268 } else {
269 error("waitpid is confused (%s)", argv0);
272 clear_child_for_cleanup(pid);
274 errno = failed_errno;
275 return code;
278 int start_command(struct child_process *cmd)
280 int need_in, need_out, need_err;
281 int fdin[2], fdout[2], fderr[2];
282 int failed_errno;
283 char *str;
285 if (!cmd->argv)
286 cmd->argv = cmd->args.argv;
287 if (!cmd->env)
288 cmd->env = cmd->env_array.argv;
291 * In case of errors we must keep the promise to close FDs
292 * that have been passed in via ->in and ->out.
295 need_in = !cmd->no_stdin && cmd->in < 0;
296 if (need_in) {
297 if (pipe(fdin) < 0) {
298 failed_errno = errno;
299 if (cmd->out > 0)
300 close(cmd->out);
301 str = "standard input";
302 goto fail_pipe;
304 cmd->in = fdin[1];
307 need_out = !cmd->no_stdout
308 && !cmd->stdout_to_stderr
309 && cmd->out < 0;
310 if (need_out) {
311 if (pipe(fdout) < 0) {
312 failed_errno = errno;
313 if (need_in)
314 close_pair(fdin);
315 else if (cmd->in)
316 close(cmd->in);
317 str = "standard output";
318 goto fail_pipe;
320 cmd->out = fdout[0];
323 need_err = !cmd->no_stderr && cmd->err < 0;
324 if (need_err) {
325 if (pipe(fderr) < 0) {
326 failed_errno = errno;
327 if (need_in)
328 close_pair(fdin);
329 else if (cmd->in)
330 close(cmd->in);
331 if (need_out)
332 close_pair(fdout);
333 else if (cmd->out)
334 close(cmd->out);
335 str = "standard error";
336 fail_pipe:
337 error("cannot create %s pipe for %s: %s",
338 str, cmd->argv[0], strerror(failed_errno));
339 argv_array_clear(&cmd->args);
340 argv_array_clear(&cmd->env_array);
341 errno = failed_errno;
342 return -1;
344 cmd->err = fderr[0];
347 trace_argv_printf(cmd->argv, "trace: run_command:");
348 fflush(NULL);
350 #ifndef GIT_WINDOWS_NATIVE
352 int notify_pipe[2];
353 if (pipe(notify_pipe))
354 notify_pipe[0] = notify_pipe[1] = -1;
356 cmd->pid = fork();
357 failed_errno = errno;
358 if (!cmd->pid) {
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) {
365 child_err = dup(2);
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);
376 if (cmd->no_stdin)
377 dup_devnull(0);
378 else if (need_in) {
379 dup2(fdin[0], 0);
380 close_pair(fdin);
381 } else if (cmd->in) {
382 dup2(cmd->in, 0);
383 close(cmd->in);
386 if (cmd->no_stderr)
387 dup_devnull(2);
388 else if (need_err) {
389 dup2(fderr[1], 2);
390 close_pair(fderr);
391 } else if (cmd->err > 1) {
392 dup2(cmd->err, 2);
393 close(cmd->err);
396 if (cmd->no_stdout)
397 dup_devnull(1);
398 else if (cmd->stdout_to_stderr)
399 dup2(2, 1);
400 else if (need_out) {
401 dup2(fdout[1], 1);
402 close_pair(fdout);
403 } else if (cmd->out > 1) {
404 dup2(cmd->out, 1);
405 close(cmd->out);
408 if (cmd->dir && chdir(cmd->dir))
409 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
410 cmd->dir);
411 if (cmd->env) {
412 for (; *cmd->env; cmd->env++) {
413 if (strchr(*cmd->env, '='))
414 putenv((char *)*cmd->env);
415 else
416 unsetenv(*cmd->env);
419 if (cmd->git_cmd)
420 execv_git_cmd(cmd->argv);
421 else if (cmd->use_shell)
422 execv_shell_cmd(cmd->argv);
423 else
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],
428 strerror(ENOENT));
429 exit(127);
430 } else {
431 die_errno("cannot exec '%s'", cmd->argv[0]);
434 if (cmd->pid < 0)
435 error("cannot fork() for %s: %s", cmd->argv[0],
436 strerror(errno));
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], &notify_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;
455 cmd->pid = -1;
457 close(notify_pipe[0]);
459 #else
461 int fhin = 0, fhout = 1, fherr = 2;
462 const char **sargv = cmd->argv;
464 if (cmd->no_stdin)
465 fhin = open("/dev/null", O_RDWR);
466 else if (need_in)
467 fhin = dup(fdin[0]);
468 else if (cmd->in)
469 fhin = dup(cmd->in);
471 if (cmd->no_stderr)
472 fherr = open("/dev/null", O_RDWR);
473 else if (need_err)
474 fherr = dup(fderr[1]);
475 else if (cmd->err > 2)
476 fherr = dup(cmd->err);
478 if (cmd->no_stdout)
479 fhout = open("/dev/null", O_RDWR);
480 else if (cmd->stdout_to_stderr)
481 fhout = dup(fherr);
482 else if (need_out)
483 fhout = dup(fdout[1]);
484 else if (cmd->out > 1)
485 fhout = dup(cmd->out);
487 if (cmd->git_cmd)
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);
500 if (cmd->git_cmd)
501 free(cmd->argv);
503 cmd->argv = sargv;
504 if (fhin != 0)
505 close(fhin);
506 if (fhout != 1)
507 close(fhout);
508 if (fherr != 2)
509 close(fherr);
511 #endif
513 if (cmd->pid < 0) {
514 if (need_in)
515 close_pair(fdin);
516 else if (cmd->in)
517 close(cmd->in);
518 if (need_out)
519 close_pair(fdout);
520 else if (cmd->out)
521 close(cmd->out);
522 if (need_err)
523 close_pair(fderr);
524 else if (cmd->err)
525 close(cmd->err);
526 argv_array_clear(&cmd->args);
527 argv_array_clear(&cmd->env_array);
528 errno = failed_errno;
529 return -1;
532 if (need_in)
533 close(fdin[0]);
534 else if (cmd->in)
535 close(cmd->in);
537 if (need_out)
538 close(fdout[1]);
539 else if (cmd->out)
540 close(cmd->out);
542 if (need_err)
543 close(fderr[1]);
544 else if (cmd->err)
545 close(cmd->err);
547 return 0;
550 int finish_command(struct child_process *cmd)
552 int ret = wait_or_whine(cmd->pid, cmd->argv[0]);
553 argv_array_clear(&cmd->args);
554 argv_array_clear(&cmd->env_array);
555 return ret;
558 int run_command(struct child_process *cmd)
560 int code = start_command(cmd);
561 if (code)
562 return code;
563 return finish_command(cmd);
566 int run_command_v_opt(const char **argv, int opt)
568 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
571 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
573 struct child_process cmd = CHILD_PROCESS_INIT;
574 cmd.argv = argv;
575 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
576 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
577 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
578 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
579 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
580 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
581 cmd.dir = dir;
582 cmd.env = env;
583 return run_command(&cmd);
586 #ifndef NO_PTHREADS
587 static pthread_t main_thread;
588 static int main_thread_set;
589 static pthread_key_t async_key;
590 static pthread_key_t async_die_counter;
592 static void *run_thread(void *data)
594 struct async *async = data;
595 intptr_t ret;
597 pthread_setspecific(async_key, async);
598 ret = async->proc(async->proc_in, async->proc_out, async->data);
599 return (void *)ret;
602 static NORETURN void die_async(const char *err, va_list params)
604 vreportf("fatal: ", err, params);
606 if (!pthread_equal(main_thread, pthread_self())) {
607 struct async *async = pthread_getspecific(async_key);
608 if (async->proc_in >= 0)
609 close(async->proc_in);
610 if (async->proc_out >= 0)
611 close(async->proc_out);
612 pthread_exit((void *)128);
615 exit(128);
618 static int async_die_is_recursing(void)
620 void *ret = pthread_getspecific(async_die_counter);
621 pthread_setspecific(async_die_counter, (void *)1);
622 return ret != NULL;
625 #else
627 static struct {
628 void (**handlers)(void);
629 size_t nr;
630 size_t alloc;
631 } git_atexit_hdlrs;
633 static int git_atexit_installed;
635 static void git_atexit_dispatch(void)
637 size_t i;
639 for (i=git_atexit_hdlrs.nr ; i ; i--)
640 git_atexit_hdlrs.handlers[i-1]();
643 static void git_atexit_clear(void)
645 free(git_atexit_hdlrs.handlers);
646 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
647 git_atexit_installed = 0;
650 #undef atexit
651 int git_atexit(void (*handler)(void))
653 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
654 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
655 if (!git_atexit_installed) {
656 if (atexit(&git_atexit_dispatch))
657 return -1;
658 git_atexit_installed = 1;
660 return 0;
662 #define atexit git_atexit
664 #endif
666 int start_async(struct async *async)
668 int need_in, need_out;
669 int fdin[2], fdout[2];
670 int proc_in, proc_out;
672 need_in = async->in < 0;
673 if (need_in) {
674 if (pipe(fdin) < 0) {
675 if (async->out > 0)
676 close(async->out);
677 return error("cannot create pipe: %s", strerror(errno));
679 async->in = fdin[1];
682 need_out = async->out < 0;
683 if (need_out) {
684 if (pipe(fdout) < 0) {
685 if (need_in)
686 close_pair(fdin);
687 else if (async->in)
688 close(async->in);
689 return error("cannot create pipe: %s", strerror(errno));
691 async->out = fdout[0];
694 if (need_in)
695 proc_in = fdin[0];
696 else if (async->in)
697 proc_in = async->in;
698 else
699 proc_in = -1;
701 if (need_out)
702 proc_out = fdout[1];
703 else if (async->out)
704 proc_out = async->out;
705 else
706 proc_out = -1;
708 #ifdef NO_PTHREADS
709 /* Flush stdio before fork() to avoid cloning buffers */
710 fflush(NULL);
712 async->pid = fork();
713 if (async->pid < 0) {
714 error("fork (async) failed: %s", strerror(errno));
715 goto error;
717 if (!async->pid) {
718 if (need_in)
719 close(fdin[1]);
720 if (need_out)
721 close(fdout[0]);
722 git_atexit_clear();
723 exit(!!async->proc(proc_in, proc_out, async->data));
726 mark_child_for_cleanup(async->pid);
728 if (need_in)
729 close(fdin[0]);
730 else if (async->in)
731 close(async->in);
733 if (need_out)
734 close(fdout[1]);
735 else if (async->out)
736 close(async->out);
737 #else
738 if (!main_thread_set) {
740 * We assume that the first time that start_async is called
741 * it is from the main thread.
743 main_thread_set = 1;
744 main_thread = pthread_self();
745 pthread_key_create(&async_key, NULL);
746 pthread_key_create(&async_die_counter, NULL);
747 set_die_routine(die_async);
748 set_die_is_recursing_routine(async_die_is_recursing);
751 if (proc_in >= 0)
752 set_cloexec(proc_in);
753 if (proc_out >= 0)
754 set_cloexec(proc_out);
755 async->proc_in = proc_in;
756 async->proc_out = proc_out;
758 int err = pthread_create(&async->tid, NULL, run_thread, async);
759 if (err) {
760 error("cannot create thread: %s", strerror(err));
761 goto error;
764 #endif
765 return 0;
767 error:
768 if (need_in)
769 close_pair(fdin);
770 else if (async->in)
771 close(async->in);
773 if (need_out)
774 close_pair(fdout);
775 else if (async->out)
776 close(async->out);
777 return -1;
780 int finish_async(struct async *async)
782 #ifdef NO_PTHREADS
783 return wait_or_whine(async->pid, "child process");
784 #else
785 void *ret = (void *)(intptr_t)(-1);
787 if (pthread_join(async->tid, &ret))
788 error("pthread_join failed");
789 return (int)(intptr_t)ret;
790 #endif
793 char *find_hook(const char *name)
795 char *path = git_path("hooks/%s", name);
796 if (access(path, X_OK) < 0)
797 path = NULL;
799 return path;
802 int run_hook_ve(const char *const *env, const char *name, va_list args)
804 struct child_process hook = CHILD_PROCESS_INIT;
805 const char *p;
807 p = find_hook(name);
808 if (!p)
809 return 0;
811 argv_array_push(&hook.args, p);
812 while ((p = va_arg(args, const char *)))
813 argv_array_push(&hook.args, p);
814 hook.env = env;
815 hook.no_stdin = 1;
816 hook.stdout_to_stderr = 1;
818 return run_command(&hook);
821 int run_hook_le(const char *const *env, const char *name, ...)
823 va_list args;
824 int ret;
826 va_start(args, name);
827 ret = run_hook_ve(env, name, args);
828 va_end(args);
830 return ret;