Merge branch 'nd/i18n-parseopt-help'
[git/mingw.git] / run-command.c
blobf9922b9ecc8e4956e19d7143bb6cb6ef4d97abf8
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec_cmd.h"
4 #include "sigchain.h"
5 #include "argv-array.h"
7 #ifndef SHELL_PATH
8 # define SHELL_PATH "/bin/sh"
9 #endif
11 struct child_to_clean {
12 pid_t pid;
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;
23 kill(p->pid, sig);
24 free(p);
28 static void cleanup_children_on_signal(int sig)
30 cleanup_children(sig);
31 sigchain_pop(sig);
32 raise(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));
43 p->pid = pid;
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) {
60 if (p->pid == pid) {
61 *last = p->next;
62 free(p);
63 return;
68 static inline void close_pair(int fd[2])
70 close(fd[0]);
71 close(fd[1]);
74 #ifndef WIN32
75 static inline void dup_devnull(int to)
77 int fd = open("/dev/null", O_RDWR);
78 dup2(fd, to);
79 close(fd);
81 #endif
83 static char *locate_in_PATH(const char *file)
85 const char *p = getenv("PATH");
86 struct strbuf buf = STRBUF_INIT;
88 if (!p || !*p)
89 return NULL;
91 while (1) {
92 const char *end = strchrnul(p, ':');
94 strbuf_reset(&buf);
96 /* POSIX specifies an empty entry as the current directory. */
97 if (end != p) {
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);
106 if (!*end)
107 break;
108 p = end + 1;
111 strbuf_release(&buf);
112 return NULL;
115 static int exists_in_PATH(const char *file)
117 char *r = locate_in_PATH(file);
118 free(r);
119 return r != NULL;
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
132 * intuitive.
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, '/'))
143 errno = ENOENT;
144 return -1;
147 static const char **prepare_shell_cmd(const char **argv)
149 int argc, nargc = 0;
150 const char **nargv;
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));
157 if (argc < 1)
158 die("BUG: shell command is empty");
160 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
161 #ifndef WIN32
162 nargv[nargc++] = SHELL_PATH;
163 #else
164 nargv[nargc++] = "sh";
165 #endif
166 nargv[nargc++] = "-c";
168 if (argc < 2)
169 nargv[nargc++] = argv[0];
170 else {
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];
179 nargv[nargc] = NULL;
181 return nargv;
184 #ifndef WIN32
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);
190 free(nargv);
191 return -1;
193 #endif
195 #ifndef WIN32
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);
212 exit(128);
215 static void error_child(const char *err, va_list params)
217 vwritef(child_err, "error: ", err, params);
219 #endif
221 static inline void set_cloexec(int fd)
223 int flags = fcntl(fd, F_GETFD);
224 if (flags >= 0)
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;
231 pid_t waiting;
232 int failed_errno = 0;
234 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
235 ; /* nothing */
237 if (waiting < 0) {
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.
250 code -= 128;
251 } else if (WIFEXITED(status)) {
252 code = WEXITSTATUS(status);
254 * Convert special exit code when execvp failed.
256 if (code == 127) {
257 code = -1;
258 failed_errno = ENOENT;
260 } else {
261 error("waitpid is confused (%s)", argv0);
264 clear_child_for_cleanup(pid);
266 errno = failed_errno;
267 return code;
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;
282 if (need_in) {
283 if (pipe(fdin) < 0) {
284 failed_errno = errno;
285 if (cmd->out > 0)
286 close(cmd->out);
287 goto fail_pipe;
289 cmd->in = fdin[1];
292 need_out = !cmd->no_stdout
293 && !cmd->stdout_to_stderr
294 && cmd->out < 0;
295 if (need_out) {
296 if (pipe(fdout) < 0) {
297 failed_errno = errno;
298 if (need_in)
299 close_pair(fdin);
300 else if (cmd->in)
301 close(cmd->in);
302 goto fail_pipe;
304 cmd->out = fdout[0];
307 need_err = !cmd->no_stderr && cmd->err < 0;
308 if (need_err) {
309 if (pipe(fderr) < 0) {
310 failed_errno = errno;
311 if (need_in)
312 close_pair(fdin);
313 else if (cmd->in)
314 close(cmd->in);
315 if (need_out)
316 close_pair(fdout);
317 else if (cmd->out)
318 close(cmd->out);
319 fail_pipe:
320 error("cannot create pipe for %s: %s",
321 cmd->argv[0], strerror(failed_errno));
322 errno = failed_errno;
323 return -1;
325 cmd->err = fderr[0];
328 trace_argv_printf(cmd->argv, "trace: run_command:");
329 fflush(NULL);
331 #ifndef WIN32
333 int notify_pipe[2];
334 if (pipe(notify_pipe))
335 notify_pipe[0] = notify_pipe[1] = -1;
337 cmd->pid = fork();
338 if (!cmd->pid) {
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) {
345 child_err = dup(2);
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);
356 if (cmd->no_stdin)
357 dup_devnull(0);
358 else if (need_in) {
359 dup2(fdin[0], 0);
360 close_pair(fdin);
361 } else if (cmd->in) {
362 dup2(cmd->in, 0);
363 close(cmd->in);
366 if (cmd->no_stderr)
367 dup_devnull(2);
368 else if (need_err) {
369 dup2(fderr[1], 2);
370 close_pair(fderr);
371 } else if (cmd->err > 1) {
372 dup2(cmd->err, 2);
373 close(cmd->err);
376 if (cmd->no_stdout)
377 dup_devnull(1);
378 else if (cmd->stdout_to_stderr)
379 dup2(2, 1);
380 else if (need_out) {
381 dup2(fdout[1], 1);
382 close_pair(fdout);
383 } else if (cmd->out > 1) {
384 dup2(cmd->out, 1);
385 close(cmd->out);
388 if (cmd->dir && chdir(cmd->dir))
389 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
390 cmd->dir);
391 if (cmd->env) {
392 for (; *cmd->env; cmd->env++) {
393 if (strchr(*cmd->env, '='))
394 putenv((char *)*cmd->env);
395 else
396 unsetenv(*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);
405 child_notifier = -1;
407 cmd->preexec_cb();
409 if (cmd->git_cmd) {
410 execv_git_cmd(cmd->argv);
411 } else if (cmd->use_shell) {
412 execv_shell_cmd(cmd->argv);
413 } else {
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],
419 strerror(ENOENT));
420 exit(127);
421 } else {
422 die_errno("cannot exec '%s'", cmd->argv[0]);
425 if (cmd->pid < 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], &notify_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;
447 cmd->pid = -1;
449 close(notify_pipe[0]);
452 #else
454 int fhin = 0, fhout = 1, fherr = 2;
455 const char **sargv = cmd->argv;
456 char **env = environ;
458 if (cmd->no_stdin)
459 fhin = open("/dev/null", O_RDWR);
460 else if (need_in)
461 fhin = dup(fdin[0]);
462 else if (cmd->in)
463 fhin = dup(cmd->in);
465 if (cmd->no_stderr)
466 fherr = open("/dev/null", O_RDWR);
467 else if (need_err)
468 fherr = dup(fderr[1]);
469 else if (cmd->err > 2)
470 fherr = dup(cmd->err);
472 if (cmd->no_stdout)
473 fhout = open("/dev/null", O_RDWR);
474 else if (cmd->stdout_to_stderr)
475 fhout = dup(fherr);
476 else if (need_out)
477 fhout = dup(fdout[1]);
478 else if (cmd->out > 1)
479 fhout = dup(cmd->out);
481 if (cmd->env)
482 env = make_augmented_environ(cmd->env);
484 if (cmd->git_cmd) {
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,
491 fhin, fhout, fherr);
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);
498 if (cmd->env)
499 free_environ(env);
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 errno = failed_errno;
527 return -1;
530 if (need_in)
531 close(fdin[0]);
532 else if (cmd->in)
533 close(cmd->in);
535 if (need_out)
536 close(fdout[1]);
537 else if (cmd->out)
538 close(cmd->out);
540 if (need_err)
541 close(fderr[1]);
542 else if (cmd->err)
543 close(cmd->err);
545 return 0;
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);
556 if (code)
557 return code;
558 return finish_command(cmd);
561 static void prepare_run_command_v_opt(struct child_process *cmd,
562 const char **argv,
563 int opt)
565 memset(cmd, 0, sizeof(*cmd));
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;
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);
586 cmd.dir = dir;
587 cmd.env = env;
588 return run_command(&cmd);
591 #ifndef NO_PTHREADS
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;
599 intptr_t ret;
601 pthread_setspecific(async_key, async);
602 ret = async->proc(async->proc_in, async->proc_out, async->data);
603 return (void *)ret;
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);
619 exit(128);
621 #endif
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;
630 if (need_in) {
631 if (pipe(fdin) < 0) {
632 if (async->out > 0)
633 close(async->out);
634 return error("cannot create pipe: %s", strerror(errno));
636 async->in = fdin[1];
639 need_out = async->out < 0;
640 if (need_out) {
641 if (pipe(fdout) < 0) {
642 if (need_in)
643 close_pair(fdin);
644 else if (async->in)
645 close(async->in);
646 return error("cannot create pipe: %s", strerror(errno));
648 async->out = fdout[0];
651 if (need_in)
652 proc_in = fdin[0];
653 else if (async->in)
654 proc_in = async->in;
655 else
656 proc_in = -1;
658 if (need_out)
659 proc_out = fdout[1];
660 else if (async->out)
661 proc_out = async->out;
662 else
663 proc_out = -1;
665 #ifdef NO_PTHREADS
666 /* Flush stdio before fork() to avoid cloning buffers */
667 fflush(NULL);
669 async->pid = fork();
670 if (async->pid < 0) {
671 error("fork (async) failed: %s", strerror(errno));
672 goto error;
674 if (!async->pid) {
675 if (need_in)
676 close(fdin[1]);
677 if (need_out)
678 close(fdout[0]);
679 exit(!!async->proc(proc_in, proc_out, async->data));
682 mark_child_for_cleanup(async->pid);
684 if (need_in)
685 close(fdin[0]);
686 else if (async->in)
687 close(async->in);
689 if (need_out)
690 close(fdout[1]);
691 else if (async->out)
692 close(async->out);
693 #else
694 if (!main_thread_set) {
696 * We assume that the first time that start_async is called
697 * it is from the main thread.
699 main_thread_set = 1;
700 main_thread = pthread_self();
701 pthread_key_create(&async_key, NULL);
702 set_die_routine(die_async);
705 if (proc_in >= 0)
706 set_cloexec(proc_in);
707 if (proc_out >= 0)
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);
713 if (err) {
714 error("cannot create thread: %s", strerror(err));
715 goto error;
718 #endif
719 return 0;
721 error:
722 if (need_in)
723 close_pair(fdin);
724 else if (async->in)
725 close(async->in);
727 if (need_out)
728 close_pair(fdout);
729 else if (async->out)
730 close(async->out);
731 return -1;
734 int finish_async(struct async *async)
736 #ifdef NO_PTHREADS
737 return wait_or_whine(async->pid, "child process", 0);
738 #else
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;
744 #endif
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];
753 va_list args;
754 int ret;
756 if (access(git_path("hooks/%s", name), X_OK) < 0)
757 return 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);
763 va_end(args);
765 memset(&hook, 0, sizeof(hook));
766 hook.argv = argv.argv;
767 hook.no_stdin = 1;
768 hook.stdout_to_stderr = 1;
769 if (index_file) {
770 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
771 env[0] = index;
772 env[1] = NULL;
773 hook.env = env;
776 ret = run_command(&hook);
777 argv_array_clear(&argv);
778 return ret;