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