run-command: forbid using run_command with piped output
[git/git.git] / run-command.c
CommitLineData
b1bf95bb
JW
1#include "cache.h"
2#include "run-command.h"
77cb17e9 3#include "exec_cmd.h"
afe19ff7 4#include "sigchain.h"
5d40a179 5#include "argv-array.h"
b1bf95bb 6
b3e34ddd
BW
7#ifndef SHELL_PATH
8# define SHELL_PATH "/bin/sh"
9#endif
10
483bbd4e
RS
11void child_process_init(struct child_process *child)
12{
13 memset(child, 0, sizeof(*child));
14 argv_array_init(&child->args);
19a583dc 15 argv_array_init(&child->env_array);
483bbd4e
RS
16}
17
afe19ff7
JK
18struct child_to_clean {
19 pid_t pid;
20 struct child_to_clean *next;
21};
22static struct child_to_clean *children_to_clean;
23static int installed_child_cleanup_handler;
24
25static void cleanup_children(int sig)
26{
27 while (children_to_clean) {
28 struct child_to_clean *p = children_to_clean;
29 children_to_clean = p->next;
30 kill(p->pid, sig);
31 free(p);
32 }
33}
34
35static void cleanup_children_on_signal(int sig)
36{
37 cleanup_children(sig);
38 sigchain_pop(sig);
39 raise(sig);
40}
41
42static void cleanup_children_on_exit(void)
43{
44 cleanup_children(SIGTERM);
45}
46
47static void mark_child_for_cleanup(pid_t pid)
48{
49 struct child_to_clean *p = xmalloc(sizeof(*p));
50 p->pid = pid;
51 p->next = children_to_clean;
52 children_to_clean = p;
53
54 if (!installed_child_cleanup_handler) {
55 atexit(cleanup_children_on_exit);
56 sigchain_push_common(cleanup_children_on_signal);
57 installed_child_cleanup_handler = 1;
58 }
59}
60
61static void clear_child_for_cleanup(pid_t pid)
62{
bdee397d 63 struct child_to_clean **pp;
afe19ff7 64
bdee397d
DG
65 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
66 struct child_to_clean *clean_me = *pp;
67
68 if (clean_me->pid == pid) {
69 *pp = clean_me->next;
70 free(clean_me);
afe19ff7
JK
71 return;
72 }
73 }
74}
75
9dc09c76
SP
76static inline void close_pair(int fd[2])
77{
78 close(fd[0]);
79 close(fd[1]);
80}
81
380395d0 82#ifndef GIT_WINDOWS_NATIVE
e4507ae8
SP
83static inline void dup_devnull(int to)
84{
85 int fd = open("/dev/null", O_RDWR);
a77f106c
TR
86 if (fd < 0)
87 die_errno(_("open /dev/null failed"));
88 if (dup2(fd, to) < 0)
89 die_errno(_("dup2(%d,%d) failed"), fd, to);
e4507ae8
SP
90 close(fd);
91}
75301f90 92#endif
e4507ae8 93
38f865c2
JK
94static char *locate_in_PATH(const char *file)
95{
96 const char *p = getenv("PATH");
97 struct strbuf buf = STRBUF_INIT;
98
99 if (!p || !*p)
100 return NULL;
101
102 while (1) {
103 const char *end = strchrnul(p, ':');
104
105 strbuf_reset(&buf);
106
107 /* POSIX specifies an empty entry as the current directory. */
108 if (end != p) {
109 strbuf_add(&buf, p, end - p);
110 strbuf_addch(&buf, '/');
111 }
112 strbuf_addstr(&buf, file);
113
114 if (!access(buf.buf, F_OK))
115 return strbuf_detach(&buf, NULL);
116
117 if (!*end)
118 break;
119 p = end + 1;
120 }
121
122 strbuf_release(&buf);
123 return NULL;
124}
125
126static int exists_in_PATH(const char *file)
127{
128 char *r = locate_in_PATH(file);
129 free(r);
130 return r != NULL;
131}
132
133int sane_execvp(const char *file, char * const argv[])
134{
135 if (!execvp(file, argv))
136 return 0; /* cannot happen ;-) */
137
138 /*
139 * When a command can't be found because one of the directories
140 * listed in $PATH is unsearchable, execvp reports EACCES, but
141 * careful usability testing (read: analysis of occasional bug
142 * reports) reveals that "No such file or directory" is more
143 * intuitive.
144 *
145 * We avoid commands with "/", because execvp will not do $PATH
146 * lookups in that case.
147 *
148 * The reassignment of EACCES to errno looks like a no-op below,
149 * but we need to protect against exists_in_PATH overwriting errno.
150 */
151 if (errno == EACCES && !strchr(file, '/'))
152 errno = exists_in_PATH(file) ? EACCES : ENOENT;
a7855083
JH
153 else if (errno == ENOTDIR && !strchr(file, '/'))
154 errno = ENOENT;
38f865c2
JK
155 return -1;
156}
157
8dba1e63
JK
158static const char **prepare_shell_cmd(const char **argv)
159{
160 int argc, nargc = 0;
161 const char **nargv;
162
163 for (argc = 0; argv[argc]; argc++)
164 ; /* just counting */
165 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
166 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
167
168 if (argc < 1)
169 die("BUG: shell command is empty");
170
f445644f 171 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
380395d0 172#ifndef GIT_WINDOWS_NATIVE
b3e34ddd 173 nargv[nargc++] = SHELL_PATH;
77629754
JS
174#else
175 nargv[nargc++] = "sh";
176#endif
f445644f 177 nargv[nargc++] = "-c";
8dba1e63 178
f445644f
JK
179 if (argc < 2)
180 nargv[nargc++] = argv[0];
181 else {
182 struct strbuf arg0 = STRBUF_INIT;
183 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
184 nargv[nargc++] = strbuf_detach(&arg0, NULL);
185 }
8dba1e63
JK
186 }
187
188 for (argc = 0; argv[argc]; argc++)
189 nargv[nargc++] = argv[argc];
190 nargv[nargc] = NULL;
191
192 return nargv;
193}
194
380395d0 195#ifndef GIT_WINDOWS_NATIVE
8dba1e63
JK
196static int execv_shell_cmd(const char **argv)
197{
198 const char **nargv = prepare_shell_cmd(argv);
199 trace_argv_printf(nargv, "trace: exec:");
38f865c2 200 sane_execvp(nargv[0], (char **)nargv);
8dba1e63
JK
201 free(nargv);
202 return -1;
203}
204#endif
205
380395d0 206#ifndef GIT_WINDOWS_NATIVE
a5487ddf 207static int child_err = 2;
2b541bf8
JS
208static int child_notifier = -1;
209
210static void notify_parent(void)
211{
a111eb78
JN
212 /*
213 * execvp failed. If possible, we'd like to let start_command
214 * know, so failures like ENOENT can be handled right away; but
215 * otherwise, finish_command will still report the error.
216 */
217 xwrite(child_notifier, "", 1);
2b541bf8 218}
a5487ddf
JS
219
220static NORETURN void die_child(const char *err, va_list params)
221{
3bc4181f 222 vwritef(child_err, "fatal: ", err, params);
a5487ddf
JS
223 exit(128);
224}
3bc4181f
CB
225
226static void error_child(const char *err, va_list params)
227{
228 vwritef(child_err, "error: ", err, params);
229}
200a76b7 230#endif
a5487ddf
JS
231
232static inline void set_cloexec(int fd)
233{
234 int flags = fcntl(fd, F_GETFD);
235 if (flags >= 0)
236 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
237}
a5487ddf 238
13274526 239static int wait_or_whine(pid_t pid, const char *argv0)
ab0b41da
JS
240{
241 int status, code = -1;
242 pid_t waiting;
243 int failed_errno = 0;
244
245 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
246 ; /* nothing */
247
248 if (waiting < 0) {
249 failed_errno = errno;
250 error("waitpid for %s failed: %s", argv0, strerror(errno));
251 } else if (waiting != pid) {
252 error("waitpid is confused (%s)", argv0);
253 } else if (WIFSIGNALED(status)) {
254 code = WTERMSIG(status);
a2767c5c
JK
255 if (code != SIGINT && code != SIGQUIT)
256 error("%s died of signal %d", argv0, code);
ab0b41da
JS
257 /*
258 * This return value is chosen so that code & 0xff
259 * mimics the exit code that a POSIX shell would report for
260 * a program that died from this signal.
261 */
709ca730 262 code += 128;
ab0b41da
JS
263 } else if (WIFEXITED(status)) {
264 code = WEXITSTATUS(status);
265 /*
266 * Convert special exit code when execvp failed.
267 */
268 if (code == 127) {
269 code = -1;
270 failed_errno = ENOENT;
ab0b41da
JS
271 }
272 } else {
273 error("waitpid is confused (%s)", argv0);
274 }
afe19ff7
JK
275
276 clear_child_for_cleanup(pid);
277
ab0b41da
JS
278 errno = failed_errno;
279 return code;
280}
281
ebcb5d16 282int start_command(struct child_process *cmd)
b1bf95bb 283{
f3b33f1d
JS
284 int need_in, need_out, need_err;
285 int fdin[2], fdout[2], fderr[2];
25043d8a 286 int failed_errno;
939296c4 287 char *str;
4919bf03 288
c460c0ec
JK
289 if (!cmd->argv)
290 cmd->argv = cmd->args.argv;
19a583dc
RS
291 if (!cmd->env)
292 cmd->env = cmd->env_array.argv;
c460c0ec 293
c20181e3
JS
294 /*
295 * In case of errors we must keep the promise to close FDs
296 * that have been passed in via ->in and ->out.
297 */
298
e4507ae8 299 need_in = !cmd->no_stdin && cmd->in < 0;
4919bf03 300 if (need_in) {
c20181e3 301 if (pipe(fdin) < 0) {
0ac77ec3 302 failed_errno = errno;
c20181e3
JS
303 if (cmd->out > 0)
304 close(cmd->out);
939296c4 305 str = "standard input";
0ac77ec3 306 goto fail_pipe;
c20181e3 307 }
4919bf03 308 cmd->in = fdin[1];
4919bf03
SP
309 }
310
e4507ae8
SP
311 need_out = !cmd->no_stdout
312 && !cmd->stdout_to_stderr
313 && cmd->out < 0;
f4bba25b
SP
314 if (need_out) {
315 if (pipe(fdout) < 0) {
0ac77ec3 316 failed_errno = errno;
f4bba25b
SP
317 if (need_in)
318 close_pair(fdin);
c20181e3
JS
319 else if (cmd->in)
320 close(cmd->in);
939296c4 321 str = "standard output";
0ac77ec3 322 goto fail_pipe;
f4bba25b
SP
323 }
324 cmd->out = fdout[0];
f4bba25b
SP
325 }
326
b73a4397 327 need_err = !cmd->no_stderr && cmd->err < 0;
f3b33f1d
JS
328 if (need_err) {
329 if (pipe(fderr) < 0) {
0ac77ec3 330 failed_errno = errno;
f3b33f1d
JS
331 if (need_in)
332 close_pair(fdin);
c20181e3
JS
333 else if (cmd->in)
334 close(cmd->in);
f3b33f1d
JS
335 if (need_out)
336 close_pair(fdout);
c20181e3
JS
337 else if (cmd->out)
338 close(cmd->out);
939296c4 339 str = "standard error";
0ac77ec3 340fail_pipe:
939296c4
SB
341 error("cannot create %s pipe for %s: %s",
342 str, cmd->argv[0], strerror(failed_errno));
c460c0ec 343 argv_array_clear(&cmd->args);
19a583dc 344 argv_array_clear(&cmd->env_array);
0ac77ec3
JS
345 errno = failed_errno;
346 return -1;
f3b33f1d
JS
347 }
348 cmd->err = fderr[0];
349 }
350
8852f5d7 351 trace_argv_printf(cmd->argv, "trace: run_command:");
13af8cbd 352 fflush(NULL);
8852f5d7 353
380395d0 354#ifndef GIT_WINDOWS_NATIVE
2b541bf8
JS
355{
356 int notify_pipe[2];
357 if (pipe(notify_pipe))
358 notify_pipe[0] = notify_pipe[1] = -1;
359
ebcb5d16 360 cmd->pid = fork();
25043d8a 361 failed_errno = errno;
ebcb5d16 362 if (!cmd->pid) {
a5487ddf
JS
363 /*
364 * Redirect the channel to write syscall error messages to
365 * before redirecting the process's stderr so that all die()
366 * in subsequent call paths use the parent's stderr.
367 */
368 if (cmd->no_stderr || need_err) {
369 child_err = dup(2);
370 set_cloexec(child_err);
371 }
372 set_die_routine(die_child);
3bc4181f 373 set_error_routine(error_child);
a5487ddf 374
2b541bf8
JS
375 close(notify_pipe[0]);
376 set_cloexec(notify_pipe[1]);
377 child_notifier = notify_pipe[1];
378 atexit(notify_parent);
379
e4507ae8
SP
380 if (cmd->no_stdin)
381 dup_devnull(0);
382 else if (need_in) {
4919bf03 383 dup2(fdin[0], 0);
9dc09c76 384 close_pair(fdin);
4919bf03
SP
385 } else if (cmd->in) {
386 dup2(cmd->in, 0);
387 close(cmd->in);
95d3c4f5 388 }
4919bf03 389
ce2cf27a
CC
390 if (cmd->no_stderr)
391 dup_devnull(2);
392 else if (need_err) {
393 dup2(fderr[1], 2);
394 close_pair(fderr);
4f41b611
SP
395 } else if (cmd->err > 1) {
396 dup2(cmd->err, 2);
397 close(cmd->err);
ce2cf27a
CC
398 }
399
e4507ae8
SP
400 if (cmd->no_stdout)
401 dup_devnull(1);
402 else if (cmd->stdout_to_stderr)
cd83c74c 403 dup2(2, 1);
f4bba25b
SP
404 else if (need_out) {
405 dup2(fdout[1], 1);
406 close_pair(fdout);
407 } else if (cmd->out > 1) {
408 dup2(cmd->out, 1);
409 close(cmd->out);
410 }
411
1568fea0 412 if (cmd->dir && chdir(cmd->dir))
d824cbba
TR
413 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
414 cmd->dir);
ee493148 415 if (cmd->env) {
3427b375
AR
416 for (; *cmd->env; cmd->env++) {
417 if (strchr(*cmd->env, '='))
4b25d091 418 putenv((char *)*cmd->env);
3427b375
AR
419 else
420 unsetenv(*cmd->env);
421 }
ee493148 422 }
5a50085c 423 if (cmd->git_cmd)
f1000898 424 execv_git_cmd(cmd->argv);
5a50085c 425 else if (cmd->use_shell)
8dba1e63 426 execv_shell_cmd(cmd->argv);
5a50085c 427 else
38f865c2 428 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
fc1b56f0
CB
429 if (errno == ENOENT) {
430 if (!cmd->silent_exec_failure)
431 error("cannot run %s: %s", cmd->argv[0],
432 strerror(ENOENT));
a5487ddf 433 exit(127);
fc1b56f0 434 } else {
a5487ddf 435 die_errno("cannot exec '%s'", cmd->argv[0]);
fc1b56f0 436 }
b1bf95bb 437 }
0ac77ec3
JS
438 if (cmd->pid < 0)
439 error("cannot fork() for %s: %s", cmd->argv[0],
25043d8a 440 strerror(errno));
afe19ff7
JK
441 else if (cmd->clean_on_exit)
442 mark_child_for_cleanup(cmd->pid);
2b541bf8
JS
443
444 /*
445 * Wait for child's execvp. If the execvp succeeds (or if fork()
446 * failed), EOF is seen immediately by the parent. Otherwise, the
447 * child process sends a single byte.
448 * Note that use of this infrastructure is completely advisory,
449 * therefore, we keep error checks minimal.
450 */
451 close(notify_pipe[1]);
452 if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
453 /*
454 * At this point we know that fork() succeeded, but execvp()
455 * failed. Errors have been reported to our stderr.
456 */
13274526 457 wait_or_whine(cmd->pid, cmd->argv[0]);
2b541bf8
JS
458 failed_errno = errno;
459 cmd->pid = -1;
460 }
461 close(notify_pipe[0]);
462}
ba26f296 463#else
0d30ad71 464{
75301f90 465 int fhin = 0, fhout = 1, fherr = 2;
108ac313 466 const char **sargv = cmd->argv;
ba26f296 467
75301f90
JS
468 if (cmd->no_stdin)
469 fhin = open("/dev/null", O_RDWR);
470 else if (need_in)
471 fhin = dup(fdin[0]);
472 else if (cmd->in)
473 fhin = dup(cmd->in);
474
475 if (cmd->no_stderr)
476 fherr = open("/dev/null", O_RDWR);
477 else if (need_err)
478 fherr = dup(fderr[1]);
76d44c8c
JH
479 else if (cmd->err > 2)
480 fherr = dup(cmd->err);
75301f90
JS
481
482 if (cmd->no_stdout)
483 fhout = open("/dev/null", O_RDWR);
484 else if (cmd->stdout_to_stderr)
485 fhout = dup(fherr);
486 else if (need_out)
487 fhout = dup(fdout[1]);
488 else if (cmd->out > 1)
489 fhout = dup(cmd->out);
ba26f296 490
5a50085c 491 if (cmd->git_cmd)
108ac313 492 cmd->argv = prepare_git_cmd(cmd->argv);
5a50085c 493 else if (cmd->use_shell)
8dba1e63 494 cmd->argv = prepare_shell_cmd(cmd->argv);
ba26f296 495
77734da2
KB
496 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
497 cmd->dir, fhin, fhout, fherr);
0ac77ec3 498 failed_errno = errno;
c024beb5 499 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
0ac77ec3 500 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
afe19ff7
JK
501 if (cmd->clean_on_exit && cmd->pid >= 0)
502 mark_child_for_cleanup(cmd->pid);
ba26f296 503
ba26f296 504 if (cmd->git_cmd)
108ac313 505 free(cmd->argv);
ba26f296 506
108ac313 507 cmd->argv = sargv;
75301f90
JS
508 if (fhin != 0)
509 close(fhin);
510 if (fhout != 1)
511 close(fhout);
512 if (fherr != 2)
513 close(fherr);
0d30ad71 514}
ba26f296
JS
515#endif
516
517 if (cmd->pid < 0) {
518 if (need_in)
519 close_pair(fdin);
520 else if (cmd->in)
521 close(cmd->in);
522 if (need_out)
523 close_pair(fdout);
524 else if (cmd->out)
525 close(cmd->out);
526 if (need_err)
527 close_pair(fderr);
fc012c28
D
528 else if (cmd->err)
529 close(cmd->err);
c460c0ec 530 argv_array_clear(&cmd->args);
19a583dc 531 argv_array_clear(&cmd->env_array);
0ac77ec3
JS
532 errno = failed_errno;
533 return -1;
ba26f296 534 }
4919bf03
SP
535
536 if (need_in)
537 close(fdin[0]);
538 else if (cmd->in)
539 close(cmd->in);
540
f4bba25b
SP
541 if (need_out)
542 close(fdout[1]);
c20181e3 543 else if (cmd->out)
f4bba25b
SP
544 close(cmd->out);
545
f3b33f1d
JS
546 if (need_err)
547 close(fderr[1]);
4f41b611
SP
548 else if (cmd->err)
549 close(cmd->err);
f3b33f1d 550
ebcb5d16
SP
551 return 0;
552}
553
2d22c208
JS
554int finish_command(struct child_process *cmd)
555{
c460c0ec
JK
556 int ret = wait_or_whine(cmd->pid, cmd->argv[0]);
557 argv_array_clear(&cmd->args);
19a583dc 558 argv_array_clear(&cmd->env_array);
c460c0ec 559 return ret;
2d22c208
JS
560}
561
ebcb5d16
SP
562int run_command(struct child_process *cmd)
563{
c29b3962
JK
564 int code;
565
566 if (cmd->out < 0 || cmd->err < 0)
567 die("BUG: run_command with a pipe can cause deadlock");
568
569 code = start_command(cmd);
ebcb5d16
SP
570 if (code)
571 return code;
572 return finish_command(cmd);
573}
574
f1000898
SP
575int run_command_v_opt(const char **argv, int opt)
576{
41e9bad7 577 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
1568fea0
AR
578}
579
ee493148
AR
580int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
581{
1f87293d
RS
582 struct child_process cmd = CHILD_PROCESS_INIT;
583 cmd.argv = argv;
584 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
585 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
586 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
587 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
588 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
589 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
ee493148
AR
590 cmd.dir = dir;
591 cmd.env = env;
592 return run_command(&cmd);
593}
2d22c208 594
f6b60983 595#ifndef NO_PTHREADS
0ea1c89b
JS
596static pthread_t main_thread;
597static int main_thread_set;
598static pthread_key_t async_key;
1ece66bc 599static pthread_key_t async_die_counter;
0ea1c89b 600
200a76b7 601static void *run_thread(void *data)
618ebe9f
JS
602{
603 struct async *async = data;
f6b60983 604 intptr_t ret;
0ea1c89b
JS
605
606 pthread_setspecific(async_key, async);
f6b60983 607 ret = async->proc(async->proc_in, async->proc_out, async->data);
200a76b7 608 return (void *)ret;
618ebe9f 609}
0ea1c89b
JS
610
611static NORETURN void die_async(const char *err, va_list params)
612{
613 vreportf("fatal: ", err, params);
614
615 if (!pthread_equal(main_thread, pthread_self())) {
616 struct async *async = pthread_getspecific(async_key);
617 if (async->proc_in >= 0)
618 close(async->proc_in);
619 if (async->proc_out >= 0)
620 close(async->proc_out);
621 pthread_exit((void *)128);
622 }
623
624 exit(128);
618ebe9f 625}
1ece66bc
JK
626
627static int async_die_is_recursing(void)
628{
629 void *ret = pthread_getspecific(async_die_counter);
630 pthread_setspecific(async_die_counter, (void *)1);
631 return ret != NULL;
632}
633
0f4b6db3
EB
634#else
635
636static struct {
637 void (**handlers)(void);
638 size_t nr;
639 size_t alloc;
640} git_atexit_hdlrs;
641
642static int git_atexit_installed;
643
6066a7ea 644static void git_atexit_dispatch(void)
0f4b6db3
EB
645{
646 size_t i;
647
648 for (i=git_atexit_hdlrs.nr ; i ; i--)
649 git_atexit_hdlrs.handlers[i-1]();
650}
651
6066a7ea 652static void git_atexit_clear(void)
0f4b6db3
EB
653{
654 free(git_atexit_hdlrs.handlers);
655 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
656 git_atexit_installed = 0;
657}
658
659#undef atexit
660int git_atexit(void (*handler)(void))
661{
662 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
663 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
664 if (!git_atexit_installed) {
665 if (atexit(&git_atexit_dispatch))
666 return -1;
667 git_atexit_installed = 1;
668 }
669 return 0;
670}
671#define atexit git_atexit
672
618ebe9f
JS
673#endif
674
2d22c208
JS
675int start_async(struct async *async)
676{
ae6a5609
EFL
677 int need_in, need_out;
678 int fdin[2], fdout[2];
679 int proc_in, proc_out;
2d22c208 680
ae6a5609
EFL
681 need_in = async->in < 0;
682 if (need_in) {
683 if (pipe(fdin) < 0) {
684 if (async->out > 0)
685 close(async->out);
686 return error("cannot create pipe: %s", strerror(errno));
687 }
688 async->in = fdin[1];
689 }
690
691 need_out = async->out < 0;
692 if (need_out) {
693 if (pipe(fdout) < 0) {
694 if (need_in)
695 close_pair(fdin);
696 else if (async->in)
697 close(async->in);
698 return error("cannot create pipe: %s", strerror(errno));
699 }
700 async->out = fdout[0];
701 }
702
703 if (need_in)
704 proc_in = fdin[0];
705 else if (async->in)
706 proc_in = async->in;
707 else
708 proc_in = -1;
709
710 if (need_out)
711 proc_out = fdout[1];
712 else if (async->out)
713 proc_out = async->out;
714 else
715 proc_out = -1;
2d22c208 716
f6b60983 717#ifdef NO_PTHREADS
2c3766f0
AM
718 /* Flush stdio before fork() to avoid cloning buffers */
719 fflush(NULL);
720
2d22c208
JS
721 async->pid = fork();
722 if (async->pid < 0) {
723 error("fork (async) failed: %s", strerror(errno));
ae6a5609 724 goto error;
2d22c208
JS
725 }
726 if (!async->pid) {
ae6a5609
EFL
727 if (need_in)
728 close(fdin[1]);
729 if (need_out)
730 close(fdout[0]);
0f4b6db3 731 git_atexit_clear();
ae6a5609 732 exit(!!async->proc(proc_in, proc_out, async->data));
2d22c208 733 }
ae6a5609 734
afe19ff7
JK
735 mark_child_for_cleanup(async->pid);
736
ae6a5609
EFL
737 if (need_in)
738 close(fdin[0]);
739 else if (async->in)
740 close(async->in);
741
742 if (need_out)
743 close(fdout[1]);
744 else if (async->out)
745 close(async->out);
618ebe9f 746#else
0ea1c89b
JS
747 if (!main_thread_set) {
748 /*
749 * We assume that the first time that start_async is called
750 * it is from the main thread.
751 */
752 main_thread_set = 1;
753 main_thread = pthread_self();
754 pthread_key_create(&async_key, NULL);
1ece66bc 755 pthread_key_create(&async_die_counter, NULL);
0ea1c89b 756 set_die_routine(die_async);
1ece66bc 757 set_die_is_recursing_routine(async_die_is_recursing);
0ea1c89b
JS
758 }
759
200a76b7
JS
760 if (proc_in >= 0)
761 set_cloexec(proc_in);
762 if (proc_out >= 0)
763 set_cloexec(proc_out);
ae6a5609
EFL
764 async->proc_in = proc_in;
765 async->proc_out = proc_out;
200a76b7
JS
766 {
767 int err = pthread_create(&async->tid, NULL, run_thread, async);
768 if (err) {
769 error("cannot create thread: %s", strerror(err));
770 goto error;
771 }
618ebe9f
JS
772 }
773#endif
2d22c208 774 return 0;
ae6a5609
EFL
775
776error:
777 if (need_in)
778 close_pair(fdin);
779 else if (async->in)
780 close(async->in);
781
782 if (need_out)
783 close_pair(fdout);
784 else if (async->out)
785 close(async->out);
786 return -1;
2d22c208
JS
787}
788
789int finish_async(struct async *async)
790{
f6b60983 791#ifdef NO_PTHREADS
0398fc34 792 return wait_or_whine(async->pid, "child process");
618ebe9f 793#else
200a76b7
JS
794 void *ret = (void *)(intptr_t)(-1);
795
796 if (pthread_join(async->tid, &ret))
797 error("pthread_join failed");
798 return (int)(intptr_t)ret;
618ebe9f 799#endif
2d22c208 800}
ae98a008 801
5a7da2dc
AS
802char *find_hook(const char *name)
803{
804 char *path = git_path("hooks/%s", name);
805 if (access(path, X_OK) < 0)
806 path = NULL;
807
808 return path;
809}
810
15048f8a 811int run_hook_ve(const char *const *env, const char *name, va_list args)
ae98a008 812{
d3180279 813 struct child_process hook = CHILD_PROCESS_INIT;
15048f8a 814 const char *p;
ae98a008 815
5a7da2dc
AS
816 p = find_hook(name);
817 if (!p)
cf94ca8e
SB
818 return 0;
819
d1d09456
RS
820 argv_array_push(&hook.args, p);
821 while ((p = va_arg(args, const char *)))
822 argv_array_push(&hook.args, p);
15048f8a 823 hook.env = env;
ae98a008
SB
824 hook.no_stdin = 1;
825 hook.stdout_to_stderr = 1;
ae98a008 826
d1d09456 827 return run_command(&hook);
ae98a008 828}
15048f8a
BP
829
830int run_hook_le(const char *const *env, const char *name, ...)
831{
832 va_list args;
833 int ret;
834
835 va_start(args, name);
836 ret = run_hook_ve(env, name, args);
837 va_end(args);
838
839 return ret;
840}
911ec99b
JK
841
842int capture_command(struct child_process *cmd, struct strbuf *buf, size_t hint)
843{
844 cmd->out = -1;
845 if (start_command(cmd) < 0)
846 return -1;
847
848 if (strbuf_read(buf, cmd->out, hint) < 0) {
849 close(cmd->out);
850 finish_command(cmd); /* throw away exit code */
851 return -1;
852 }
853
854 close(cmd->out);
855 return finish_command(cmd);
856}