Merge branch 'jk/blame-first-parent'
[git.git] / run-command.c
blobc8029f239405e463bba5b033a7321faf16ca6c0d
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_notifier = -1;
205 static void notify_parent(void)
208 * execvp failed. If possible, we'd like to let start_command
209 * know, so failures like ENOENT can be handled right away; but
210 * otherwise, finish_command will still report the error.
212 xwrite(child_notifier, "", 1);
214 #endif
216 static inline void set_cloexec(int fd)
218 int flags = fcntl(fd, F_GETFD);
219 if (flags >= 0)
220 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
223 static int wait_or_whine(pid_t pid, const char *argv0)
225 int status, code = -1;
226 pid_t waiting;
227 int failed_errno = 0;
229 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
230 ; /* nothing */
232 if (waiting < 0) {
233 failed_errno = errno;
234 error("waitpid for %s failed: %s", argv0, strerror(errno));
235 } else if (waiting != pid) {
236 error("waitpid is confused (%s)", argv0);
237 } else if (WIFSIGNALED(status)) {
238 code = WTERMSIG(status);
239 if (code != SIGINT && code != SIGQUIT)
240 error("%s died of signal %d", argv0, code);
242 * This return value is chosen so that code & 0xff
243 * mimics the exit code that a POSIX shell would report for
244 * a program that died from this signal.
246 code += 128;
247 } else if (WIFEXITED(status)) {
248 code = WEXITSTATUS(status);
250 * Convert special exit code when execvp failed.
252 if (code == 127) {
253 code = -1;
254 failed_errno = ENOENT;
256 } else {
257 error("waitpid is confused (%s)", argv0);
260 clear_child_for_cleanup(pid);
262 errno = failed_errno;
263 return code;
266 int start_command(struct child_process *cmd)
268 int need_in, need_out, need_err;
269 int fdin[2], fdout[2], fderr[2];
270 int failed_errno;
271 char *str;
273 if (!cmd->argv)
274 cmd->argv = cmd->args.argv;
275 if (!cmd->env)
276 cmd->env = cmd->env_array.argv;
279 * In case of errors we must keep the promise to close FDs
280 * that have been passed in via ->in and ->out.
283 need_in = !cmd->no_stdin && cmd->in < 0;
284 if (need_in) {
285 if (pipe(fdin) < 0) {
286 failed_errno = errno;
287 if (cmd->out > 0)
288 close(cmd->out);
289 str = "standard input";
290 goto fail_pipe;
292 cmd->in = fdin[1];
295 need_out = !cmd->no_stdout
296 && !cmd->stdout_to_stderr
297 && cmd->out < 0;
298 if (need_out) {
299 if (pipe(fdout) < 0) {
300 failed_errno = errno;
301 if (need_in)
302 close_pair(fdin);
303 else if (cmd->in)
304 close(cmd->in);
305 str = "standard output";
306 goto fail_pipe;
308 cmd->out = fdout[0];
311 need_err = !cmd->no_stderr && cmd->err < 0;
312 if (need_err) {
313 if (pipe(fderr) < 0) {
314 failed_errno = errno;
315 if (need_in)
316 close_pair(fdin);
317 else if (cmd->in)
318 close(cmd->in);
319 if (need_out)
320 close_pair(fdout);
321 else if (cmd->out)
322 close(cmd->out);
323 str = "standard error";
324 fail_pipe:
325 error("cannot create %s pipe for %s: %s",
326 str, cmd->argv[0], strerror(failed_errno));
327 argv_array_clear(&cmd->args);
328 argv_array_clear(&cmd->env_array);
329 errno = failed_errno;
330 return -1;
332 cmd->err = fderr[0];
335 trace_argv_printf(cmd->argv, "trace: run_command:");
336 fflush(NULL);
338 #ifndef GIT_WINDOWS_NATIVE
340 int notify_pipe[2];
341 if (pipe(notify_pipe))
342 notify_pipe[0] = notify_pipe[1] = -1;
344 cmd->pid = fork();
345 failed_errno = errno;
346 if (!cmd->pid) {
348 * Redirect the channel to write syscall error messages to
349 * before redirecting the process's stderr so that all die()
350 * in subsequent call paths use the parent's stderr.
352 if (cmd->no_stderr || need_err) {
353 int child_err = dup(2);
354 set_cloexec(child_err);
355 set_error_handle(fdopen(child_err, "w"));
358 close(notify_pipe[0]);
359 set_cloexec(notify_pipe[1]);
360 child_notifier = notify_pipe[1];
361 atexit(notify_parent);
363 if (cmd->no_stdin)
364 dup_devnull(0);
365 else if (need_in) {
366 dup2(fdin[0], 0);
367 close_pair(fdin);
368 } else if (cmd->in) {
369 dup2(cmd->in, 0);
370 close(cmd->in);
373 if (cmd->no_stderr)
374 dup_devnull(2);
375 else if (need_err) {
376 dup2(fderr[1], 2);
377 close_pair(fderr);
378 } else if (cmd->err > 1) {
379 dup2(cmd->err, 2);
380 close(cmd->err);
383 if (cmd->no_stdout)
384 dup_devnull(1);
385 else if (cmd->stdout_to_stderr)
386 dup2(2, 1);
387 else if (need_out) {
388 dup2(fdout[1], 1);
389 close_pair(fdout);
390 } else if (cmd->out > 1) {
391 dup2(cmd->out, 1);
392 close(cmd->out);
395 if (cmd->dir && chdir(cmd->dir))
396 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
397 cmd->dir);
398 if (cmd->env) {
399 for (; *cmd->env; cmd->env++) {
400 if (strchr(*cmd->env, '='))
401 putenv((char *)*cmd->env);
402 else
403 unsetenv(*cmd->env);
406 if (cmd->git_cmd)
407 execv_git_cmd(cmd->argv);
408 else if (cmd->use_shell)
409 execv_shell_cmd(cmd->argv);
410 else
411 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
412 if (errno == ENOENT) {
413 if (!cmd->silent_exec_failure)
414 error("cannot run %s: %s", cmd->argv[0],
415 strerror(ENOENT));
416 exit(127);
417 } else {
418 die_errno("cannot exec '%s'", cmd->argv[0]);
421 if (cmd->pid < 0)
422 error("cannot fork() for %s: %s", cmd->argv[0],
423 strerror(errno));
424 else if (cmd->clean_on_exit)
425 mark_child_for_cleanup(cmd->pid);
428 * Wait for child's execvp. If the execvp succeeds (or if fork()
429 * failed), EOF is seen immediately by the parent. Otherwise, the
430 * child process sends a single byte.
431 * Note that use of this infrastructure is completely advisory,
432 * therefore, we keep error checks minimal.
434 close(notify_pipe[1]);
435 if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
437 * At this point we know that fork() succeeded, but execvp()
438 * failed. Errors have been reported to our stderr.
440 wait_or_whine(cmd->pid, cmd->argv[0]);
441 failed_errno = errno;
442 cmd->pid = -1;
444 close(notify_pipe[0]);
446 #else
448 int fhin = 0, fhout = 1, fherr = 2;
449 const char **sargv = cmd->argv;
451 if (cmd->no_stdin)
452 fhin = open("/dev/null", O_RDWR);
453 else if (need_in)
454 fhin = dup(fdin[0]);
455 else if (cmd->in)
456 fhin = dup(cmd->in);
458 if (cmd->no_stderr)
459 fherr = open("/dev/null", O_RDWR);
460 else if (need_err)
461 fherr = dup(fderr[1]);
462 else if (cmd->err > 2)
463 fherr = dup(cmd->err);
465 if (cmd->no_stdout)
466 fhout = open("/dev/null", O_RDWR);
467 else if (cmd->stdout_to_stderr)
468 fhout = dup(fherr);
469 else if (need_out)
470 fhout = dup(fdout[1]);
471 else if (cmd->out > 1)
472 fhout = dup(cmd->out);
474 if (cmd->git_cmd)
475 cmd->argv = prepare_git_cmd(cmd->argv);
476 else if (cmd->use_shell)
477 cmd->argv = prepare_shell_cmd(cmd->argv);
479 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
480 cmd->dir, fhin, fhout, fherr);
481 failed_errno = errno;
482 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
483 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
484 if (cmd->clean_on_exit && cmd->pid >= 0)
485 mark_child_for_cleanup(cmd->pid);
487 if (cmd->git_cmd)
488 free(cmd->argv);
490 cmd->argv = sargv;
491 if (fhin != 0)
492 close(fhin);
493 if (fhout != 1)
494 close(fhout);
495 if (fherr != 2)
496 close(fherr);
498 #endif
500 if (cmd->pid < 0) {
501 if (need_in)
502 close_pair(fdin);
503 else if (cmd->in)
504 close(cmd->in);
505 if (need_out)
506 close_pair(fdout);
507 else if (cmd->out)
508 close(cmd->out);
509 if (need_err)
510 close_pair(fderr);
511 else if (cmd->err)
512 close(cmd->err);
513 argv_array_clear(&cmd->args);
514 argv_array_clear(&cmd->env_array);
515 errno = failed_errno;
516 return -1;
519 if (need_in)
520 close(fdin[0]);
521 else if (cmd->in)
522 close(cmd->in);
524 if (need_out)
525 close(fdout[1]);
526 else if (cmd->out)
527 close(cmd->out);
529 if (need_err)
530 close(fderr[1]);
531 else if (cmd->err)
532 close(cmd->err);
534 return 0;
537 int finish_command(struct child_process *cmd)
539 int ret = wait_or_whine(cmd->pid, cmd->argv[0]);
540 argv_array_clear(&cmd->args);
541 argv_array_clear(&cmd->env_array);
542 return ret;
545 int run_command(struct child_process *cmd)
547 int code;
549 if (cmd->out < 0 || cmd->err < 0)
550 die("BUG: run_command with a pipe can cause deadlock");
552 code = start_command(cmd);
553 if (code)
554 return code;
555 return finish_command(cmd);
558 int run_command_v_opt(const char **argv, int opt)
560 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
563 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
565 struct child_process cmd = CHILD_PROCESS_INIT;
566 cmd.argv = argv;
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;
573 cmd.dir = dir;
574 cmd.env = env;
575 return run_command(&cmd);
578 #ifndef NO_PTHREADS
579 static pthread_t main_thread;
580 static int main_thread_set;
581 static pthread_key_t async_key;
582 static pthread_key_t async_die_counter;
584 static void *run_thread(void *data)
586 struct async *async = data;
587 intptr_t ret;
589 pthread_setspecific(async_key, async);
590 ret = async->proc(async->proc_in, async->proc_out, async->data);
591 return (void *)ret;
594 static NORETURN void die_async(const char *err, va_list params)
596 vreportf("fatal: ", err, params);
598 if (in_async()) {
599 struct async *async = pthread_getspecific(async_key);
600 if (async->proc_in >= 0)
601 close(async->proc_in);
602 if (async->proc_out >= 0)
603 close(async->proc_out);
604 pthread_exit((void *)128);
607 exit(128);
610 static int async_die_is_recursing(void)
612 void *ret = pthread_getspecific(async_die_counter);
613 pthread_setspecific(async_die_counter, (void *)1);
614 return ret != NULL;
617 int in_async(void)
619 if (!main_thread_set)
620 return 0; /* no asyncs started yet */
621 return !pthread_equal(main_thread, pthread_self());
624 #else
626 static struct {
627 void (**handlers)(void);
628 size_t nr;
629 size_t alloc;
630 } git_atexit_hdlrs;
632 static int git_atexit_installed;
634 static void git_atexit_dispatch(void)
636 size_t i;
638 for (i=git_atexit_hdlrs.nr ; i ; i--)
639 git_atexit_hdlrs.handlers[i-1]();
642 static void git_atexit_clear(void)
644 free(git_atexit_hdlrs.handlers);
645 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
646 git_atexit_installed = 0;
649 #undef atexit
650 int git_atexit(void (*handler)(void))
652 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
653 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
654 if (!git_atexit_installed) {
655 if (atexit(&git_atexit_dispatch))
656 return -1;
657 git_atexit_installed = 1;
659 return 0;
661 #define atexit git_atexit
663 static int process_is_async;
664 int in_async(void)
666 return process_is_async;
669 #endif
671 int start_async(struct async *async)
673 int need_in, need_out;
674 int fdin[2], fdout[2];
675 int proc_in, proc_out;
677 need_in = async->in < 0;
678 if (need_in) {
679 if (pipe(fdin) < 0) {
680 if (async->out > 0)
681 close(async->out);
682 return error("cannot create pipe: %s", strerror(errno));
684 async->in = fdin[1];
687 need_out = async->out < 0;
688 if (need_out) {
689 if (pipe(fdout) < 0) {
690 if (need_in)
691 close_pair(fdin);
692 else if (async->in)
693 close(async->in);
694 return error("cannot create pipe: %s", strerror(errno));
696 async->out = fdout[0];
699 if (need_in)
700 proc_in = fdin[0];
701 else if (async->in)
702 proc_in = async->in;
703 else
704 proc_in = -1;
706 if (need_out)
707 proc_out = fdout[1];
708 else if (async->out)
709 proc_out = async->out;
710 else
711 proc_out = -1;
713 #ifdef NO_PTHREADS
714 /* Flush stdio before fork() to avoid cloning buffers */
715 fflush(NULL);
717 async->pid = fork();
718 if (async->pid < 0) {
719 error("fork (async) failed: %s", strerror(errno));
720 goto error;
722 if (!async->pid) {
723 if (need_in)
724 close(fdin[1]);
725 if (need_out)
726 close(fdout[0]);
727 git_atexit_clear();
728 process_is_async = 1;
729 exit(!!async->proc(proc_in, proc_out, async->data));
732 mark_child_for_cleanup(async->pid);
734 if (need_in)
735 close(fdin[0]);
736 else if (async->in)
737 close(async->in);
739 if (need_out)
740 close(fdout[1]);
741 else if (async->out)
742 close(async->out);
743 #else
744 if (!main_thread_set) {
746 * We assume that the first time that start_async is called
747 * it is from the main thread.
749 main_thread_set = 1;
750 main_thread = pthread_self();
751 pthread_key_create(&async_key, NULL);
752 pthread_key_create(&async_die_counter, NULL);
753 set_die_routine(die_async);
754 set_die_is_recursing_routine(async_die_is_recursing);
757 if (proc_in >= 0)
758 set_cloexec(proc_in);
759 if (proc_out >= 0)
760 set_cloexec(proc_out);
761 async->proc_in = proc_in;
762 async->proc_out = proc_out;
764 int err = pthread_create(&async->tid, NULL, run_thread, async);
765 if (err) {
766 error("cannot create thread: %s", strerror(err));
767 goto error;
770 #endif
771 return 0;
773 error:
774 if (need_in)
775 close_pair(fdin);
776 else if (async->in)
777 close(async->in);
779 if (need_out)
780 close_pair(fdout);
781 else if (async->out)
782 close(async->out);
783 return -1;
786 int finish_async(struct async *async)
788 #ifdef NO_PTHREADS
789 return wait_or_whine(async->pid, "child process");
790 #else
791 void *ret = (void *)(intptr_t)(-1);
793 if (pthread_join(async->tid, &ret))
794 error("pthread_join failed");
795 return (int)(intptr_t)ret;
796 #endif
799 const char *find_hook(const char *name)
801 static struct strbuf path = STRBUF_INIT;
803 strbuf_reset(&path);
804 strbuf_git_path(&path, "hooks/%s", name);
805 if (access(path.buf, X_OK) < 0)
806 return NULL;
807 return path.buf;
810 int run_hook_ve(const char *const *env, const char *name, va_list args)
812 struct child_process hook = CHILD_PROCESS_INIT;
813 const char *p;
815 p = find_hook(name);
816 if (!p)
817 return 0;
819 argv_array_push(&hook.args, p);
820 while ((p = va_arg(args, const char *)))
821 argv_array_push(&hook.args, p);
822 hook.env = env;
823 hook.no_stdin = 1;
824 hook.stdout_to_stderr = 1;
826 return run_command(&hook);
829 int run_hook_le(const char *const *env, const char *name, ...)
831 va_list args;
832 int ret;
834 va_start(args, name);
835 ret = run_hook_ve(env, name, args);
836 va_end(args);
838 return ret;
841 int capture_command(struct child_process *cmd, struct strbuf *buf, size_t hint)
843 cmd->out = -1;
844 if (start_command(cmd) < 0)
845 return -1;
847 if (strbuf_read(buf, cmd->out, hint) < 0) {
848 close(cmd->out);
849 finish_command(cmd); /* throw away exit code */
850 return -1;
853 close(cmd->out);
854 return finish_command(cmd);