Enable use of shell scripts as executables in mingw.
[gnulib.git] / lib / pipe.c
1 /* Creation of subprocesses, communicating via pipes.
2    Copyright (C) 2001-2004, 2006-2008 Free Software Foundation, Inc.
3    Written by Bruno Haible <haible@clisp.cons.org>, 2001.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18
19 #include <config.h>
20
21 /* Specification.  */
22 #include "pipe.h"
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <unistd.h>
29
30 #include "error.h"
31 #include "fatal-signal.h"
32 #include "unistd-safer.h"
33 #include "wait-process.h"
34 #include "gettext.h"
35
36 #define _(str) gettext (str)
37
38 #if defined _MSC_VER || defined __MINGW32__
39
40 /* Native Woe32 API.  */
41 # include <process.h>
42 # include "w32spawn.h"
43
44 #else
45
46 /* Unix API.  */
47 # if HAVE_POSIX_SPAWN
48 #  include <spawn.h>
49 # else
50 #  if HAVE_VFORK_H
51 #   include <vfork.h>
52 #  endif
53 # endif
54
55 #endif
56
57 #ifndef STDIN_FILENO
58 # define STDIN_FILENO 0
59 #endif
60 #ifndef STDOUT_FILENO
61 # define STDOUT_FILENO 1
62 #endif
63 #ifndef STDERR_FILENO
64 # define STDERR_FILENO 2
65 #endif
66
67 /* The results of open() in this file are not used with fchdir,
68    therefore save some unnecessary work in fchdir.c.  */
69 #undef open
70 #undef close
71
72
73 #ifdef EINTR
74
75 /* EINTR handling for close().
76    These functions can return -1/EINTR even though we don't have any
77    signal handlers set up, namely when we get interrupted via SIGSTOP.  */
78
79 static inline int
80 nonintr_close (int fd)
81 {
82   int retval;
83
84   do
85     retval = close (fd);
86   while (retval < 0 && errno == EINTR);
87
88   return retval;
89 }
90 #define close nonintr_close
91
92 static inline int
93 nonintr_open (const char *pathname, int oflag, mode_t mode)
94 {
95   int retval;
96
97   do
98     retval = open (pathname, oflag, mode);
99   while (retval < 0 && errno == EINTR);
100
101   return retval;
102 }
103 #undef open /* avoid warning on VMS */
104 #define open nonintr_open
105
106 #endif
107
108
109 /* Open a pipe connected to a child process.
110  *
111  *           write       system                read
112  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child       if pipe_stdin
113  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child       if pipe_stdout
114  *           read        system                write
115  *
116  * At least one of pipe_stdin, pipe_stdout must be true.
117  * pipe_stdin and prog_stdin together determine the child's standard input.
118  * pipe_stdout and prog_stdout together determine the child's standard output.
119  * If pipe_stdin is true, prog_stdin is ignored.
120  * If pipe_stdout is true, prog_stdout is ignored.
121  */
122 static pid_t
123 create_pipe (const char *progname,
124              const char *prog_path, char **prog_argv,
125              bool pipe_stdin, bool pipe_stdout,
126              const char *prog_stdin, const char *prog_stdout,
127              bool null_stderr,
128              bool slave_process, bool exit_on_error,
129              int fd[2])
130 {
131 #if defined _MSC_VER || defined __MINGW32__
132
133   /* Native Woe32 API.
134      This uses _pipe(), dup2(), and spawnv().  It could also be implemented
135      using the low-level functions CreatePipe(), DuplicateHandle(),
136      CreateProcess() and _open_osfhandle(); see the GNU make and GNU clisp
137      and cvs source code.  */
138   int ifd[2];
139   int ofd[2];
140   int orig_stdin;
141   int orig_stdout;
142   int orig_stderr;
143   int child;
144   int nulloutfd;
145   int stdinfd;
146   int stdoutfd;
147
148   /* FIXME: Need to free memory allocated by prepare_spawn.  */
149   prog_argv = prepare_spawn (prog_argv);
150
151   if (pipe_stdout)
152     if (_pipe (ifd, 4096, O_BINARY | O_NOINHERIT) < 0
153         || (ifd[0] = fd_safer (ifd[0])) < 0)
154       error (EXIT_FAILURE, errno, _("cannot create pipe"));
155   if (pipe_stdin)
156     if (_pipe (ofd, 4096, O_BINARY | O_NOINHERIT) < 0
157         || (ofd[1] = fd_safer (ofd[1])) < 0)
158       error (EXIT_FAILURE, errno, _("cannot create pipe"));
159 /* Data flow diagram:
160  *
161  *           write        system         read
162  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
163  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
164  *           read         system         write
165  *
166  */
167
168   /* Save standard file handles of parent process.  */
169   if (pipe_stdin || prog_stdin != NULL)
170     orig_stdin = dup_noinherit (STDIN_FILENO);
171   if (pipe_stdout || prog_stdout != NULL)
172     orig_stdout = dup_noinherit (STDOUT_FILENO);
173   if (null_stderr)
174     orig_stderr = dup_noinherit (STDERR_FILENO);
175   child = -1;
176
177   /* Create standard file handles of child process.  */
178   nulloutfd = -1;
179   stdinfd = -1;
180   stdoutfd = -1;
181   if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
182       && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
183       && (!null_stderr
184           || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
185               && (nulloutfd == STDERR_FILENO
186                   || (dup2 (nulloutfd, STDERR_FILENO) >= 0
187                       && close (nulloutfd) >= 0))))
188       && (pipe_stdin
189           || prog_stdin == NULL
190           || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
191               && (stdinfd == STDIN_FILENO
192                   || (dup2 (stdinfd, STDIN_FILENO) >= 0
193                       && close (stdinfd) >= 0))))
194       && (pipe_stdout
195           || prog_stdout == NULL
196           || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
197               && (stdoutfd == STDOUT_FILENO
198                   || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
199                       && close (stdoutfd) >= 0)))))
200     /* The child process doesn't inherit ifd[0], ifd[1], ofd[0], ofd[1],
201        but it inherits all open()ed or dup2()ed file handles (which is what
202        we want in the case of STD*_FILENO) and also orig_stdin,
203        orig_stdout, orig_stderr (which is not explicitly wanted but
204        harmless).  */
205     {
206       child = spawnvp (P_NOWAIT, prog_path, prog_argv);
207       if (child < 0 && errno == ENOEXEC)
208         {
209           /* prog is not an native executable.  Try to execute it as a
210              shell script.  Note that prepare_spawn() has already prepended
211              a hidden element "sh.exe" to prog_argv.  */
212           --prog_argv;
213           child = spawnvp (P_NOWAIT, prog_argv[0], prog_argv);
214         }
215     }
216   if (stdinfd >= 0)
217     close (stdinfd);
218   if (stdoutfd >= 0)
219     close (stdoutfd);
220   if (nulloutfd >= 0)
221     close (nulloutfd);
222
223   /* Restore standard file handles of parent process.  */
224   if (null_stderr)
225     dup2 (orig_stderr, STDERR_FILENO), close (orig_stderr);
226   if (pipe_stdout || prog_stdout != NULL)
227     dup2 (orig_stdout, STDOUT_FILENO), close (orig_stdout);
228   if (pipe_stdin || prog_stdin != NULL)
229     dup2 (orig_stdin, STDIN_FILENO), close (orig_stdin);
230
231   if (pipe_stdin)
232     close (ofd[0]);
233   if (pipe_stdout)
234     close (ifd[1]);
235   if (child == -1)
236     {
237       if (exit_on_error || !null_stderr)
238         error (exit_on_error ? EXIT_FAILURE : 0, errno,
239                _("%s subprocess failed"), progname);
240       if (pipe_stdout)
241         close (ifd[0]);
242       if (pipe_stdin)
243         close (ofd[1]);
244       return -1;
245     }
246
247   if (pipe_stdout)
248     fd[0] = ifd[0];
249   if (pipe_stdin)
250     fd[1] = ofd[1];
251   return child;
252
253 #else
254
255   /* Unix API.  */
256   int ifd[2];
257   int ofd[2];
258 # if HAVE_POSIX_SPAWN
259   sigset_t blocked_signals;
260   posix_spawn_file_actions_t actions;
261   bool actions_allocated;
262   posix_spawnattr_t attrs;
263   bool attrs_allocated;
264   int err;
265   pid_t child;
266 # else
267   int child;
268 # endif
269
270   if (pipe_stdout)
271     if (pipe (ifd) < 0
272         || (ifd[0] = fd_safer (ifd[0])) < 0)
273       error (EXIT_FAILURE, errno, _("cannot create pipe"));
274   if (pipe_stdin)
275     if (pipe (ofd) < 0
276         || (ofd[1] = fd_safer (ofd[1])) < 0)
277       error (EXIT_FAILURE, errno, _("cannot create pipe"));
278 /* Data flow diagram:
279  *
280  *           write        system         read
281  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
282  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
283  *           read         system         write
284  *
285  */
286
287 # if HAVE_POSIX_SPAWN
288   if (slave_process)
289     {
290       sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
291       block_fatal_signals ();
292     }
293   actions_allocated = false;
294   attrs_allocated = false;
295   if ((err = posix_spawn_file_actions_init (&actions)) != 0
296       || (actions_allocated = true,
297           (pipe_stdin
298            && (err = posix_spawn_file_actions_adddup2 (&actions,
299                                                        ofd[0], STDIN_FILENO))
300               != 0)
301           || (pipe_stdout
302               && (err = posix_spawn_file_actions_adddup2 (&actions,
303                                                           ifd[1], STDOUT_FILENO))
304                  != 0)
305           || (pipe_stdin
306               && (err = posix_spawn_file_actions_addclose (&actions, ofd[0]))
307                  != 0)
308           || (pipe_stdout
309               && (err = posix_spawn_file_actions_addclose (&actions, ifd[1]))
310                  != 0)
311           || (pipe_stdin
312               && (err = posix_spawn_file_actions_addclose (&actions, ofd[1]))
313                  != 0)
314           || (pipe_stdout
315               && (err = posix_spawn_file_actions_addclose (&actions, ifd[0]))
316                  != 0)
317           || (null_stderr
318               && (err = posix_spawn_file_actions_addopen (&actions,
319                                                           STDERR_FILENO,
320                                                           "/dev/null", O_RDWR,
321                                                           0))
322                  != 0)
323           || (!pipe_stdin
324               && prog_stdin != NULL
325               && (err = posix_spawn_file_actions_addopen (&actions,
326                                                           STDIN_FILENO,
327                                                           prog_stdin, O_RDONLY,
328                                                           0))
329                  != 0)
330           || (!pipe_stdout
331               && prog_stdout != NULL
332               && (err = posix_spawn_file_actions_addopen (&actions,
333                                                           STDOUT_FILENO,
334                                                           prog_stdout, O_WRONLY,
335                                                           0))
336                  != 0)
337           || (slave_process
338               && ((err = posix_spawnattr_init (&attrs)) != 0
339                   || (attrs_allocated = true,
340                       (err = posix_spawnattr_setsigmask (&attrs,
341                                                          &blocked_signals))
342                       != 0
343                       || (err = posix_spawnattr_setflags (&attrs,
344                                                         POSIX_SPAWN_SETSIGMASK))
345                          != 0)))
346           || (err = posix_spawnp (&child, prog_path, &actions,
347                                   attrs_allocated ? &attrs : NULL, prog_argv,
348                                   environ))
349              != 0))
350     {
351       if (actions_allocated)
352         posix_spawn_file_actions_destroy (&actions);
353       if (attrs_allocated)
354         posix_spawnattr_destroy (&attrs);
355       if (slave_process)
356         unblock_fatal_signals ();
357       if (exit_on_error || !null_stderr)
358         error (exit_on_error ? EXIT_FAILURE : 0, err,
359                _("%s subprocess failed"), progname);
360       if (pipe_stdout)
361         {
362           close (ifd[0]);
363           close (ifd[1]);
364         }
365       if (pipe_stdin)
366         {
367           close (ofd[0]);
368           close (ofd[1]);
369         }
370       return -1;
371     }
372   posix_spawn_file_actions_destroy (&actions);
373   if (attrs_allocated)
374     posix_spawnattr_destroy (&attrs);
375 # else
376   if (slave_process)
377     block_fatal_signals ();
378   /* Use vfork() instead of fork() for efficiency.  */
379   if ((child = vfork ()) == 0)
380     {
381       /* Child process code.  */
382       int nulloutfd;
383       int stdinfd;
384       int stdoutfd;
385
386       if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
387           && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
388           && (!pipe_stdin || close (ofd[0]) >= 0)
389           && (!pipe_stdout || close (ifd[1]) >= 0)
390           && (!pipe_stdin || close (ofd[1]) >= 0)
391           && (!pipe_stdout || close (ifd[0]) >= 0)
392           && (!null_stderr
393               || ((nulloutfd = open ("/dev/null", O_RDWR, 0)) >= 0
394                   && (nulloutfd == STDERR_FILENO
395                       || (dup2 (nulloutfd, STDERR_FILENO) >= 0
396                           && close (nulloutfd) >= 0))))
397           && (pipe_stdin
398               || prog_stdin == NULL
399               || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
400                   && (stdinfd == STDIN_FILENO
401                       || (dup2 (stdinfd, STDIN_FILENO) >= 0
402                           && close (stdinfd) >= 0))))
403           && (pipe_stdout
404               || prog_stdout == NULL
405               || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
406                   && (stdoutfd == STDOUT_FILENO
407                       || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
408                           && close (stdoutfd) >= 0))))
409           && (!slave_process || (unblock_fatal_signals (), true)))
410         execvp (prog_path, prog_argv);
411       _exit (127);
412     }
413   if (child == -1)
414     {
415       if (slave_process)
416         unblock_fatal_signals ();
417       if (exit_on_error || !null_stderr)
418         error (exit_on_error ? EXIT_FAILURE : 0, errno,
419                _("%s subprocess failed"), progname);
420       if (pipe_stdout)
421         {
422           close (ifd[0]);
423           close (ifd[1]);
424         }
425       if (pipe_stdin)
426         {
427           close (ofd[0]);
428           close (ofd[1]);
429         }
430       return -1;
431     }
432 # endif
433   if (slave_process)
434     {
435       register_slave_subprocess (child);
436       unblock_fatal_signals ();
437     }
438   if (pipe_stdin)
439     close (ofd[0]);
440   if (pipe_stdout)
441     close (ifd[1]);
442
443   if (pipe_stdout)
444     fd[0] = ifd[0];
445   if (pipe_stdin)
446     fd[1] = ofd[1];
447   return child;
448
449 #endif
450 }
451
452 /* Open a bidirectional pipe.
453  *
454  *           write       system                read
455  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child
456  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
457  *           read        system                write
458  *
459  */
460 pid_t
461 create_pipe_bidi (const char *progname,
462                   const char *prog_path, char **prog_argv,
463                   bool null_stderr,
464                   bool slave_process, bool exit_on_error,
465                   int fd[2])
466 {
467   pid_t result = create_pipe (progname, prog_path, prog_argv,
468                               true, true, NULL, NULL,
469                               null_stderr, slave_process, exit_on_error,
470                               fd);
471   return result;
472 }
473
474 /* Open a pipe for input from a child process.
475  * The child's stdin comes from a file.
476  *
477  *           read        system                write
478  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
479  *
480  */
481 pid_t
482 create_pipe_in (const char *progname,
483                 const char *prog_path, char **prog_argv,
484                 const char *prog_stdin, bool null_stderr,
485                 bool slave_process, bool exit_on_error,
486                 int fd[1])
487 {
488   int iofd[2];
489   pid_t result = create_pipe (progname, prog_path, prog_argv,
490                               false, true, prog_stdin, NULL,
491                               null_stderr, slave_process, exit_on_error,
492                               iofd);
493   if (result != -1)
494     fd[0] = iofd[0];
495   return result;
496 }
497
498 /* Open a pipe for output to a child process.
499  * The child's stdout goes to a file.
500  *
501  *           write       system                read
502  *    parent  ->   fd[0]   ->   STDIN_FILENO    ->   child
503  *
504  */
505 pid_t
506 create_pipe_out (const char *progname,
507                  const char *prog_path, char **prog_argv,
508                  const char *prog_stdout, bool null_stderr,
509                  bool slave_process, bool exit_on_error,
510                  int fd[1])
511 {
512   int iofd[2];
513   pid_t result = create_pipe (progname, prog_path, prog_argv,
514                               true, false, NULL, prog_stdout,
515                               null_stderr, slave_process, exit_on_error,
516                               iofd);
517   if (result != -1)
518     fd[0] = iofd[1];
519   return result;
520 }