]> git.ipfire.org Git - thirdparty/git.git/blame - run-command.c
run-command: move check_pipe() from write_or_die to run_command
[thirdparty/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"
c553c72e
SB
6#include "thread-utils.h"
7#include "strbuf.h"
b1bf95bb 8
483bbd4e
RS
9void child_process_init(struct child_process *child)
10{
11 memset(child, 0, sizeof(*child));
12 argv_array_init(&child->args);
19a583dc 13 argv_array_init(&child->env_array);
483bbd4e
RS
14}
15
2d71608e
RS
16void child_process_clear(struct child_process *child)
17{
18 argv_array_clear(&child->args);
19 argv_array_clear(&child->env_array);
20}
21
afe19ff7
JK
22struct child_to_clean {
23 pid_t pid;
24 struct child_to_clean *next;
25};
26static struct child_to_clean *children_to_clean;
27static int installed_child_cleanup_handler;
28
507d7804 29static void cleanup_children(int sig, int in_signal)
afe19ff7
JK
30{
31 while (children_to_clean) {
32 struct child_to_clean *p = children_to_clean;
33 children_to_clean = p->next;
34 kill(p->pid, sig);
507d7804
TI
35 if (!in_signal)
36 free(p);
afe19ff7
JK
37 }
38}
39
40static void cleanup_children_on_signal(int sig)
41{
507d7804 42 cleanup_children(sig, 1);
afe19ff7
JK
43 sigchain_pop(sig);
44 raise(sig);
45}
46
47static void cleanup_children_on_exit(void)
48{
507d7804 49 cleanup_children(SIGTERM, 0);
afe19ff7
JK
50}
51
52static void mark_child_for_cleanup(pid_t pid)
53{
54 struct child_to_clean *p = xmalloc(sizeof(*p));
55 p->pid = pid;
56 p->next = children_to_clean;
57 children_to_clean = p;
58
59 if (!installed_child_cleanup_handler) {
60 atexit(cleanup_children_on_exit);
61 sigchain_push_common(cleanup_children_on_signal);
62 installed_child_cleanup_handler = 1;
63 }
64}
65
66static void clear_child_for_cleanup(pid_t pid)
67{
bdee397d 68 struct child_to_clean **pp;
afe19ff7 69
bdee397d
DG
70 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
71 struct child_to_clean *clean_me = *pp;
72
73 if (clean_me->pid == pid) {
74 *pp = clean_me->next;
75 free(clean_me);
afe19ff7
JK
76 return;
77 }
78 }
79}
80
9dc09c76
SP
81static inline void close_pair(int fd[2])
82{
83 close(fd[0]);
84 close(fd[1]);
85}
86
380395d0 87#ifndef GIT_WINDOWS_NATIVE
e4507ae8
SP
88static inline void dup_devnull(int to)
89{
90 int fd = open("/dev/null", O_RDWR);
a77f106c
TR
91 if (fd < 0)
92 die_errno(_("open /dev/null failed"));
93 if (dup2(fd, to) < 0)
94 die_errno(_("dup2(%d,%d) failed"), fd, to);
e4507ae8
SP
95 close(fd);
96}
75301f90 97#endif
e4507ae8 98
38f865c2
JK
99static char *locate_in_PATH(const char *file)
100{
101 const char *p = getenv("PATH");
102 struct strbuf buf = STRBUF_INIT;
103
104 if (!p || !*p)
105 return NULL;
106
107 while (1) {
108 const char *end = strchrnul(p, ':');
109
110 strbuf_reset(&buf);
111
112 /* POSIX specifies an empty entry as the current directory. */
113 if (end != p) {
114 strbuf_add(&buf, p, end - p);
115 strbuf_addch(&buf, '/');
116 }
117 strbuf_addstr(&buf, file);
118
119 if (!access(buf.buf, F_OK))
120 return strbuf_detach(&buf, NULL);
121
122 if (!*end)
123 break;
124 p = end + 1;
125 }
126
127 strbuf_release(&buf);
128 return NULL;
129}
130
131static int exists_in_PATH(const char *file)
132{
133 char *r = locate_in_PATH(file);
134 free(r);
135 return r != NULL;
136}
137
138int sane_execvp(const char *file, char * const argv[])
139{
140 if (!execvp(file, argv))
141 return 0; /* cannot happen ;-) */
142
143 /*
144 * When a command can't be found because one of the directories
145 * listed in $PATH is unsearchable, execvp reports EACCES, but
146 * careful usability testing (read: analysis of occasional bug
147 * reports) reveals that "No such file or directory" is more
148 * intuitive.
149 *
150 * We avoid commands with "/", because execvp will not do $PATH
151 * lookups in that case.
152 *
153 * The reassignment of EACCES to errno looks like a no-op below,
154 * but we need to protect against exists_in_PATH overwriting errno.
155 */
156 if (errno == EACCES && !strchr(file, '/'))
157 errno = exists_in_PATH(file) ? EACCES : ENOENT;
a7855083
JH
158 else if (errno == ENOTDIR && !strchr(file, '/'))
159 errno = ENOENT;
38f865c2
JK
160 return -1;
161}
162
20574f55 163static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
8dba1e63 164{
20574f55 165 if (!argv[0])
8dba1e63
JK
166 die("BUG: shell command is empty");
167
f445644f 168 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
380395d0 169#ifndef GIT_WINDOWS_NATIVE
20574f55 170 argv_array_push(out, SHELL_PATH);
77629754 171#else
20574f55 172 argv_array_push(out, "sh");
77629754 173#endif
20574f55 174 argv_array_push(out, "-c");
8dba1e63 175
20574f55
JK
176 /*
177 * If we have no extra arguments, we do not even need to
178 * bother with the "$@" magic.
179 */
180 if (!argv[1])
181 argv_array_push(out, argv[0]);
182 else
183 argv_array_pushf(out, "%s \"$@\"", argv[0]);
184 }
8dba1e63 185
20574f55
JK
186 argv_array_pushv(out, argv);
187 return out->argv;
8dba1e63
JK
188}
189
380395d0 190#ifndef GIT_WINDOWS_NATIVE
8dba1e63
JK
191static int execv_shell_cmd(const char **argv)
192{
20574f55
JK
193 struct argv_array nargv = ARGV_ARRAY_INIT;
194 prepare_shell_cmd(&nargv, argv);
195 trace_argv_printf(nargv.argv, "trace: exec:");
196 sane_execvp(nargv.argv[0], (char **)nargv.argv);
197 argv_array_clear(&nargv);
8dba1e63
JK
198 return -1;
199}
200#endif
201
380395d0 202#ifndef GIT_WINDOWS_NATIVE
2b541bf8
JS
203static int child_notifier = -1;
204
205static void notify_parent(void)
206{
a111eb78
JN
207 /*
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.
211 */
212 xwrite(child_notifier, "", 1);
2b541bf8 213}
200a76b7 214#endif
a5487ddf
JS
215
216static inline void set_cloexec(int fd)
217{
218 int flags = fcntl(fd, F_GETFD);
219 if (flags >= 0)
220 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
221}
a5487ddf 222
507d7804 223static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
ab0b41da
JS
224{
225 int status, code = -1;
226 pid_t waiting;
227 int failed_errno = 0;
228
229 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
230 ; /* nothing */
507d7804
TI
231 if (in_signal)
232 return 0;
ab0b41da
JS
233
234 if (waiting < 0) {
235 failed_errno = errno;
fbcb0e06 236 error_errno("waitpid for %s failed", argv0);
ab0b41da
JS
237 } else if (waiting != pid) {
238 error("waitpid is confused (%s)", argv0);
239 } else if (WIFSIGNALED(status)) {
240 code = WTERMSIG(status);
ac78663b 241 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
a2767c5c 242 error("%s died of signal %d", argv0, code);
ab0b41da
JS
243 /*
244 * This return value is chosen so that code & 0xff
245 * mimics the exit code that a POSIX shell would report for
246 * a program that died from this signal.
247 */
709ca730 248 code += 128;
ab0b41da
JS
249 } else if (WIFEXITED(status)) {
250 code = WEXITSTATUS(status);
251 /*
252 * Convert special exit code when execvp failed.
253 */
254 if (code == 127) {
255 code = -1;
256 failed_errno = ENOENT;
ab0b41da
JS
257 }
258 } else {
259 error("waitpid is confused (%s)", argv0);
260 }
afe19ff7
JK
261
262 clear_child_for_cleanup(pid);
263
ab0b41da
JS
264 errno = failed_errno;
265 return code;
266}
267
ebcb5d16 268int start_command(struct child_process *cmd)
b1bf95bb 269{
f3b33f1d
JS
270 int need_in, need_out, need_err;
271 int fdin[2], fdout[2], fderr[2];
25043d8a 272 int failed_errno;
939296c4 273 char *str;
4919bf03 274
c460c0ec
JK
275 if (!cmd->argv)
276 cmd->argv = cmd->args.argv;
19a583dc
RS
277 if (!cmd->env)
278 cmd->env = cmd->env_array.argv;
c460c0ec 279
c20181e3
JS
280 /*
281 * In case of errors we must keep the promise to close FDs
282 * that have been passed in via ->in and ->out.
283 */
284
e4507ae8 285 need_in = !cmd->no_stdin && cmd->in < 0;
4919bf03 286 if (need_in) {
c20181e3 287 if (pipe(fdin) < 0) {
0ac77ec3 288 failed_errno = errno;
c20181e3
JS
289 if (cmd->out > 0)
290 close(cmd->out);
939296c4 291 str = "standard input";
0ac77ec3 292 goto fail_pipe;
c20181e3 293 }
4919bf03 294 cmd->in = fdin[1];
4919bf03
SP
295 }
296
e4507ae8
SP
297 need_out = !cmd->no_stdout
298 && !cmd->stdout_to_stderr
299 && cmd->out < 0;
f4bba25b
SP
300 if (need_out) {
301 if (pipe(fdout) < 0) {
0ac77ec3 302 failed_errno = errno;
f4bba25b
SP
303 if (need_in)
304 close_pair(fdin);
c20181e3
JS
305 else if (cmd->in)
306 close(cmd->in);
939296c4 307 str = "standard output";
0ac77ec3 308 goto fail_pipe;
f4bba25b
SP
309 }
310 cmd->out = fdout[0];
f4bba25b
SP
311 }
312
b73a4397 313 need_err = !cmd->no_stderr && cmd->err < 0;
f3b33f1d
JS
314 if (need_err) {
315 if (pipe(fderr) < 0) {
0ac77ec3 316 failed_errno = errno;
f3b33f1d
JS
317 if (need_in)
318 close_pair(fdin);
c20181e3
JS
319 else if (cmd->in)
320 close(cmd->in);
f3b33f1d
JS
321 if (need_out)
322 close_pair(fdout);
c20181e3
JS
323 else if (cmd->out)
324 close(cmd->out);
939296c4 325 str = "standard error";
0ac77ec3 326fail_pipe:
939296c4
SB
327 error("cannot create %s pipe for %s: %s",
328 str, cmd->argv[0], strerror(failed_errno));
2d71608e 329 child_process_clear(cmd);
0ac77ec3
JS
330 errno = failed_errno;
331 return -1;
f3b33f1d
JS
332 }
333 cmd->err = fderr[0];
334 }
335
8852f5d7 336 trace_argv_printf(cmd->argv, "trace: run_command:");
13af8cbd 337 fflush(NULL);
8852f5d7 338
380395d0 339#ifndef GIT_WINDOWS_NATIVE
2b541bf8
JS
340{
341 int notify_pipe[2];
342 if (pipe(notify_pipe))
343 notify_pipe[0] = notify_pipe[1] = -1;
344
ebcb5d16 345 cmd->pid = fork();
25043d8a 346 failed_errno = errno;
ebcb5d16 347 if (!cmd->pid) {
a5487ddf
JS
348 /*
349 * Redirect the channel to write syscall error messages to
350 * before redirecting the process's stderr so that all die()
351 * in subsequent call paths use the parent's stderr.
352 */
353 if (cmd->no_stderr || need_err) {
3b331e92 354 int child_err = dup(2);
a5487ddf 355 set_cloexec(child_err);
3b331e92 356 set_error_handle(fdopen(child_err, "w"));
a5487ddf 357 }
a5487ddf 358
2b541bf8
JS
359 close(notify_pipe[0]);
360 set_cloexec(notify_pipe[1]);
361 child_notifier = notify_pipe[1];
362 atexit(notify_parent);
363
e4507ae8
SP
364 if (cmd->no_stdin)
365 dup_devnull(0);
366 else if (need_in) {
4919bf03 367 dup2(fdin[0], 0);
9dc09c76 368 close_pair(fdin);
4919bf03
SP
369 } else if (cmd->in) {
370 dup2(cmd->in, 0);
371 close(cmd->in);
95d3c4f5 372 }
4919bf03 373
ce2cf27a
CC
374 if (cmd->no_stderr)
375 dup_devnull(2);
376 else if (need_err) {
377 dup2(fderr[1], 2);
378 close_pair(fderr);
4f41b611
SP
379 } else if (cmd->err > 1) {
380 dup2(cmd->err, 2);
381 close(cmd->err);
ce2cf27a
CC
382 }
383
e4507ae8
SP
384 if (cmd->no_stdout)
385 dup_devnull(1);
386 else if (cmd->stdout_to_stderr)
cd83c74c 387 dup2(2, 1);
f4bba25b
SP
388 else if (need_out) {
389 dup2(fdout[1], 1);
390 close_pair(fdout);
391 } else if (cmd->out > 1) {
392 dup2(cmd->out, 1);
393 close(cmd->out);
394 }
395
1568fea0 396 if (cmd->dir && chdir(cmd->dir))
d824cbba
TR
397 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
398 cmd->dir);
ee493148 399 if (cmd->env) {
3427b375
AR
400 for (; *cmd->env; cmd->env++) {
401 if (strchr(*cmd->env, '='))
4b25d091 402 putenv((char *)*cmd->env);
3427b375
AR
403 else
404 unsetenv(*cmd->env);
405 }
ee493148 406 }
5a50085c 407 if (cmd->git_cmd)
f1000898 408 execv_git_cmd(cmd->argv);
5a50085c 409 else if (cmd->use_shell)
8dba1e63 410 execv_shell_cmd(cmd->argv);
5a50085c 411 else
38f865c2 412 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
fc1b56f0
CB
413 if (errno == ENOENT) {
414 if (!cmd->silent_exec_failure)
415 error("cannot run %s: %s", cmd->argv[0],
416 strerror(ENOENT));
a5487ddf 417 exit(127);
fc1b56f0 418 } else {
a5487ddf 419 die_errno("cannot exec '%s'", cmd->argv[0]);
fc1b56f0 420 }
b1bf95bb 421 }
0ac77ec3 422 if (cmd->pid < 0)
fbcb0e06 423 error_errno("cannot fork() for %s", cmd->argv[0]);
afe19ff7
JK
424 else if (cmd->clean_on_exit)
425 mark_child_for_cleanup(cmd->pid);
2b541bf8
JS
426
427 /*
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.
433 */
434 close(notify_pipe[1]);
435 if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
436 /*
437 * At this point we know that fork() succeeded, but execvp()
438 * failed. Errors have been reported to our stderr.
439 */
507d7804 440 wait_or_whine(cmd->pid, cmd->argv[0], 0);
2b541bf8
JS
441 failed_errno = errno;
442 cmd->pid = -1;
443 }
444 close(notify_pipe[0]);
445}
ba26f296 446#else
0d30ad71 447{
75301f90 448 int fhin = 0, fhout = 1, fherr = 2;
108ac313 449 const char **sargv = cmd->argv;
20574f55 450 struct argv_array nargv = ARGV_ARRAY_INIT;
ba26f296 451
75301f90
JS
452 if (cmd->no_stdin)
453 fhin = open("/dev/null", O_RDWR);
454 else if (need_in)
455 fhin = dup(fdin[0]);
456 else if (cmd->in)
457 fhin = dup(cmd->in);
458
459 if (cmd->no_stderr)
460 fherr = open("/dev/null", O_RDWR);
461 else if (need_err)
462 fherr = dup(fderr[1]);
76d44c8c
JH
463 else if (cmd->err > 2)
464 fherr = dup(cmd->err);
75301f90
JS
465
466 if (cmd->no_stdout)
467 fhout = open("/dev/null", O_RDWR);
468 else if (cmd->stdout_to_stderr)
469 fhout = dup(fherr);
470 else if (need_out)
471 fhout = dup(fdout[1]);
472 else if (cmd->out > 1)
473 fhout = dup(cmd->out);
ba26f296 474
5a50085c 475 if (cmd->git_cmd)
20574f55 476 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
5a50085c 477 else if (cmd->use_shell)
20574f55 478 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
ba26f296 479
77734da2
KB
480 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
481 cmd->dir, fhin, fhout, fherr);
0ac77ec3 482 failed_errno = errno;
c024beb5 483 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
fbcb0e06 484 error_errno("cannot spawn %s", cmd->argv[0]);
afe19ff7
JK
485 if (cmd->clean_on_exit && cmd->pid >= 0)
486 mark_child_for_cleanup(cmd->pid);
ba26f296 487
20574f55 488 argv_array_clear(&nargv);
108ac313 489 cmd->argv = sargv;
75301f90
JS
490 if (fhin != 0)
491 close(fhin);
492 if (fhout != 1)
493 close(fhout);
494 if (fherr != 2)
495 close(fherr);
0d30ad71 496}
ba26f296
JS
497#endif
498
499 if (cmd->pid < 0) {
500 if (need_in)
501 close_pair(fdin);
502 else if (cmd->in)
503 close(cmd->in);
504 if (need_out)
505 close_pair(fdout);
506 else if (cmd->out)
507 close(cmd->out);
508 if (need_err)
509 close_pair(fderr);
fc012c28
D
510 else if (cmd->err)
511 close(cmd->err);
2d71608e 512 child_process_clear(cmd);
0ac77ec3
JS
513 errno = failed_errno;
514 return -1;
ba26f296 515 }
4919bf03
SP
516
517 if (need_in)
518 close(fdin[0]);
519 else if (cmd->in)
520 close(cmd->in);
521
f4bba25b
SP
522 if (need_out)
523 close(fdout[1]);
c20181e3 524 else if (cmd->out)
f4bba25b
SP
525 close(cmd->out);
526
f3b33f1d
JS
527 if (need_err)
528 close(fderr[1]);
4f41b611
SP
529 else if (cmd->err)
530 close(cmd->err);
f3b33f1d 531
ebcb5d16
SP
532 return 0;
533}
534
2d22c208
JS
535int finish_command(struct child_process *cmd)
536{
507d7804 537 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
2d71608e 538 child_process_clear(cmd);
c460c0ec 539 return ret;
2d22c208
JS
540}
541
507d7804
TI
542int finish_command_in_signal(struct child_process *cmd)
543{
544 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
545}
546
547
ebcb5d16
SP
548int run_command(struct child_process *cmd)
549{
c29b3962
JK
550 int code;
551
552 if (cmd->out < 0 || cmd->err < 0)
553 die("BUG: run_command with a pipe can cause deadlock");
554
555 code = start_command(cmd);
ebcb5d16
SP
556 if (code)
557 return code;
558 return finish_command(cmd);
559}
560
f1000898
SP
561int run_command_v_opt(const char **argv, int opt)
562{
41e9bad7 563 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
1568fea0
AR
564}
565
ee493148
AR
566int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
567{
1f87293d
RS
568 struct child_process cmd = CHILD_PROCESS_INIT;
569 cmd.argv = argv;
570 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
571 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
572 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
573 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
574 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
575 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
ee493148
AR
576 cmd.dir = dir;
577 cmd.env = env;
578 return run_command(&cmd);
579}
2d22c208 580
f6b60983 581#ifndef NO_PTHREADS
0ea1c89b
JS
582static pthread_t main_thread;
583static int main_thread_set;
584static pthread_key_t async_key;
1ece66bc 585static pthread_key_t async_die_counter;
0ea1c89b 586
200a76b7 587static void *run_thread(void *data)
618ebe9f
JS
588{
589 struct async *async = data;
f6b60983 590 intptr_t ret;
0ea1c89b 591
c792d7b6
JK
592 if (async->isolate_sigpipe) {
593 sigset_t mask;
594 sigemptyset(&mask);
595 sigaddset(&mask, SIGPIPE);
596 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
597 ret = error("unable to block SIGPIPE in async thread");
598 return (void *)ret;
599 }
600 }
601
0ea1c89b 602 pthread_setspecific(async_key, async);
f6b60983 603 ret = async->proc(async->proc_in, async->proc_out, async->data);
200a76b7 604 return (void *)ret;
618ebe9f 605}
0ea1c89b
JS
606
607static NORETURN void die_async(const char *err, va_list params)
608{
609 vreportf("fatal: ", err, params);
610
661a8cf4 611 if (in_async()) {
0ea1c89b
JS
612 struct async *async = pthread_getspecific(async_key);
613 if (async->proc_in >= 0)
614 close(async->proc_in);
615 if (async->proc_out >= 0)
616 close(async->proc_out);
617 pthread_exit((void *)128);
618 }
619
620 exit(128);
618ebe9f 621}
1ece66bc
JK
622
623static int async_die_is_recursing(void)
624{
625 void *ret = pthread_getspecific(async_die_counter);
626 pthread_setspecific(async_die_counter, (void *)1);
627 return ret != NULL;
628}
629
661a8cf4
JK
630int in_async(void)
631{
632 if (!main_thread_set)
633 return 0; /* no asyncs started yet */
634 return !pthread_equal(main_thread, pthread_self());
635}
636
b992fe10 637static void NORETURN async_exit(int code)
9658846c
JK
638{
639 pthread_exit((void *)(intptr_t)code);
640}
641
0f4b6db3
EB
642#else
643
644static struct {
645 void (**handlers)(void);
646 size_t nr;
647 size_t alloc;
648} git_atexit_hdlrs;
649
650static int git_atexit_installed;
651
6066a7ea 652static void git_atexit_dispatch(void)
0f4b6db3
EB
653{
654 size_t i;
655
656 for (i=git_atexit_hdlrs.nr ; i ; i--)
657 git_atexit_hdlrs.handlers[i-1]();
658}
659
6066a7ea 660static void git_atexit_clear(void)
0f4b6db3
EB
661{
662 free(git_atexit_hdlrs.handlers);
663 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
664 git_atexit_installed = 0;
665}
666
667#undef atexit
668int git_atexit(void (*handler)(void))
669{
670 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
671 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
672 if (!git_atexit_installed) {
673 if (atexit(&git_atexit_dispatch))
674 return -1;
675 git_atexit_installed = 1;
676 }
677 return 0;
678}
679#define atexit git_atexit
680
661a8cf4
JK
681static int process_is_async;
682int in_async(void)
683{
684 return process_is_async;
685}
686
b992fe10 687static void NORETURN async_exit(int code)
9658846c
JK
688{
689 exit(code);
690}
691
618ebe9f
JS
692#endif
693
b992fe10
LS
694void check_pipe(int err)
695{
696 if (err == EPIPE) {
697 if (in_async())
698 async_exit(141);
699
700 signal(SIGPIPE, SIG_DFL);
701 raise(SIGPIPE);
702 /* Should never happen, but just in case... */
703 exit(141);
704 }
705}
706
2d22c208
JS
707int start_async(struct async *async)
708{
ae6a5609
EFL
709 int need_in, need_out;
710 int fdin[2], fdout[2];
711 int proc_in, proc_out;
2d22c208 712
ae6a5609
EFL
713 need_in = async->in < 0;
714 if (need_in) {
715 if (pipe(fdin) < 0) {
716 if (async->out > 0)
717 close(async->out);
fbcb0e06 718 return error_errno("cannot create pipe");
ae6a5609
EFL
719 }
720 async->in = fdin[1];
721 }
722
723 need_out = async->out < 0;
724 if (need_out) {
725 if (pipe(fdout) < 0) {
726 if (need_in)
727 close_pair(fdin);
728 else if (async->in)
729 close(async->in);
fbcb0e06 730 return error_errno("cannot create pipe");
ae6a5609
EFL
731 }
732 async->out = fdout[0];
733 }
734
735 if (need_in)
736 proc_in = fdin[0];
737 else if (async->in)
738 proc_in = async->in;
739 else
740 proc_in = -1;
741
742 if (need_out)
743 proc_out = fdout[1];
744 else if (async->out)
745 proc_out = async->out;
746 else
747 proc_out = -1;
2d22c208 748
f6b60983 749#ifdef NO_PTHREADS
2c3766f0
AM
750 /* Flush stdio before fork() to avoid cloning buffers */
751 fflush(NULL);
752
2d22c208
JS
753 async->pid = fork();
754 if (async->pid < 0) {
fbcb0e06 755 error_errno("fork (async) failed");
ae6a5609 756 goto error;
2d22c208
JS
757 }
758 if (!async->pid) {
ae6a5609
EFL
759 if (need_in)
760 close(fdin[1]);
761 if (need_out)
762 close(fdout[0]);
0f4b6db3 763 git_atexit_clear();
661a8cf4 764 process_is_async = 1;
ae6a5609 765 exit(!!async->proc(proc_in, proc_out, async->data));
2d22c208 766 }
ae6a5609 767
afe19ff7
JK
768 mark_child_for_cleanup(async->pid);
769
ae6a5609
EFL
770 if (need_in)
771 close(fdin[0]);
772 else if (async->in)
773 close(async->in);
774
775 if (need_out)
776 close(fdout[1]);
777 else if (async->out)
778 close(async->out);
618ebe9f 779#else
0ea1c89b
JS
780 if (!main_thread_set) {
781 /*
782 * We assume that the first time that start_async is called
783 * it is from the main thread.
784 */
785 main_thread_set = 1;
786 main_thread = pthread_self();
787 pthread_key_create(&async_key, NULL);
1ece66bc 788 pthread_key_create(&async_die_counter, NULL);
0ea1c89b 789 set_die_routine(die_async);
1ece66bc 790 set_die_is_recursing_routine(async_die_is_recursing);
0ea1c89b
JS
791 }
792
200a76b7
JS
793 if (proc_in >= 0)
794 set_cloexec(proc_in);
795 if (proc_out >= 0)
796 set_cloexec(proc_out);
ae6a5609
EFL
797 async->proc_in = proc_in;
798 async->proc_out = proc_out;
200a76b7
JS
799 {
800 int err = pthread_create(&async->tid, NULL, run_thread, async);
801 if (err) {
fbcb0e06 802 error_errno("cannot create thread");
200a76b7
JS
803 goto error;
804 }
618ebe9f
JS
805 }
806#endif
2d22c208 807 return 0;
ae6a5609
EFL
808
809error:
810 if (need_in)
811 close_pair(fdin);
812 else if (async->in)
813 close(async->in);
814
815 if (need_out)
816 close_pair(fdout);
817 else if (async->out)
818 close(async->out);
819 return -1;
2d22c208
JS
820}
821
822int finish_async(struct async *async)
823{
f6b60983 824#ifdef NO_PTHREADS
507d7804 825 return wait_or_whine(async->pid, "child process", 0);
618ebe9f 826#else
200a76b7
JS
827 void *ret = (void *)(intptr_t)(-1);
828
829 if (pthread_join(async->tid, &ret))
830 error("pthread_join failed");
831 return (int)(intptr_t)ret;
618ebe9f 832#endif
2d22c208 833}
ae98a008 834
dcf69262 835const char *find_hook(const char *name)
5a7da2dc 836{
03f2c773 837 static struct strbuf path = STRBUF_INIT;
5a7da2dc 838
03f2c773 839 strbuf_reset(&path);
9445b492 840 strbuf_git_path(&path, "hooks/%s", name);
03f2c773
JK
841 if (access(path.buf, X_OK) < 0)
842 return NULL;
843 return path.buf;
5a7da2dc
AS
844}
845
15048f8a 846int run_hook_ve(const char *const *env, const char *name, va_list args)
ae98a008 847{
d3180279 848 struct child_process hook = CHILD_PROCESS_INIT;
15048f8a 849 const char *p;
ae98a008 850
5a7da2dc
AS
851 p = find_hook(name);
852 if (!p)
cf94ca8e
SB
853 return 0;
854
d1d09456
RS
855 argv_array_push(&hook.args, p);
856 while ((p = va_arg(args, const char *)))
857 argv_array_push(&hook.args, p);
15048f8a 858 hook.env = env;
ae98a008
SB
859 hook.no_stdin = 1;
860 hook.stdout_to_stderr = 1;
ae98a008 861
d1d09456 862 return run_command(&hook);
ae98a008 863}
15048f8a
BP
864
865int run_hook_le(const char *const *env, const char *name, ...)
866{
867 va_list args;
868 int ret;
869
870 va_start(args, name);
871 ret = run_hook_ve(env, name, args);
872 va_end(args);
873
874 return ret;
875}
911ec99b 876
96335bcf
JK
877struct io_pump {
878 /* initialized by caller */
879 int fd;
880 int type; /* POLLOUT or POLLIN */
881 union {
882 struct {
883 const char *buf;
884 size_t len;
885 } out;
886 struct {
887 struct strbuf *buf;
888 size_t hint;
889 } in;
890 } u;
891
892 /* returned by pump_io */
893 int error; /* 0 for success, otherwise errno */
894
895 /* internal use */
896 struct pollfd *pfd;
897};
898
899static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
900{
901 int pollsize = 0;
902 int i;
903
904 for (i = 0; i < nr; i++) {
905 struct io_pump *io = &slots[i];
906 if (io->fd < 0)
907 continue;
908 pfd[pollsize].fd = io->fd;
909 pfd[pollsize].events = io->type;
910 io->pfd = &pfd[pollsize++];
911 }
912
913 if (!pollsize)
914 return 0;
915
916 if (poll(pfd, pollsize, -1) < 0) {
917 if (errno == EINTR)
918 return 1;
919 die_errno("poll failed");
920 }
921
922 for (i = 0; i < nr; i++) {
923 struct io_pump *io = &slots[i];
924
925 if (io->fd < 0)
926 continue;
927
928 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
929 continue;
930
931 if (io->type == POLLOUT) {
932 ssize_t len = xwrite(io->fd,
933 io->u.out.buf, io->u.out.len);
934 if (len < 0) {
935 io->error = errno;
936 close(io->fd);
937 io->fd = -1;
938 } else {
939 io->u.out.buf += len;
940 io->u.out.len -= len;
941 if (!io->u.out.len) {
942 close(io->fd);
943 io->fd = -1;
944 }
945 }
946 }
947
948 if (io->type == POLLIN) {
949 ssize_t len = strbuf_read_once(io->u.in.buf,
950 io->fd, io->u.in.hint);
951 if (len < 0)
952 io->error = errno;
953 if (len <= 0) {
954 close(io->fd);
955 io->fd = -1;
956 }
957 }
958 }
959
960 return 1;
961}
962
963static int pump_io(struct io_pump *slots, int nr)
911ec99b 964{
96335bcf
JK
965 struct pollfd *pfd;
966 int i;
967
968 for (i = 0; i < nr; i++)
969 slots[i].error = 0;
970
971 ALLOC_ARRAY(pfd, nr);
972 while (pump_io_round(slots, nr, pfd))
973 ; /* nothing */
974 free(pfd);
975
976 /* There may be multiple errno values, so just pick the first. */
977 for (i = 0; i < nr; i++) {
978 if (slots[i].error) {
979 errno = slots[i].error;
980 return -1;
981 }
982 }
983 return 0;
984}
985
986
987int pipe_command(struct child_process *cmd,
988 const char *in, size_t in_len,
989 struct strbuf *out, size_t out_hint,
990 struct strbuf *err, size_t err_hint)
991{
992 struct io_pump io[3];
993 int nr = 0;
994
995 if (in)
996 cmd->in = -1;
997 if (out)
998 cmd->out = -1;
999 if (err)
1000 cmd->err = -1;
1001
911ec99b
JK
1002 if (start_command(cmd) < 0)
1003 return -1;
1004
96335bcf
JK
1005 if (in) {
1006 io[nr].fd = cmd->in;
1007 io[nr].type = POLLOUT;
1008 io[nr].u.out.buf = in;
1009 io[nr].u.out.len = in_len;
1010 nr++;
1011 }
1012 if (out) {
1013 io[nr].fd = cmd->out;
1014 io[nr].type = POLLIN;
1015 io[nr].u.in.buf = out;
1016 io[nr].u.in.hint = out_hint;
1017 nr++;
1018 }
1019 if (err) {
1020 io[nr].fd = cmd->err;
1021 io[nr].type = POLLIN;
1022 io[nr].u.in.buf = err;
1023 io[nr].u.in.hint = err_hint;
1024 nr++;
1025 }
1026
1027 if (pump_io(io, nr) < 0) {
911ec99b
JK
1028 finish_command(cmd); /* throw away exit code */
1029 return -1;
1030 }
1031
911ec99b
JK
1032 return finish_command(cmd);
1033}
c553c72e
SB
1034
1035enum child_state {
1036 GIT_CP_FREE,
1037 GIT_CP_WORKING,
1038 GIT_CP_WAIT_CLEANUP,
1039};
1040
1041struct parallel_processes {
1042 void *data;
1043
1044 int max_processes;
1045 int nr_processes;
1046
1047 get_next_task_fn get_next_task;
1048 start_failure_fn start_failure;
1049 task_finished_fn task_finished;
1050
1051 struct {
1052 enum child_state state;
1053 struct child_process process;
1054 struct strbuf err;
1055 void *data;
1056 } *children;
1057 /*
1058 * The struct pollfd is logically part of *children,
1059 * but the system call expects it as its own array.
1060 */
1061 struct pollfd *pfd;
1062
1063 unsigned shutdown : 1;
1064
1065 int output_owner;
1066 struct strbuf buffered_output; /* of finished children */
1067};
1068
aa710494 1069static int default_start_failure(struct strbuf *out,
c553c72e
SB
1070 void *pp_cb,
1071 void *pp_task_cb)
1072{
c553c72e
SB
1073 return 0;
1074}
1075
1076static int default_task_finished(int result,
aa710494 1077 struct strbuf *out,
c553c72e
SB
1078 void *pp_cb,
1079 void *pp_task_cb)
1080{
c553c72e
SB
1081 return 0;
1082}
1083
1084static void kill_children(struct parallel_processes *pp, int signo)
1085{
1086 int i, n = pp->max_processes;
1087
1088 for (i = 0; i < n; i++)
1089 if (pp->children[i].state == GIT_CP_WORKING)
1090 kill(pp->children[i].process.pid, signo);
1091}
1092
1093static struct parallel_processes *pp_for_signal;
1094
1095static void handle_children_on_signal(int signo)
1096{
1097 kill_children(pp_for_signal, signo);
1098 sigchain_pop(signo);
1099 raise(signo);
1100}
1101
1102static void pp_init(struct parallel_processes *pp,
1103 int n,
1104 get_next_task_fn get_next_task,
1105 start_failure_fn start_failure,
1106 task_finished_fn task_finished,
1107 void *data)
1108{
1109 int i;
1110
1111 if (n < 1)
1112 n = online_cpus();
1113
1114 pp->max_processes = n;
1115
1116 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1117
1118 pp->data = data;
1119 if (!get_next_task)
1120 die("BUG: you need to specify a get_next_task function");
1121 pp->get_next_task = get_next_task;
1122
1123 pp->start_failure = start_failure ? start_failure : default_start_failure;
1124 pp->task_finished = task_finished ? task_finished : default_task_finished;
1125
1126 pp->nr_processes = 0;
1127 pp->output_owner = 0;
1128 pp->shutdown = 0;
1129 pp->children = xcalloc(n, sizeof(*pp->children));
1130 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1131 strbuf_init(&pp->buffered_output, 0);
1132
1133 for (i = 0; i < n; i++) {
1134 strbuf_init(&pp->children[i].err, 0);
1135 child_process_init(&pp->children[i].process);
1136 pp->pfd[i].events = POLLIN | POLLHUP;
1137 pp->pfd[i].fd = -1;
1138 }
1139
1140 pp_for_signal = pp;
1141 sigchain_push_common(handle_children_on_signal);
1142}
1143
1144static void pp_cleanup(struct parallel_processes *pp)
1145{
1146 int i;
1147
1148 trace_printf("run_processes_parallel: done");
1149 for (i = 0; i < pp->max_processes; i++) {
1150 strbuf_release(&pp->children[i].err);
1151 child_process_clear(&pp->children[i].process);
1152 }
1153
1154 free(pp->children);
1155 free(pp->pfd);
1156
1157 /*
1158 * When get_next_task added messages to the buffer in its last
1159 * iteration, the buffered output is non empty.
1160 */
2dac9b56 1161 strbuf_write(&pp->buffered_output, stderr);
c553c72e
SB
1162 strbuf_release(&pp->buffered_output);
1163
1164 sigchain_pop_common();
1165}
1166
1167/* returns
1168 * 0 if a new task was started.
1169 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1170 * problem with starting a new command)
1171 * <0 no new job was started, user wishes to shutdown early. Use negative code
1172 * to signal the children.
1173 */
1174static int pp_start_one(struct parallel_processes *pp)
1175{
1176 int i, code;
1177
1178 for (i = 0; i < pp->max_processes; i++)
1179 if (pp->children[i].state == GIT_CP_FREE)
1180 break;
1181 if (i == pp->max_processes)
1182 die("BUG: bookkeeping is hard");
1183
1184 code = pp->get_next_task(&pp->children[i].process,
1185 &pp->children[i].err,
1186 pp->data,
1187 &pp->children[i].data);
1188 if (!code) {
1189 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1190 strbuf_reset(&pp->children[i].err);
1191 return 1;
1192 }
1193 pp->children[i].process.err = -1;
1194 pp->children[i].process.stdout_to_stderr = 1;
1195 pp->children[i].process.no_stdin = 1;
1196
1197 if (start_command(&pp->children[i].process)) {
2a73b3da 1198 code = pp->start_failure(&pp->children[i].err,
c553c72e
SB
1199 pp->data,
1200 &pp->children[i].data);
1201 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1202 strbuf_reset(&pp->children[i].err);
1203 if (code)
1204 pp->shutdown = 1;
1205 return code;
1206 }
1207
1208 pp->nr_processes++;
1209 pp->children[i].state = GIT_CP_WORKING;
1210 pp->pfd[i].fd = pp->children[i].process.err;
1211 return 0;
1212}
1213
1214static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1215{
1216 int i;
1217
1218 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1219 if (errno == EINTR)
1220 continue;
1221 pp_cleanup(pp);
1222 die_errno("poll");
1223 }
1224
1225 /* Buffer output from all pipes. */
1226 for (i = 0; i < pp->max_processes; i++) {
1227 if (pp->children[i].state == GIT_CP_WORKING &&
1228 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1229 int n = strbuf_read_once(&pp->children[i].err,
1230 pp->children[i].process.err, 0);
1231 if (n == 0) {
1232 close(pp->children[i].process.err);
1233 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1234 } else if (n < 0)
1235 if (errno != EAGAIN)
1236 die_errno("read");
1237 }
1238 }
1239}
1240
1241static void pp_output(struct parallel_processes *pp)
1242{
1243 int i = pp->output_owner;
1244 if (pp->children[i].state == GIT_CP_WORKING &&
1245 pp->children[i].err.len) {
2dac9b56 1246 strbuf_write(&pp->children[i].err, stderr);
c553c72e
SB
1247 strbuf_reset(&pp->children[i].err);
1248 }
1249}
1250
1251static int pp_collect_finished(struct parallel_processes *pp)
1252{
1253 int i, code;
1254 int n = pp->max_processes;
1255 int result = 0;
1256
1257 while (pp->nr_processes > 0) {
1258 for (i = 0; i < pp->max_processes; i++)
1259 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1260 break;
1261 if (i == pp->max_processes)
1262 break;
1263
1264 code = finish_command(&pp->children[i].process);
1265
2a73b3da 1266 code = pp->task_finished(code,
c553c72e
SB
1267 &pp->children[i].err, pp->data,
1268 &pp->children[i].data);
1269
1270 if (code)
1271 result = code;
1272 if (code < 0)
1273 break;
1274
1275 pp->nr_processes--;
1276 pp->children[i].state = GIT_CP_FREE;
1277 pp->pfd[i].fd = -1;
1278 child_process_init(&pp->children[i].process);
1279
1280 if (i != pp->output_owner) {
1281 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1282 strbuf_reset(&pp->children[i].err);
1283 } else {
2dac9b56 1284 strbuf_write(&pp->children[i].err, stderr);
c553c72e
SB
1285 strbuf_reset(&pp->children[i].err);
1286
1287 /* Output all other finished child processes */
2dac9b56 1288 strbuf_write(&pp->buffered_output, stderr);
c553c72e
SB
1289 strbuf_reset(&pp->buffered_output);
1290
1291 /*
1292 * Pick next process to output live.
1293 * NEEDSWORK:
1294 * For now we pick it randomly by doing a round
1295 * robin. Later we may want to pick the one with
1296 * the most output or the longest or shortest
1297 * running process time.
1298 */
1299 for (i = 0; i < n; i++)
1300 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1301 break;
1302 pp->output_owner = (pp->output_owner + i) % n;
1303 }
1304 }
1305 return result;
1306}
1307
1308int run_processes_parallel(int n,
1309 get_next_task_fn get_next_task,
1310 start_failure_fn start_failure,
1311 task_finished_fn task_finished,
1312 void *pp_cb)
1313{
1314 int i, code;
1315 int output_timeout = 100;
1316 int spawn_cap = 4;
1317 struct parallel_processes pp;
1318
1319 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1320 while (1) {
1321 for (i = 0;
1322 i < spawn_cap && !pp.shutdown &&
1323 pp.nr_processes < pp.max_processes;
1324 i++) {
1325 code = pp_start_one(&pp);
1326 if (!code)
1327 continue;
1328 if (code < 0) {
1329 pp.shutdown = 1;
1330 kill_children(&pp, -code);
1331 }
1332 break;
1333 }
1334 if (!pp.nr_processes)
1335 break;
1336 pp_buffer_stderr(&pp, output_timeout);
1337 pp_output(&pp);
1338 code = pp_collect_finished(&pp);
1339 if (code) {
1340 pp.shutdown = 1;
1341 if (code < 0)
1342 kill_children(&pp, -code);
1343 }
1344 }
1345
1346 pp_cleanup(&pp);
1347 return 0;
1348}