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