run-command.c: fix broken list iteration in clear_child_for_cleanup
[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
7 struct child_to_clean {
8         pid_t pid;
9         struct child_to_clean *next;
10 };
11 static struct child_to_clean *children_to_clean;
12 static int installed_child_cleanup_handler;
13
14 static void cleanup_children(int sig)
15 {
16         while (children_to_clean) {
17                 struct child_to_clean *p = children_to_clean;
18                 children_to_clean = p->next;
19                 kill(p->pid, sig);
20                 free(p);
21         }
22 }
23
24 static void cleanup_children_on_signal(int sig)
25 {
26         cleanup_children(sig);
27         sigchain_pop(sig);
28         raise(sig);
29 }
30
31 static void cleanup_children_on_exit(void)
32 {
33         cleanup_children(SIGTERM);
34 }
35
36 static void mark_child_for_cleanup(pid_t pid)
37 {
38         struct child_to_clean *p = xmalloc(sizeof(*p));
39         p->pid = pid;
40         p->next = children_to_clean;
41         children_to_clean = p;
42
43         if (!installed_child_cleanup_handler) {
44                 atexit(cleanup_children_on_exit);
45                 sigchain_push_common(cleanup_children_on_signal);
46                 installed_child_cleanup_handler = 1;
47         }
48 }
49
50 static void clear_child_for_cleanup(pid_t pid)
51 {
52         struct child_to_clean **pp;
53
54         for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
55                 struct child_to_clean *clean_me = *pp;
56
57                 if (clean_me->pid == pid) {
58                         *pp = clean_me->next;
59                         free(clean_me);
60                         return;
61                 }
62         }
63 }
64
65 static inline void close_pair(int fd[2])
66 {
67         close(fd[0]);
68         close(fd[1]);
69 }
70
71 #ifndef WIN32
72 static inline void dup_devnull(int to)
73 {
74         int fd = open("/dev/null", O_RDWR);
75         dup2(fd, to);
76         close(fd);
77 }
78 #endif
79
80 static const char **prepare_shell_cmd(const char **argv)
81 {
82         int argc, nargc = 0;
83         const char **nargv;
84
85         for (argc = 0; argv[argc]; argc++)
86                 ; /* just counting */
87         /* +1 for NULL, +3 for "sh -c" plus extra $0 */
88         nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
89
90         if (argc < 1)
91                 die("BUG: shell command is empty");
92
93         if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
94                 nargv[nargc++] = "sh";
95                 nargv[nargc++] = "-c";
96
97                 if (argc < 2)
98                         nargv[nargc++] = argv[0];
99                 else {
100                         struct strbuf arg0 = STRBUF_INIT;
101                         strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
102                         nargv[nargc++] = strbuf_detach(&arg0, NULL);
103                 }
104         }
105
106         for (argc = 0; argv[argc]; argc++)
107                 nargv[nargc++] = argv[argc];
108         nargv[nargc] = NULL;
109
110         return nargv;
111 }
112
113 #ifndef WIN32
114 static int execv_shell_cmd(const char **argv)
115 {
116         const char **nargv = prepare_shell_cmd(argv);
117         trace_argv_printf(nargv, "trace: exec:");
118         execvp(nargv[0], (char **)nargv);
119         free(nargv);
120         return -1;
121 }
122 #endif
123
124 #ifndef WIN32
125 static int child_err = 2;
126 static int child_notifier = -1;
127
128 static void notify_parent(void)
129 {
130         /*
131          * execvp failed.  If possible, we'd like to let start_command
132          * know, so failures like ENOENT can be handled right away; but
133          * otherwise, finish_command will still report the error.
134          */
135         xwrite(child_notifier, "", 1);
136 }
137
138 static NORETURN void die_child(const char *err, va_list params)
139 {
140         vwritef(child_err, "fatal: ", err, params);
141         exit(128);
142 }
143
144 static void error_child(const char *err, va_list params)
145 {
146         vwritef(child_err, "error: ", err, params);
147 }
148 #endif
149
150 static inline void set_cloexec(int fd)
151 {
152         int flags = fcntl(fd, F_GETFD);
153         if (flags >= 0)
154                 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
155 }
156
157 static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
158 {
159         int status, code = -1;
160         pid_t waiting;
161         int failed_errno = 0;
162
163         while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
164                 ;       /* nothing */
165
166         if (waiting < 0) {
167                 failed_errno = errno;
168                 error("waitpid for %s failed: %s", argv0, strerror(errno));
169         } else if (waiting != pid) {
170                 error("waitpid is confused (%s)", argv0);
171         } else if (WIFSIGNALED(status)) {
172                 code = WTERMSIG(status);
173                 error("%s died of signal %d", argv0, code);
174                 /*
175                  * This return value is chosen so that code & 0xff
176                  * mimics the exit code that a POSIX shell would report for
177                  * a program that died from this signal.
178                  */
179                 code -= 128;
180         } else if (WIFEXITED(status)) {
181                 code = WEXITSTATUS(status);
182                 /*
183                  * Convert special exit code when execvp failed.
184                  */
185                 if (code == 127) {
186                         code = -1;
187                         failed_errno = ENOENT;
188                 }
189         } else {
190                 error("waitpid is confused (%s)", argv0);
191         }
192
193         clear_child_for_cleanup(pid);
194
195         errno = failed_errno;
196         return code;
197 }
198
199 int start_command(struct child_process *cmd)
200 {
201         int need_in, need_out, need_err;
202         int fdin[2], fdout[2], fderr[2];
203         int failed_errno = failed_errno;
204
205         /*
206          * In case of errors we must keep the promise to close FDs
207          * that have been passed in via ->in and ->out.
208          */
209
210         need_in = !cmd->no_stdin && cmd->in < 0;
211         if (need_in) {
212                 if (pipe(fdin) < 0) {
213                         failed_errno = errno;
214                         if (cmd->out > 0)
215                                 close(cmd->out);
216                         goto fail_pipe;
217                 }
218                 cmd->in = fdin[1];
219         }
220
221         need_out = !cmd->no_stdout
222                 && !cmd->stdout_to_stderr
223                 && cmd->out < 0;
224         if (need_out) {
225                 if (pipe(fdout) < 0) {
226                         failed_errno = errno;
227                         if (need_in)
228                                 close_pair(fdin);
229                         else if (cmd->in)
230                                 close(cmd->in);
231                         goto fail_pipe;
232                 }
233                 cmd->out = fdout[0];
234         }
235
236         need_err = !cmd->no_stderr && cmd->err < 0;
237         if (need_err) {
238                 if (pipe(fderr) < 0) {
239                         failed_errno = errno;
240                         if (need_in)
241                                 close_pair(fdin);
242                         else if (cmd->in)
243                                 close(cmd->in);
244                         if (need_out)
245                                 close_pair(fdout);
246                         else if (cmd->out)
247                                 close(cmd->out);
248 fail_pipe:
249                         error("cannot create pipe for %s: %s",
250                                 cmd->argv[0], strerror(failed_errno));
251                         errno = failed_errno;
252                         return -1;
253                 }
254                 cmd->err = fderr[0];
255         }
256
257         trace_argv_printf(cmd->argv, "trace: run_command:");
258         fflush(NULL);
259
260 #ifndef WIN32
261 {
262         int notify_pipe[2];
263         if (pipe(notify_pipe))
264                 notify_pipe[0] = notify_pipe[1] = -1;
265
266         cmd->pid = fork();
267         if (!cmd->pid) {
268                 /*
269                  * Redirect the channel to write syscall error messages to
270                  * before redirecting the process's stderr so that all die()
271                  * in subsequent call paths use the parent's stderr.
272                  */
273                 if (cmd->no_stderr || need_err) {
274                         child_err = dup(2);
275                         set_cloexec(child_err);
276                 }
277                 set_die_routine(die_child);
278                 set_error_routine(error_child);
279
280                 close(notify_pipe[0]);
281                 set_cloexec(notify_pipe[1]);
282                 child_notifier = notify_pipe[1];
283                 atexit(notify_parent);
284
285                 if (cmd->no_stdin)
286                         dup_devnull(0);
287                 else if (need_in) {
288                         dup2(fdin[0], 0);
289                         close_pair(fdin);
290                 } else if (cmd->in) {
291                         dup2(cmd->in, 0);
292                         close(cmd->in);
293                 }
294
295                 if (cmd->no_stderr)
296                         dup_devnull(2);
297                 else if (need_err) {
298                         dup2(fderr[1], 2);
299                         close_pair(fderr);
300                 } else if (cmd->err > 1) {
301                         dup2(cmd->err, 2);
302                         close(cmd->err);
303                 }
304
305                 if (cmd->no_stdout)
306                         dup_devnull(1);
307                 else if (cmd->stdout_to_stderr)
308                         dup2(2, 1);
309                 else if (need_out) {
310                         dup2(fdout[1], 1);
311                         close_pair(fdout);
312                 } else if (cmd->out > 1) {
313                         dup2(cmd->out, 1);
314                         close(cmd->out);
315                 }
316
317                 if (cmd->dir && chdir(cmd->dir))
318                         die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
319                             cmd->dir);
320                 if (cmd->env) {
321                         for (; *cmd->env; cmd->env++) {
322                                 if (strchr(*cmd->env, '='))
323                                         putenv((char *)*cmd->env);
324                                 else
325                                         unsetenv(*cmd->env);
326                         }
327                 }
328                 if (cmd->preexec_cb) {
329                         /*
330                          * We cannot predict what the pre-exec callback does.
331                          * Forgo parent notification.
332                          */
333                         close(child_notifier);
334                         child_notifier = -1;
335
336                         cmd->preexec_cb();
337                 }
338                 if (cmd->git_cmd) {
339                         execv_git_cmd(cmd->argv);
340                 } else if (cmd->use_shell) {
341                         execv_shell_cmd(cmd->argv);
342                 } else {
343                         execvp(cmd->argv[0], (char *const*) cmd->argv);
344                 }
345                 if (errno == ENOENT) {
346                         if (!cmd->silent_exec_failure)
347                                 error("cannot run %s: %s", cmd->argv[0],
348                                         strerror(ENOENT));
349                         exit(127);
350                 } else {
351                         die_errno("cannot exec '%s'", cmd->argv[0]);
352                 }
353         }
354         if (cmd->pid < 0)
355                 error("cannot fork() for %s: %s", cmd->argv[0],
356                         strerror(failed_errno = errno));
357         else if (cmd->clean_on_exit)
358                 mark_child_for_cleanup(cmd->pid);
359
360         /*
361          * Wait for child's execvp. If the execvp succeeds (or if fork()
362          * failed), EOF is seen immediately by the parent. Otherwise, the
363          * child process sends a single byte.
364          * Note that use of this infrastructure is completely advisory,
365          * therefore, we keep error checks minimal.
366          */
367         close(notify_pipe[1]);
368         if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
369                 /*
370                  * At this point we know that fork() succeeded, but execvp()
371                  * failed. Errors have been reported to our stderr.
372                  */
373                 wait_or_whine(cmd->pid, cmd->argv[0],
374                               cmd->silent_exec_failure);
375                 failed_errno = errno;
376                 cmd->pid = -1;
377         }
378         close(notify_pipe[0]);
379
380 }
381 #else
382 {
383         int fhin = 0, fhout = 1, fherr = 2;
384         const char **sargv = cmd->argv;
385         char **env = environ;
386
387         if (cmd->no_stdin)
388                 fhin = open("/dev/null", O_RDWR);
389         else if (need_in)
390                 fhin = dup(fdin[0]);
391         else if (cmd->in)
392                 fhin = dup(cmd->in);
393
394         if (cmd->no_stderr)
395                 fherr = open("/dev/null", O_RDWR);
396         else if (need_err)
397                 fherr = dup(fderr[1]);
398         else if (cmd->err > 2)
399                 fherr = dup(cmd->err);
400
401         if (cmd->no_stdout)
402                 fhout = open("/dev/null", O_RDWR);
403         else if (cmd->stdout_to_stderr)
404                 fhout = dup(fherr);
405         else if (need_out)
406                 fhout = dup(fdout[1]);
407         else if (cmd->out > 1)
408                 fhout = dup(cmd->out);
409
410         if (cmd->env)
411                 env = make_augmented_environ(cmd->env);
412
413         if (cmd->git_cmd) {
414                 cmd->argv = prepare_git_cmd(cmd->argv);
415         } else if (cmd->use_shell) {
416                 cmd->argv = prepare_shell_cmd(cmd->argv);
417         }
418
419         cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
420                                   fhin, fhout, fherr);
421         failed_errno = errno;
422         if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
423                 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
424         if (cmd->clean_on_exit && cmd->pid >= 0)
425                 mark_child_for_cleanup(cmd->pid);
426
427         if (cmd->env)
428                 free_environ(env);
429         if (cmd->git_cmd)
430                 free(cmd->argv);
431
432         cmd->argv = sargv;
433         if (fhin != 0)
434                 close(fhin);
435         if (fhout != 1)
436                 close(fhout);
437         if (fherr != 2)
438                 close(fherr);
439 }
440 #endif
441
442         if (cmd->pid < 0) {
443                 if (need_in)
444                         close_pair(fdin);
445                 else if (cmd->in)
446                         close(cmd->in);
447                 if (need_out)
448                         close_pair(fdout);
449                 else if (cmd->out)
450                         close(cmd->out);
451                 if (need_err)
452                         close_pair(fderr);
453                 else if (cmd->err)
454                         close(cmd->err);
455                 errno = failed_errno;
456                 return -1;
457         }
458
459         if (need_in)
460                 close(fdin[0]);
461         else if (cmd->in)
462                 close(cmd->in);
463
464         if (need_out)
465                 close(fdout[1]);
466         else if (cmd->out)
467                 close(cmd->out);
468
469         if (need_err)
470                 close(fderr[1]);
471         else if (cmd->err)
472                 close(cmd->err);
473
474         return 0;
475 }
476
477 int finish_command(struct child_process *cmd)
478 {
479         return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
480 }
481
482 int run_command(struct child_process *cmd)
483 {
484         int code = start_command(cmd);
485         if (code)
486                 return code;
487         return finish_command(cmd);
488 }
489
490 static void prepare_run_command_v_opt(struct child_process *cmd,
491                                       const char **argv,
492                                       int opt)
493 {
494         memset(cmd, 0, sizeof(*cmd));
495         cmd->argv = argv;
496         cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
497         cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
498         cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
499         cmd->silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
500         cmd->use_shell = opt & RUN_USING_SHELL ? 1 : 0;
501 }
502
503 int run_command_v_opt(const char **argv, int opt)
504 {
505         struct child_process cmd;
506         prepare_run_command_v_opt(&cmd, argv, opt);
507         return run_command(&cmd);
508 }
509
510 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
511 {
512         struct child_process cmd;
513         prepare_run_command_v_opt(&cmd, argv, opt);
514         cmd.dir = dir;
515         cmd.env = env;
516         return run_command(&cmd);
517 }
518
519 #ifndef NO_PTHREADS
520 static pthread_t main_thread;
521 static int main_thread_set;
522 static pthread_key_t async_key;
523
524 static void *run_thread(void *data)
525 {
526         struct async *async = data;
527         intptr_t ret;
528
529         pthread_setspecific(async_key, async);
530         ret = async->proc(async->proc_in, async->proc_out, async->data);
531         return (void *)ret;
532 }
533
534 static NORETURN void die_async(const char *err, va_list params)
535 {
536         vreportf("fatal: ", err, params);
537
538         if (!pthread_equal(main_thread, pthread_self())) {
539                 struct async *async = pthread_getspecific(async_key);
540                 if (async->proc_in >= 0)
541                         close(async->proc_in);
542                 if (async->proc_out >= 0)
543                         close(async->proc_out);
544                 pthread_exit((void *)128);
545         }
546
547         exit(128);
548 }
549 #endif
550
551 int start_async(struct async *async)
552 {
553         int need_in, need_out;
554         int fdin[2], fdout[2];
555         int proc_in, proc_out;
556
557         need_in = async->in < 0;
558         if (need_in) {
559                 if (pipe(fdin) < 0) {
560                         if (async->out > 0)
561                                 close(async->out);
562                         return error("cannot create pipe: %s", strerror(errno));
563                 }
564                 async->in = fdin[1];
565         }
566
567         need_out = async->out < 0;
568         if (need_out) {
569                 if (pipe(fdout) < 0) {
570                         if (need_in)
571                                 close_pair(fdin);
572                         else if (async->in)
573                                 close(async->in);
574                         return error("cannot create pipe: %s", strerror(errno));
575                 }
576                 async->out = fdout[0];
577         }
578
579         if (need_in)
580                 proc_in = fdin[0];
581         else if (async->in)
582                 proc_in = async->in;
583         else
584                 proc_in = -1;
585
586         if (need_out)
587                 proc_out = fdout[1];
588         else if (async->out)
589                 proc_out = async->out;
590         else
591                 proc_out = -1;
592
593 #ifdef NO_PTHREADS
594         /* Flush stdio before fork() to avoid cloning buffers */
595         fflush(NULL);
596
597         async->pid = fork();
598         if (async->pid < 0) {
599                 error("fork (async) failed: %s", strerror(errno));
600                 goto error;
601         }
602         if (!async->pid) {
603                 if (need_in)
604                         close(fdin[1]);
605                 if (need_out)
606                         close(fdout[0]);
607                 exit(!!async->proc(proc_in, proc_out, async->data));
608         }
609
610         mark_child_for_cleanup(async->pid);
611
612         if (need_in)
613                 close(fdin[0]);
614         else if (async->in)
615                 close(async->in);
616
617         if (need_out)
618                 close(fdout[1]);
619         else if (async->out)
620                 close(async->out);
621 #else
622         if (!main_thread_set) {
623                 /*
624                  * We assume that the first time that start_async is called
625                  * it is from the main thread.
626                  */
627                 main_thread_set = 1;
628                 main_thread = pthread_self();
629                 pthread_key_create(&async_key, NULL);
630                 set_die_routine(die_async);
631         }
632
633         if (proc_in >= 0)
634                 set_cloexec(proc_in);
635         if (proc_out >= 0)
636                 set_cloexec(proc_out);
637         async->proc_in = proc_in;
638         async->proc_out = proc_out;
639         {
640                 int err = pthread_create(&async->tid, NULL, run_thread, async);
641                 if (err) {
642                         error("cannot create thread: %s", strerror(err));
643                         goto error;
644                 }
645         }
646 #endif
647         return 0;
648
649 error:
650         if (need_in)
651                 close_pair(fdin);
652         else if (async->in)
653                 close(async->in);
654
655         if (need_out)
656                 close_pair(fdout);
657         else if (async->out)
658                 close(async->out);
659         return -1;
660 }
661
662 int finish_async(struct async *async)
663 {
664 #ifdef NO_PTHREADS
665         return wait_or_whine(async->pid, "child process", 0);
666 #else
667         void *ret = (void *)(intptr_t)(-1);
668
669         if (pthread_join(async->tid, &ret))
670                 error("pthread_join failed");
671         return (int)(intptr_t)ret;
672 #endif
673 }
674
675 int run_hook(const char *index_file, const char *name, ...)
676 {
677         struct child_process hook;
678         struct argv_array argv = ARGV_ARRAY_INIT;
679         const char *p, *env[2];
680         char index[PATH_MAX];
681         va_list args;
682         int ret;
683
684         if (access(git_path("hooks/%s", name), X_OK) < 0)
685                 return 0;
686
687         va_start(args, name);
688         argv_array_push(&argv, git_path("hooks/%s", name));
689         while ((p = va_arg(args, const char *)))
690                 argv_array_push(&argv, p);
691         va_end(args);
692
693         memset(&hook, 0, sizeof(hook));
694         hook.argv = argv.argv;
695         hook.no_stdin = 1;
696         hook.stdout_to_stderr = 1;
697         if (index_file) {
698                 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
699                 env[0] = index;
700                 env[1] = NULL;
701                 hook.env = env;
702         }
703
704         ret = run_command(&hook);
705         argv_array_clear(&argv);
706         return ret;
707 }