Merge branch 'jc/push-upstream-sanity'
[git/jnareb-git.git] / run-command.c
blob2af3e0fa520bcd87d241ed7a3601b14232ad94d5
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 const char **prepare_shell_cmd(const char **argv)
85 int argc, nargc = 0;
86 const char **nargv;
88 for (argc = 0; argv[argc]; argc++)
89 ; /* just counting */
90 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
91 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
93 if (argc < 1)
94 die("BUG: shell command is empty");
96 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
97 nargv[nargc++] = SHELL_PATH;
98 nargv[nargc++] = "-c";
100 if (argc < 2)
101 nargv[nargc++] = argv[0];
102 else {
103 struct strbuf arg0 = STRBUF_INIT;
104 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
105 nargv[nargc++] = strbuf_detach(&arg0, NULL);
109 for (argc = 0; argv[argc]; argc++)
110 nargv[nargc++] = argv[argc];
111 nargv[nargc] = NULL;
113 return nargv;
116 #ifndef WIN32
117 static int execv_shell_cmd(const char **argv)
119 const char **nargv = prepare_shell_cmd(argv);
120 trace_argv_printf(nargv, "trace: exec:");
121 execvp(nargv[0], (char **)nargv);
122 free(nargv);
123 return -1;
125 #endif
127 #ifndef WIN32
128 static int child_err = 2;
129 static int child_notifier = -1;
131 static void notify_parent(void)
134 * execvp failed. If possible, we'd like to let start_command
135 * know, so failures like ENOENT can be handled right away; but
136 * otherwise, finish_command will still report the error.
138 xwrite(child_notifier, "", 1);
141 static NORETURN void die_child(const char *err, va_list params)
143 vwritef(child_err, "fatal: ", err, params);
144 exit(128);
147 static void error_child(const char *err, va_list params)
149 vwritef(child_err, "error: ", err, params);
151 #endif
153 static inline void set_cloexec(int fd)
155 int flags = fcntl(fd, F_GETFD);
156 if (flags >= 0)
157 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
160 static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
162 int status, code = -1;
163 pid_t waiting;
164 int failed_errno = 0;
166 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
167 ; /* nothing */
169 if (waiting < 0) {
170 failed_errno = errno;
171 error("waitpid for %s failed: %s", argv0, strerror(errno));
172 } else if (waiting != pid) {
173 error("waitpid is confused (%s)", argv0);
174 } else if (WIFSIGNALED(status)) {
175 code = WTERMSIG(status);
176 error("%s died of signal %d", argv0, code);
178 * This return value is chosen so that code & 0xff
179 * mimics the exit code that a POSIX shell would report for
180 * a program that died from this signal.
182 code -= 128;
183 } else if (WIFEXITED(status)) {
184 code = WEXITSTATUS(status);
186 * Convert special exit code when execvp failed.
188 if (code == 127) {
189 code = -1;
190 failed_errno = ENOENT;
192 } else {
193 error("waitpid is confused (%s)", argv0);
196 clear_child_for_cleanup(pid);
198 errno = failed_errno;
199 return code;
202 int start_command(struct child_process *cmd)
204 int need_in, need_out, need_err;
205 int fdin[2], fdout[2], fderr[2];
206 int failed_errno = failed_errno;
209 * In case of errors we must keep the promise to close FDs
210 * that have been passed in via ->in and ->out.
213 need_in = !cmd->no_stdin && cmd->in < 0;
214 if (need_in) {
215 if (pipe(fdin) < 0) {
216 failed_errno = errno;
217 if (cmd->out > 0)
218 close(cmd->out);
219 goto fail_pipe;
221 cmd->in = fdin[1];
224 need_out = !cmd->no_stdout
225 && !cmd->stdout_to_stderr
226 && cmd->out < 0;
227 if (need_out) {
228 if (pipe(fdout) < 0) {
229 failed_errno = errno;
230 if (need_in)
231 close_pair(fdin);
232 else if (cmd->in)
233 close(cmd->in);
234 goto fail_pipe;
236 cmd->out = fdout[0];
239 need_err = !cmd->no_stderr && cmd->err < 0;
240 if (need_err) {
241 if (pipe(fderr) < 0) {
242 failed_errno = errno;
243 if (need_in)
244 close_pair(fdin);
245 else if (cmd->in)
246 close(cmd->in);
247 if (need_out)
248 close_pair(fdout);
249 else if (cmd->out)
250 close(cmd->out);
251 fail_pipe:
252 error("cannot create pipe for %s: %s",
253 cmd->argv[0], strerror(failed_errno));
254 errno = failed_errno;
255 return -1;
257 cmd->err = fderr[0];
260 trace_argv_printf(cmd->argv, "trace: run_command:");
261 fflush(NULL);
263 #ifndef WIN32
265 int notify_pipe[2];
266 if (pipe(notify_pipe))
267 notify_pipe[0] = notify_pipe[1] = -1;
269 cmd->pid = fork();
270 if (!cmd->pid) {
272 * Redirect the channel to write syscall error messages to
273 * before redirecting the process's stderr so that all die()
274 * in subsequent call paths use the parent's stderr.
276 if (cmd->no_stderr || need_err) {
277 child_err = dup(2);
278 set_cloexec(child_err);
280 set_die_routine(die_child);
281 set_error_routine(error_child);
283 close(notify_pipe[0]);
284 set_cloexec(notify_pipe[1]);
285 child_notifier = notify_pipe[1];
286 atexit(notify_parent);
288 if (cmd->no_stdin)
289 dup_devnull(0);
290 else if (need_in) {
291 dup2(fdin[0], 0);
292 close_pair(fdin);
293 } else if (cmd->in) {
294 dup2(cmd->in, 0);
295 close(cmd->in);
298 if (cmd->no_stderr)
299 dup_devnull(2);
300 else if (need_err) {
301 dup2(fderr[1], 2);
302 close_pair(fderr);
303 } else if (cmd->err > 1) {
304 dup2(cmd->err, 2);
305 close(cmd->err);
308 if (cmd->no_stdout)
309 dup_devnull(1);
310 else if (cmd->stdout_to_stderr)
311 dup2(2, 1);
312 else if (need_out) {
313 dup2(fdout[1], 1);
314 close_pair(fdout);
315 } else if (cmd->out > 1) {
316 dup2(cmd->out, 1);
317 close(cmd->out);
320 if (cmd->dir && chdir(cmd->dir))
321 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
322 cmd->dir);
323 if (cmd->env) {
324 for (; *cmd->env; cmd->env++) {
325 if (strchr(*cmd->env, '='))
326 putenv((char *)*cmd->env);
327 else
328 unsetenv(*cmd->env);
331 if (cmd->preexec_cb) {
333 * We cannot predict what the pre-exec callback does.
334 * Forgo parent notification.
336 close(child_notifier);
337 child_notifier = -1;
339 cmd->preexec_cb();
341 if (cmd->git_cmd) {
342 execv_git_cmd(cmd->argv);
343 } else if (cmd->use_shell) {
344 execv_shell_cmd(cmd->argv);
345 } else {
346 execvp(cmd->argv[0], (char *const*) cmd->argv);
348 if (errno == ENOENT) {
349 if (!cmd->silent_exec_failure)
350 error("cannot run %s: %s", cmd->argv[0],
351 strerror(ENOENT));
352 exit(127);
353 } else {
354 die_errno("cannot exec '%s'", cmd->argv[0]);
357 if (cmd->pid < 0)
358 error("cannot fork() for %s: %s", cmd->argv[0],
359 strerror(failed_errno = errno));
360 else if (cmd->clean_on_exit)
361 mark_child_for_cleanup(cmd->pid);
364 * Wait for child's execvp. If the execvp succeeds (or if fork()
365 * failed), EOF is seen immediately by the parent. Otherwise, the
366 * child process sends a single byte.
367 * Note that use of this infrastructure is completely advisory,
368 * therefore, we keep error checks minimal.
370 close(notify_pipe[1]);
371 if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
373 * At this point we know that fork() succeeded, but execvp()
374 * failed. Errors have been reported to our stderr.
376 wait_or_whine(cmd->pid, cmd->argv[0],
377 cmd->silent_exec_failure);
378 failed_errno = errno;
379 cmd->pid = -1;
381 close(notify_pipe[0]);
384 #else
386 int fhin = 0, fhout = 1, fherr = 2;
387 const char **sargv = cmd->argv;
388 char **env = environ;
390 if (cmd->no_stdin)
391 fhin = open("/dev/null", O_RDWR);
392 else if (need_in)
393 fhin = dup(fdin[0]);
394 else if (cmd->in)
395 fhin = dup(cmd->in);
397 if (cmd->no_stderr)
398 fherr = open("/dev/null", O_RDWR);
399 else if (need_err)
400 fherr = dup(fderr[1]);
401 else if (cmd->err > 2)
402 fherr = dup(cmd->err);
404 if (cmd->no_stdout)
405 fhout = open("/dev/null", O_RDWR);
406 else if (cmd->stdout_to_stderr)
407 fhout = dup(fherr);
408 else if (need_out)
409 fhout = dup(fdout[1]);
410 else if (cmd->out > 1)
411 fhout = dup(cmd->out);
413 if (cmd->env)
414 env = make_augmented_environ(cmd->env);
416 if (cmd->git_cmd) {
417 cmd->argv = prepare_git_cmd(cmd->argv);
418 } else if (cmd->use_shell) {
419 cmd->argv = prepare_shell_cmd(cmd->argv);
422 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
423 fhin, fhout, fherr);
424 failed_errno = errno;
425 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
426 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
427 if (cmd->clean_on_exit && cmd->pid >= 0)
428 mark_child_for_cleanup(cmd->pid);
430 if (cmd->env)
431 free_environ(env);
432 if (cmd->git_cmd)
433 free(cmd->argv);
435 cmd->argv = sargv;
436 if (fhin != 0)
437 close(fhin);
438 if (fhout != 1)
439 close(fhout);
440 if (fherr != 2)
441 close(fherr);
443 #endif
445 if (cmd->pid < 0) {
446 if (need_in)
447 close_pair(fdin);
448 else if (cmd->in)
449 close(cmd->in);
450 if (need_out)
451 close_pair(fdout);
452 else if (cmd->out)
453 close(cmd->out);
454 if (need_err)
455 close_pair(fderr);
456 else if (cmd->err)
457 close(cmd->err);
458 errno = failed_errno;
459 return -1;
462 if (need_in)
463 close(fdin[0]);
464 else if (cmd->in)
465 close(cmd->in);
467 if (need_out)
468 close(fdout[1]);
469 else if (cmd->out)
470 close(cmd->out);
472 if (need_err)
473 close(fderr[1]);
474 else if (cmd->err)
475 close(cmd->err);
477 return 0;
480 int finish_command(struct child_process *cmd)
482 return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
485 int run_command(struct child_process *cmd)
487 int code = start_command(cmd);
488 if (code)
489 return code;
490 return finish_command(cmd);
493 static void prepare_run_command_v_opt(struct child_process *cmd,
494 const char **argv,
495 int opt)
497 memset(cmd, 0, sizeof(*cmd));
498 cmd->argv = argv;
499 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
500 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
501 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
502 cmd->silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
503 cmd->use_shell = opt & RUN_USING_SHELL ? 1 : 0;
504 cmd->clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
507 int run_command_v_opt(const char **argv, int opt)
509 struct child_process cmd;
510 prepare_run_command_v_opt(&cmd, argv, opt);
511 return run_command(&cmd);
514 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
516 struct child_process cmd;
517 prepare_run_command_v_opt(&cmd, argv, opt);
518 cmd.dir = dir;
519 cmd.env = env;
520 return run_command(&cmd);
523 #ifndef NO_PTHREADS
524 static pthread_t main_thread;
525 static int main_thread_set;
526 static pthread_key_t async_key;
528 static void *run_thread(void *data)
530 struct async *async = data;
531 intptr_t ret;
533 pthread_setspecific(async_key, async);
534 ret = async->proc(async->proc_in, async->proc_out, async->data);
535 return (void *)ret;
538 static NORETURN void die_async(const char *err, va_list params)
540 vreportf("fatal: ", err, params);
542 if (!pthread_equal(main_thread, pthread_self())) {
543 struct async *async = pthread_getspecific(async_key);
544 if (async->proc_in >= 0)
545 close(async->proc_in);
546 if (async->proc_out >= 0)
547 close(async->proc_out);
548 pthread_exit((void *)128);
551 exit(128);
553 #endif
555 int start_async(struct async *async)
557 int need_in, need_out;
558 int fdin[2], fdout[2];
559 int proc_in, proc_out;
561 need_in = async->in < 0;
562 if (need_in) {
563 if (pipe(fdin) < 0) {
564 if (async->out > 0)
565 close(async->out);
566 return error("cannot create pipe: %s", strerror(errno));
568 async->in = fdin[1];
571 need_out = async->out < 0;
572 if (need_out) {
573 if (pipe(fdout) < 0) {
574 if (need_in)
575 close_pair(fdin);
576 else if (async->in)
577 close(async->in);
578 return error("cannot create pipe: %s", strerror(errno));
580 async->out = fdout[0];
583 if (need_in)
584 proc_in = fdin[0];
585 else if (async->in)
586 proc_in = async->in;
587 else
588 proc_in = -1;
590 if (need_out)
591 proc_out = fdout[1];
592 else if (async->out)
593 proc_out = async->out;
594 else
595 proc_out = -1;
597 #ifdef NO_PTHREADS
598 /* Flush stdio before fork() to avoid cloning buffers */
599 fflush(NULL);
601 async->pid = fork();
602 if (async->pid < 0) {
603 error("fork (async) failed: %s", strerror(errno));
604 goto error;
606 if (!async->pid) {
607 if (need_in)
608 close(fdin[1]);
609 if (need_out)
610 close(fdout[0]);
611 exit(!!async->proc(proc_in, proc_out, async->data));
614 mark_child_for_cleanup(async->pid);
616 if (need_in)
617 close(fdin[0]);
618 else if (async->in)
619 close(async->in);
621 if (need_out)
622 close(fdout[1]);
623 else if (async->out)
624 close(async->out);
625 #else
626 if (!main_thread_set) {
628 * We assume that the first time that start_async is called
629 * it is from the main thread.
631 main_thread_set = 1;
632 main_thread = pthread_self();
633 pthread_key_create(&async_key, NULL);
634 set_die_routine(die_async);
637 if (proc_in >= 0)
638 set_cloexec(proc_in);
639 if (proc_out >= 0)
640 set_cloexec(proc_out);
641 async->proc_in = proc_in;
642 async->proc_out = proc_out;
644 int err = pthread_create(&async->tid, NULL, run_thread, async);
645 if (err) {
646 error("cannot create thread: %s", strerror(err));
647 goto error;
650 #endif
651 return 0;
653 error:
654 if (need_in)
655 close_pair(fdin);
656 else if (async->in)
657 close(async->in);
659 if (need_out)
660 close_pair(fdout);
661 else if (async->out)
662 close(async->out);
663 return -1;
666 int finish_async(struct async *async)
668 #ifdef NO_PTHREADS
669 return wait_or_whine(async->pid, "child process", 0);
670 #else
671 void *ret = (void *)(intptr_t)(-1);
673 if (pthread_join(async->tid, &ret))
674 error("pthread_join failed");
675 return (int)(intptr_t)ret;
676 #endif
679 int run_hook(const char *index_file, const char *name, ...)
681 struct child_process hook;
682 struct argv_array argv = ARGV_ARRAY_INIT;
683 const char *p, *env[2];
684 char index[PATH_MAX];
685 va_list args;
686 int ret;
688 if (access(git_path("hooks/%s", name), X_OK) < 0)
689 return 0;
691 va_start(args, name);
692 argv_array_push(&argv, git_path("hooks/%s", name));
693 while ((p = va_arg(args, const char *)))
694 argv_array_push(&argv, p);
695 va_end(args);
697 memset(&hook, 0, sizeof(hook));
698 hook.argv = argv.argv;
699 hook.no_stdin = 1;
700 hook.stdout_to_stderr = 1;
701 if (index_file) {
702 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
703 env[0] = index;
704 env[1] = NULL;
705 hook.env = env;
708 ret = run_command(&hook);
709 argv_array_clear(&argv);
710 return ret;