Merge branch 'jg/credential-cache-chdir-to-sockdir'
[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_to_clean *next;
25 };
26 static struct child_to_clean *children_to_clean;
27 static int installed_child_cleanup_handler;
28
29 static void cleanup_children(int sig, int in_signal)
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);
35                 if (!in_signal)
36                         free(p);
37         }
38 }
39
40 static void cleanup_children_on_signal(int sig)
41 {
42         cleanup_children(sig, 1);
43         sigchain_pop(sig);
44         raise(sig);
45 }
46
47 static void cleanup_children_on_exit(void)
48 {
49         cleanup_children(SIGTERM, 0);
50 }
51
52 static 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
66 static void clear_child_for_cleanup(pid_t pid)
67 {
68         struct child_to_clean **pp;
69
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);
76                         return;
77                 }
78         }
79 }
80
81 static inline void close_pair(int fd[2])
82 {
83         close(fd[0]);
84         close(fd[1]);
85 }
86
87 #ifndef GIT_WINDOWS_NATIVE
88 static inline void dup_devnull(int to)
89 {
90         int fd = open("/dev/null", O_RDWR);
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);
95         close(fd);
96 }
97 #endif
98
99 static 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
131 static int exists_in_PATH(const char *file)
132 {
133         char *r = locate_in_PATH(file);
134         free(r);
135         return r != NULL;
136 }
137
138 int 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;
158         else if (errno == ENOTDIR && !strchr(file, '/'))
159                 errno = ENOENT;
160         return -1;
161 }
162
163 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
164 {
165         if (!argv[0])
166                 die("BUG: shell command is empty");
167
168         if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
169 #ifndef GIT_WINDOWS_NATIVE
170                 argv_array_push(out, SHELL_PATH);
171 #else
172                 argv_array_push(out, "sh");
173 #endif
174                 argv_array_push(out, "-c");
175
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         }
185
186         argv_array_pushv(out, argv);
187         return out->argv;
188 }
189
190 #ifndef GIT_WINDOWS_NATIVE
191 static int execv_shell_cmd(const char **argv)
192 {
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);
198         return -1;
199 }
200 #endif
201
202 #ifndef GIT_WINDOWS_NATIVE
203 static int child_notifier = -1;
204
205 static void notify_parent(void)
206 {
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);
213 }
214 #endif
215
216 static 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 }
222
223 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
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 */
231         if (in_signal)
232                 return 0;
233
234         if (waiting < 0) {
235                 failed_errno = errno;
236                 error("waitpid for %s failed: %s", argv0, strerror(errno));
237         } else if (waiting != pid) {
238                 error("waitpid is confused (%s)", argv0);
239         } else if (WIFSIGNALED(status)) {
240                 code = WTERMSIG(status);
241                 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
242                         error("%s died of signal %d", argv0, code);
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                  */
248                 code += 128;
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;
257                 }
258         } else {
259                 error("waitpid is confused (%s)", argv0);
260         }
261
262         clear_child_for_cleanup(pid);
263
264         errno = failed_errno;
265         return code;
266 }
267
268 int start_command(struct child_process *cmd)
269 {
270         int need_in, need_out, need_err;
271         int fdin[2], fdout[2], fderr[2];
272         int failed_errno;
273         char *str;
274
275         if (!cmd->argv)
276                 cmd->argv = cmd->args.argv;
277         if (!cmd->env)
278                 cmd->env = cmd->env_array.argv;
279
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
285         need_in = !cmd->no_stdin && cmd->in < 0;
286         if (need_in) {
287                 if (pipe(fdin) < 0) {
288                         failed_errno = errno;
289                         if (cmd->out > 0)
290                                 close(cmd->out);
291                         str = "standard input";
292                         goto fail_pipe;
293                 }
294                 cmd->in = fdin[1];
295         }
296
297         need_out = !cmd->no_stdout
298                 && !cmd->stdout_to_stderr
299                 && cmd->out < 0;
300         if (need_out) {
301                 if (pipe(fdout) < 0) {
302                         failed_errno = errno;
303                         if (need_in)
304                                 close_pair(fdin);
305                         else if (cmd->in)
306                                 close(cmd->in);
307                         str = "standard output";
308                         goto fail_pipe;
309                 }
310                 cmd->out = fdout[0];
311         }
312
313         need_err = !cmd->no_stderr && cmd->err < 0;
314         if (need_err) {
315                 if (pipe(fderr) < 0) {
316                         failed_errno = errno;
317                         if (need_in)
318                                 close_pair(fdin);
319                         else if (cmd->in)
320                                 close(cmd->in);
321                         if (need_out)
322                                 close_pair(fdout);
323                         else if (cmd->out)
324                                 close(cmd->out);
325                         str = "standard error";
326 fail_pipe:
327                         error("cannot create %s pipe for %s: %s",
328                                 str, cmd->argv[0], strerror(failed_errno));
329                         child_process_clear(cmd);
330                         errno = failed_errno;
331                         return -1;
332                 }
333                 cmd->err = fderr[0];
334         }
335
336         trace_argv_printf(cmd->argv, "trace: run_command:");
337         fflush(NULL);
338
339 #ifndef GIT_WINDOWS_NATIVE
340 {
341         int notify_pipe[2];
342         if (pipe(notify_pipe))
343                 notify_pipe[0] = notify_pipe[1] = -1;
344
345         cmd->pid = fork();
346         failed_errno = errno;
347         if (!cmd->pid) {
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) {
354                         int child_err = dup(2);
355                         set_cloexec(child_err);
356                         set_error_handle(fdopen(child_err, "w"));
357                 }
358
359                 close(notify_pipe[0]);
360                 set_cloexec(notify_pipe[1]);
361                 child_notifier = notify_pipe[1];
362                 atexit(notify_parent);
363
364                 if (cmd->no_stdin)
365                         dup_devnull(0);
366                 else if (need_in) {
367                         dup2(fdin[0], 0);
368                         close_pair(fdin);
369                 } else if (cmd->in) {
370                         dup2(cmd->in, 0);
371                         close(cmd->in);
372                 }
373
374                 if (cmd->no_stderr)
375                         dup_devnull(2);
376                 else if (need_err) {
377                         dup2(fderr[1], 2);
378                         close_pair(fderr);
379                 } else if (cmd->err > 1) {
380                         dup2(cmd->err, 2);
381                         close(cmd->err);
382                 }
383
384                 if (cmd->no_stdout)
385                         dup_devnull(1);
386                 else if (cmd->stdout_to_stderr)
387                         dup2(2, 1);
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
396                 if (cmd->dir && chdir(cmd->dir))
397                         die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
398                             cmd->dir);
399                 if (cmd->env) {
400                         for (; *cmd->env; cmd->env++) {
401                                 if (strchr(*cmd->env, '='))
402                                         putenv((char *)*cmd->env);
403                                 else
404                                         unsetenv(*cmd->env);
405                         }
406                 }
407                 if (cmd->git_cmd)
408                         execv_git_cmd(cmd->argv);
409                 else if (cmd->use_shell)
410                         execv_shell_cmd(cmd->argv);
411                 else
412                         sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
413                 if (errno == ENOENT) {
414                         if (!cmd->silent_exec_failure)
415                                 error("cannot run %s: %s", cmd->argv[0],
416                                         strerror(ENOENT));
417                         exit(127);
418                 } else {
419                         die_errno("cannot exec '%s'", cmd->argv[0]);
420                 }
421         }
422         if (cmd->pid < 0)
423                 error("cannot fork() for %s: %s", cmd->argv[0],
424                         strerror(errno));
425         else if (cmd->clean_on_exit)
426                 mark_child_for_cleanup(cmd->pid);
427
428         /*
429          * Wait for child's execvp. If the execvp succeeds (or if fork()
430          * failed), EOF is seen immediately by the parent. Otherwise, the
431          * child process sends a single byte.
432          * Note that use of this infrastructure is completely advisory,
433          * therefore, we keep error checks minimal.
434          */
435         close(notify_pipe[1]);
436         if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
437                 /*
438                  * At this point we know that fork() succeeded, but execvp()
439                  * failed. Errors have been reported to our stderr.
440                  */
441                 wait_or_whine(cmd->pid, cmd->argv[0], 0);
442                 failed_errno = errno;
443                 cmd->pid = -1;
444         }
445         close(notify_pipe[0]);
446 }
447 #else
448 {
449         int fhin = 0, fhout = 1, fherr = 2;
450         const char **sargv = cmd->argv;
451         struct argv_array nargv = ARGV_ARRAY_INIT;
452
453         if (cmd->no_stdin)
454                 fhin = open("/dev/null", O_RDWR);
455         else if (need_in)
456                 fhin = dup(fdin[0]);
457         else if (cmd->in)
458                 fhin = dup(cmd->in);
459
460         if (cmd->no_stderr)
461                 fherr = open("/dev/null", O_RDWR);
462         else if (need_err)
463                 fherr = dup(fderr[1]);
464         else if (cmd->err > 2)
465                 fherr = dup(cmd->err);
466
467         if (cmd->no_stdout)
468                 fhout = open("/dev/null", O_RDWR);
469         else if (cmd->stdout_to_stderr)
470                 fhout = dup(fherr);
471         else if (need_out)
472                 fhout = dup(fdout[1]);
473         else if (cmd->out > 1)
474                 fhout = dup(cmd->out);
475
476         if (cmd->git_cmd)
477                 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
478         else if (cmd->use_shell)
479                 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
480
481         cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
482                         cmd->dir, fhin, fhout, fherr);
483         failed_errno = errno;
484         if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
485                 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
486         if (cmd->clean_on_exit && cmd->pid >= 0)
487                 mark_child_for_cleanup(cmd->pid);
488
489         argv_array_clear(&nargv);
490         cmd->argv = sargv;
491         if (fhin != 0)
492                 close(fhin);
493         if (fhout != 1)
494                 close(fhout);
495         if (fherr != 2)
496                 close(fherr);
497 }
498 #endif
499
500         if (cmd->pid < 0) {
501                 if (need_in)
502                         close_pair(fdin);
503                 else if (cmd->in)
504                         close(cmd->in);
505                 if (need_out)
506                         close_pair(fdout);
507                 else if (cmd->out)
508                         close(cmd->out);
509                 if (need_err)
510                         close_pair(fderr);
511                 else if (cmd->err)
512                         close(cmd->err);
513                 child_process_clear(cmd);
514                 errno = failed_errno;
515                 return -1;
516         }
517
518         if (need_in)
519                 close(fdin[0]);
520         else if (cmd->in)
521                 close(cmd->in);
522
523         if (need_out)
524                 close(fdout[1]);
525         else if (cmd->out)
526                 close(cmd->out);
527
528         if (need_err)
529                 close(fderr[1]);
530         else if (cmd->err)
531                 close(cmd->err);
532
533         return 0;
534 }
535
536 int finish_command(struct child_process *cmd)
537 {
538         int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
539         child_process_clear(cmd);
540         return ret;
541 }
542
543 int finish_command_in_signal(struct child_process *cmd)
544 {
545         return wait_or_whine(cmd->pid, cmd->argv[0], 1);
546 }
547
548
549 int run_command(struct child_process *cmd)
550 {
551         int code;
552
553         if (cmd->out < 0 || cmd->err < 0)
554                 die("BUG: run_command with a pipe can cause deadlock");
555
556         code = start_command(cmd);
557         if (code)
558                 return code;
559         return finish_command(cmd);
560 }
561
562 int run_command_v_opt(const char **argv, int opt)
563 {
564         return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
565 }
566
567 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
568 {
569         struct child_process cmd = CHILD_PROCESS_INIT;
570         cmd.argv = argv;
571         cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
572         cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
573         cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
574         cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
575         cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
576         cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
577         cmd.dir = dir;
578         cmd.env = env;
579         return run_command(&cmd);
580 }
581
582 #ifndef NO_PTHREADS
583 static pthread_t main_thread;
584 static int main_thread_set;
585 static pthread_key_t async_key;
586 static pthread_key_t async_die_counter;
587
588 static void *run_thread(void *data)
589 {
590         struct async *async = data;
591         intptr_t ret;
592
593         pthread_setspecific(async_key, async);
594         ret = async->proc(async->proc_in, async->proc_out, async->data);
595         return (void *)ret;
596 }
597
598 static NORETURN void die_async(const char *err, va_list params)
599 {
600         vreportf("fatal: ", err, params);
601
602         if (in_async()) {
603                 struct async *async = pthread_getspecific(async_key);
604                 if (async->proc_in >= 0)
605                         close(async->proc_in);
606                 if (async->proc_out >= 0)
607                         close(async->proc_out);
608                 pthread_exit((void *)128);
609         }
610
611         exit(128);
612 }
613
614 static int async_die_is_recursing(void)
615 {
616         void *ret = pthread_getspecific(async_die_counter);
617         pthread_setspecific(async_die_counter, (void *)1);
618         return ret != NULL;
619 }
620
621 int in_async(void)
622 {
623         if (!main_thread_set)
624                 return 0; /* no asyncs started yet */
625         return !pthread_equal(main_thread, pthread_self());
626 }
627
628 #else
629
630 static struct {
631         void (**handlers)(void);
632         size_t nr;
633         size_t alloc;
634 } git_atexit_hdlrs;
635
636 static int git_atexit_installed;
637
638 static void git_atexit_dispatch(void)
639 {
640         size_t i;
641
642         for (i=git_atexit_hdlrs.nr ; i ; i--)
643                 git_atexit_hdlrs.handlers[i-1]();
644 }
645
646 static void git_atexit_clear(void)
647 {
648         free(git_atexit_hdlrs.handlers);
649         memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
650         git_atexit_installed = 0;
651 }
652
653 #undef atexit
654 int git_atexit(void (*handler)(void))
655 {
656         ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
657         git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
658         if (!git_atexit_installed) {
659                 if (atexit(&git_atexit_dispatch))
660                         return -1;
661                 git_atexit_installed = 1;
662         }
663         return 0;
664 }
665 #define atexit git_atexit
666
667 static int process_is_async;
668 int in_async(void)
669 {
670         return process_is_async;
671 }
672
673 #endif
674
675 int start_async(struct async *async)
676 {
677         int need_in, need_out;
678         int fdin[2], fdout[2];
679         int proc_in, proc_out;
680
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;
716
717 #ifdef NO_PTHREADS
718         /* Flush stdio before fork() to avoid cloning buffers */
719         fflush(NULL);
720
721         async->pid = fork();
722         if (async->pid < 0) {
723                 error("fork (async) failed: %s", strerror(errno));
724                 goto error;
725         }
726         if (!async->pid) {
727                 if (need_in)
728                         close(fdin[1]);
729                 if (need_out)
730                         close(fdout[0]);
731                 git_atexit_clear();
732                 process_is_async = 1;
733                 exit(!!async->proc(proc_in, proc_out, async->data));
734         }
735
736         mark_child_for_cleanup(async->pid);
737
738         if (need_in)
739                 close(fdin[0]);
740         else if (async->in)
741                 close(async->in);
742
743         if (need_out)
744                 close(fdout[1]);
745         else if (async->out)
746                 close(async->out);
747 #else
748         if (!main_thread_set) {
749                 /*
750                  * We assume that the first time that start_async is called
751                  * it is from the main thread.
752                  */
753                 main_thread_set = 1;
754                 main_thread = pthread_self();
755                 pthread_key_create(&async_key, NULL);
756                 pthread_key_create(&async_die_counter, NULL);
757                 set_die_routine(die_async);
758                 set_die_is_recursing_routine(async_die_is_recursing);
759         }
760
761         if (proc_in >= 0)
762                 set_cloexec(proc_in);
763         if (proc_out >= 0)
764                 set_cloexec(proc_out);
765         async->proc_in = proc_in;
766         async->proc_out = proc_out;
767         {
768                 int err = pthread_create(&async->tid, NULL, run_thread, async);
769                 if (err) {
770                         error("cannot create thread: %s", strerror(err));
771                         goto error;
772                 }
773         }
774 #endif
775         return 0;
776
777 error:
778         if (need_in)
779                 close_pair(fdin);
780         else if (async->in)
781                 close(async->in);
782
783         if (need_out)
784                 close_pair(fdout);
785         else if (async->out)
786                 close(async->out);
787         return -1;
788 }
789
790 int finish_async(struct async *async)
791 {
792 #ifdef NO_PTHREADS
793         return wait_or_whine(async->pid, "child process", 0);
794 #else
795         void *ret = (void *)(intptr_t)(-1);
796
797         if (pthread_join(async->tid, &ret))
798                 error("pthread_join failed");
799         return (int)(intptr_t)ret;
800 #endif
801 }
802
803 const char *find_hook(const char *name)
804 {
805         static struct strbuf path = STRBUF_INIT;
806
807         strbuf_reset(&path);
808         strbuf_git_path(&path, "hooks/%s", name);
809         if (access(path.buf, X_OK) < 0)
810                 return NULL;
811         return path.buf;
812 }
813
814 int run_hook_ve(const char *const *env, const char *name, va_list args)
815 {
816         struct child_process hook = CHILD_PROCESS_INIT;
817         const char *p;
818
819         p = find_hook(name);
820         if (!p)
821                 return 0;
822
823         argv_array_push(&hook.args, p);
824         while ((p = va_arg(args, const char *)))
825                 argv_array_push(&hook.args, p);
826         hook.env = env;
827         hook.no_stdin = 1;
828         hook.stdout_to_stderr = 1;
829
830         return run_command(&hook);
831 }
832
833 int run_hook_le(const char *const *env, const char *name, ...)
834 {
835         va_list args;
836         int ret;
837
838         va_start(args, name);
839         ret = run_hook_ve(env, name, args);
840         va_end(args);
841
842         return ret;
843 }
844
845 int capture_command(struct child_process *cmd, struct strbuf *buf, size_t hint)
846 {
847         cmd->out = -1;
848         if (start_command(cmd) < 0)
849                 return -1;
850
851         if (strbuf_read(buf, cmd->out, hint) < 0) {
852                 close(cmd->out);
853                 finish_command(cmd); /* throw away exit code */
854                 return -1;
855         }
856
857         close(cmd->out);
858         return finish_command(cmd);
859 }
860
861 enum child_state {
862         GIT_CP_FREE,
863         GIT_CP_WORKING,
864         GIT_CP_WAIT_CLEANUP,
865 };
866
867 struct parallel_processes {
868         void *data;
869
870         int max_processes;
871         int nr_processes;
872
873         get_next_task_fn get_next_task;
874         start_failure_fn start_failure;
875         task_finished_fn task_finished;
876
877         struct {
878                 enum child_state state;
879                 struct child_process process;
880                 struct strbuf err;
881                 void *data;
882         } *children;
883         /*
884          * The struct pollfd is logically part of *children,
885          * but the system call expects it as its own array.
886          */
887         struct pollfd *pfd;
888
889         unsigned shutdown : 1;
890
891         int output_owner;
892         struct strbuf buffered_output; /* of finished children */
893 };
894
895 static int default_start_failure(struct child_process *cp,
896                                  struct strbuf *err,
897                                  void *pp_cb,
898                                  void *pp_task_cb)
899 {
900         int i;
901
902         strbuf_addstr(err, "Starting a child failed:");
903         for (i = 0; cp->argv[i]; i++)
904                 strbuf_addf(err, " %s", cp->argv[i]);
905
906         return 0;
907 }
908
909 static int default_task_finished(int result,
910                                  struct child_process *cp,
911                                  struct strbuf *err,
912                                  void *pp_cb,
913                                  void *pp_task_cb)
914 {
915         int i;
916
917         if (!result)
918                 return 0;
919
920         strbuf_addf(err, "A child failed with return code %d:", result);
921         for (i = 0; cp->argv[i]; i++)
922                 strbuf_addf(err, " %s", cp->argv[i]);
923
924         return 0;
925 }
926
927 static void kill_children(struct parallel_processes *pp, int signo)
928 {
929         int i, n = pp->max_processes;
930
931         for (i = 0; i < n; i++)
932                 if (pp->children[i].state == GIT_CP_WORKING)
933                         kill(pp->children[i].process.pid, signo);
934 }
935
936 static struct parallel_processes *pp_for_signal;
937
938 static void handle_children_on_signal(int signo)
939 {
940         kill_children(pp_for_signal, signo);
941         sigchain_pop(signo);
942         raise(signo);
943 }
944
945 static void pp_init(struct parallel_processes *pp,
946                     int n,
947                     get_next_task_fn get_next_task,
948                     start_failure_fn start_failure,
949                     task_finished_fn task_finished,
950                     void *data)
951 {
952         int i;
953
954         if (n < 1)
955                 n = online_cpus();
956
957         pp->max_processes = n;
958
959         trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
960
961         pp->data = data;
962         if (!get_next_task)
963                 die("BUG: you need to specify a get_next_task function");
964         pp->get_next_task = get_next_task;
965
966         pp->start_failure = start_failure ? start_failure : default_start_failure;
967         pp->task_finished = task_finished ? task_finished : default_task_finished;
968
969         pp->nr_processes = 0;
970         pp->output_owner = 0;
971         pp->shutdown = 0;
972         pp->children = xcalloc(n, sizeof(*pp->children));
973         pp->pfd = xcalloc(n, sizeof(*pp->pfd));
974         strbuf_init(&pp->buffered_output, 0);
975
976         for (i = 0; i < n; i++) {
977                 strbuf_init(&pp->children[i].err, 0);
978                 child_process_init(&pp->children[i].process);
979                 pp->pfd[i].events = POLLIN | POLLHUP;
980                 pp->pfd[i].fd = -1;
981         }
982
983         pp_for_signal = pp;
984         sigchain_push_common(handle_children_on_signal);
985 }
986
987 static void pp_cleanup(struct parallel_processes *pp)
988 {
989         int i;
990
991         trace_printf("run_processes_parallel: done");
992         for (i = 0; i < pp->max_processes; i++) {
993                 strbuf_release(&pp->children[i].err);
994                 child_process_clear(&pp->children[i].process);
995         }
996
997         free(pp->children);
998         free(pp->pfd);
999
1000         /*
1001          * When get_next_task added messages to the buffer in its last
1002          * iteration, the buffered output is non empty.
1003          */
1004         fputs(pp->buffered_output.buf, stderr);
1005         strbuf_release(&pp->buffered_output);
1006
1007         sigchain_pop_common();
1008 }
1009
1010 /* returns
1011  *  0 if a new task was started.
1012  *  1 if no new jobs was started (get_next_task ran out of work, non critical
1013  *    problem with starting a new command)
1014  * <0 no new job was started, user wishes to shutdown early. Use negative code
1015  *    to signal the children.
1016  */
1017 static int pp_start_one(struct parallel_processes *pp)
1018 {
1019         int i, code;
1020
1021         for (i = 0; i < pp->max_processes; i++)
1022                 if (pp->children[i].state == GIT_CP_FREE)
1023                         break;
1024         if (i == pp->max_processes)
1025                 die("BUG: bookkeeping is hard");
1026
1027         code = pp->get_next_task(&pp->children[i].process,
1028                                  &pp->children[i].err,
1029                                  pp->data,
1030                                  &pp->children[i].data);
1031         if (!code) {
1032                 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1033                 strbuf_reset(&pp->children[i].err);
1034                 return 1;
1035         }
1036         pp->children[i].process.err = -1;
1037         pp->children[i].process.stdout_to_stderr = 1;
1038         pp->children[i].process.no_stdin = 1;
1039
1040         if (start_command(&pp->children[i].process)) {
1041                 code = pp->start_failure(&pp->children[i].process,
1042                                          &pp->children[i].err,
1043                                          pp->data,
1044                                          &pp->children[i].data);
1045                 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1046                 strbuf_reset(&pp->children[i].err);
1047                 if (code)
1048                         pp->shutdown = 1;
1049                 return code;
1050         }
1051
1052         pp->nr_processes++;
1053         pp->children[i].state = GIT_CP_WORKING;
1054         pp->pfd[i].fd = pp->children[i].process.err;
1055         return 0;
1056 }
1057
1058 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1059 {
1060         int i;
1061
1062         while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1063                 if (errno == EINTR)
1064                         continue;
1065                 pp_cleanup(pp);
1066                 die_errno("poll");
1067         }
1068
1069         /* Buffer output from all pipes. */
1070         for (i = 0; i < pp->max_processes; i++) {
1071                 if (pp->children[i].state == GIT_CP_WORKING &&
1072                     pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1073                         int n = strbuf_read_once(&pp->children[i].err,
1074                                                  pp->children[i].process.err, 0);
1075                         if (n == 0) {
1076                                 close(pp->children[i].process.err);
1077                                 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1078                         } else if (n < 0)
1079                                 if (errno != EAGAIN)
1080                                         die_errno("read");
1081                 }
1082         }
1083 }
1084
1085 static void pp_output(struct parallel_processes *pp)
1086 {
1087         int i = pp->output_owner;
1088         if (pp->children[i].state == GIT_CP_WORKING &&
1089             pp->children[i].err.len) {
1090                 fputs(pp->children[i].err.buf, stderr);
1091                 strbuf_reset(&pp->children[i].err);
1092         }
1093 }
1094
1095 static int pp_collect_finished(struct parallel_processes *pp)
1096 {
1097         int i, code;
1098         int n = pp->max_processes;
1099         int result = 0;
1100
1101         while (pp->nr_processes > 0) {
1102                 for (i = 0; i < pp->max_processes; i++)
1103                         if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1104                                 break;
1105                 if (i == pp->max_processes)
1106                         break;
1107
1108                 code = finish_command(&pp->children[i].process);
1109
1110                 code = pp->task_finished(code, &pp->children[i].process,
1111                                          &pp->children[i].err, pp->data,
1112                                          &pp->children[i].data);
1113
1114                 if (code)
1115                         result = code;
1116                 if (code < 0)
1117                         break;
1118
1119                 pp->nr_processes--;
1120                 pp->children[i].state = GIT_CP_FREE;
1121                 pp->pfd[i].fd = -1;
1122                 child_process_init(&pp->children[i].process);
1123
1124                 if (i != pp->output_owner) {
1125                         strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1126                         strbuf_reset(&pp->children[i].err);
1127                 } else {
1128                         fputs(pp->children[i].err.buf, stderr);
1129                         strbuf_reset(&pp->children[i].err);
1130
1131                         /* Output all other finished child processes */
1132                         fputs(pp->buffered_output.buf, stderr);
1133                         strbuf_reset(&pp->buffered_output);
1134
1135                         /*
1136                          * Pick next process to output live.
1137                          * NEEDSWORK:
1138                          * For now we pick it randomly by doing a round
1139                          * robin. Later we may want to pick the one with
1140                          * the most output or the longest or shortest
1141                          * running process time.
1142                          */
1143                         for (i = 0; i < n; i++)
1144                                 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1145                                         break;
1146                         pp->output_owner = (pp->output_owner + i) % n;
1147                 }
1148         }
1149         return result;
1150 }
1151
1152 int run_processes_parallel(int n,
1153                            get_next_task_fn get_next_task,
1154                            start_failure_fn start_failure,
1155                            task_finished_fn task_finished,
1156                            void *pp_cb)
1157 {
1158         int i, code;
1159         int output_timeout = 100;
1160         int spawn_cap = 4;
1161         struct parallel_processes pp;
1162
1163         pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1164         while (1) {
1165                 for (i = 0;
1166                     i < spawn_cap && !pp.shutdown &&
1167                     pp.nr_processes < pp.max_processes;
1168                     i++) {
1169                         code = pp_start_one(&pp);
1170                         if (!code)
1171                                 continue;
1172                         if (code < 0) {
1173                                 pp.shutdown = 1;
1174                                 kill_children(&pp, -code);
1175                         }
1176                         break;
1177                 }
1178                 if (!pp.nr_processes)
1179                         break;
1180                 pp_buffer_stderr(&pp, output_timeout);
1181                 pp_output(&pp);
1182                 code = pp_collect_finished(&pp);
1183                 if (code) {
1184                         pp.shutdown = 1;
1185                         if (code < 0)
1186                                 kill_children(&pp, -code);
1187                 }
1188         }
1189
1190         pp_cleanup(&pp);
1191         return 0;
1192 }