cf547fe9a1379c62c99e5286eaca17ee2cc958db
[gnulib.git] / lib / execute.c
1 /* Creation of autonomous subprocesses.
2    Copyright (C) 2001-2004, 2006-2013 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 "execute.h"
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdbool.h>
27 #include <stdlib.h>
28 #include <signal.h>
29 #include <unistd.h>
30
31 #include "error.h"
32 #include "fatal-signal.h"
33 #include "wait-process.h"
34 #include "gettext.h"
35
36 #define _(str) gettext (str)
37
38 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
39
40 /* Native Windows API.  */
41 # include <process.h>
42 # include "w32spawn.h"
43
44 #else
45
46 /* Unix API.  */
47 # include <spawn.h>
48
49 #endif
50
51 /* The results of open() in this file are not used with fchdir,
52    therefore save some unnecessary work in fchdir.c.  */
53 #undef open
54 #undef close
55
56
57 /* Execute a command, optionally redirecting any of the three standard file
58    descriptors to /dev/null.  Return its exit code.
59    If it didn't terminate correctly, exit if exit_on_error is true, otherwise
60    return 127.
61    If slave_process is true, the child process will be terminated when its
62    creator receives a catchable fatal signal.  */
63 int
64 execute (const char *progname,
65          const char *prog_path, char **prog_argv,
66          bool ignore_sigpipe,
67          bool null_stdin, bool null_stdout, bool null_stderr,
68          bool slave_process, bool exit_on_error,
69          int *termsigp)
70 {
71 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
72
73   /* Native Windows API.  */
74   int orig_stdin;
75   int orig_stdout;
76   int orig_stderr;
77   int exitcode;
78   int nullinfd;
79   int nulloutfd;
80
81   /* FIXME: Need to free memory allocated by prepare_spawn.  */
82   prog_argv = prepare_spawn (prog_argv);
83
84   /* Save standard file handles of parent process.  */
85   if (null_stdin)
86     orig_stdin = dup_safer_noinherit (STDIN_FILENO);
87   if (null_stdout)
88     orig_stdout = dup_safer_noinherit (STDOUT_FILENO);
89   if (null_stderr)
90     orig_stderr = dup_safer_noinherit (STDERR_FILENO);
91   exitcode = -1;
92
93   /* Create standard file handles of child process.  */
94   nullinfd = -1;
95   nulloutfd = -1;
96   if ((!null_stdin
97        || ((nullinfd = open ("NUL", O_RDONLY, 0)) >= 0
98            && (nullinfd == STDIN_FILENO
99                || (dup2 (nullinfd, STDIN_FILENO) >= 0
100                    && close (nullinfd) >= 0))))
101       && (!(null_stdout || null_stderr)
102           || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
103               && (!null_stdout
104                   || nulloutfd == STDOUT_FILENO
105                   || dup2 (nulloutfd, STDOUT_FILENO) >= 0)
106               && (!null_stderr
107                   || nulloutfd == STDERR_FILENO
108                   || dup2 (nulloutfd, STDERR_FILENO) >= 0)
109               && ((null_stdout && nulloutfd == STDOUT_FILENO)
110                   || (null_stderr && nulloutfd == STDERR_FILENO)
111                   || close (nulloutfd) >= 0))))
112     /* Use spawnvpe and pass the environment explicitly.  This is needed if
113        the program has modified the environment using putenv() or [un]setenv().
114        On Windows, programs have two environments, one in the "environment
115        block" of the process and managed through SetEnvironmentVariable(), and
116        one inside the process, in the location retrieved by the 'environ'
117        macro.  When using spawnvp() without 'e', the child process inherits a
118        copy of the environment block - ignoring the effects of putenv() and
119        [un]setenv().  */
120     {
121       exitcode = spawnvpe (P_WAIT, prog_path, (const char **) prog_argv,
122                            (const char **) environ);
123       if (exitcode < 0 && errno == ENOEXEC)
124         {
125           /* prog is not a native executable.  Try to execute it as a
126              shell script.  Note that prepare_spawn() has already prepended
127              a hidden element "sh.exe" to prog_argv.  */
128           --prog_argv;
129           exitcode = spawnvpe (P_WAIT, prog_argv[0], (const char **) prog_argv,
130                                (const char **) environ);
131         }
132     }
133   if (nulloutfd >= 0)
134     close (nulloutfd);
135   if (nullinfd >= 0)
136     close (nullinfd);
137
138   /* Restore standard file handles of parent process.  */
139   if (null_stderr)
140     undup_safer_noinherit (orig_stderr, STDERR_FILENO);
141   if (null_stdout)
142     undup_safer_noinherit (orig_stdout, STDOUT_FILENO);
143   if (null_stdin)
144     undup_safer_noinherit (orig_stdin, STDIN_FILENO);
145
146   if (termsigp != NULL)
147     *termsigp = 0;
148
149   if (exitcode == -1)
150     {
151       if (exit_on_error || !null_stderr)
152         error (exit_on_error ? EXIT_FAILURE : 0, errno,
153                _("%s subprocess failed"), progname);
154       return 127;
155     }
156
157   return exitcode;
158
159 #else
160
161   /* Unix API.  */
162   /* Note about 127: Some errors during posix_spawnp() cause the function
163      posix_spawnp() to return an error code; some other errors cause the
164      subprocess to exit with return code 127.  It is implementation
165      dependent which error is reported which way.  We treat both cases as
166      equivalent.  */
167   sigset_t blocked_signals;
168   posix_spawn_file_actions_t actions;
169   bool actions_allocated;
170   posix_spawnattr_t attrs;
171   bool attrs_allocated;
172   int err;
173   pid_t child;
174
175   if (slave_process)
176     {
177       sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
178       block_fatal_signals ();
179     }
180   actions_allocated = false;
181   attrs_allocated = false;
182   if ((err = posix_spawn_file_actions_init (&actions)) != 0
183       || (actions_allocated = true,
184           (null_stdin
185             && (err = posix_spawn_file_actions_addopen (&actions,
186                                                         STDIN_FILENO,
187                                                         "/dev/null", O_RDONLY,
188                                                         0))
189                != 0)
190           || (null_stdout
191               && (err = posix_spawn_file_actions_addopen (&actions,
192                                                           STDOUT_FILENO,
193                                                           "/dev/null", O_RDWR,
194                                                           0))
195                  != 0)
196           || (null_stderr
197               && (err = posix_spawn_file_actions_addopen (&actions,
198                                                           STDERR_FILENO,
199                                                           "/dev/null", O_RDWR,
200                                                           0))
201                  != 0)
202           || (slave_process
203               && ((err = posix_spawnattr_init (&attrs)) != 0
204                   || (attrs_allocated = true,
205                       (err = posix_spawnattr_setsigmask (&attrs,
206                                                          &blocked_signals))
207                       != 0
208                       || (err = posix_spawnattr_setflags (&attrs,
209                                                         POSIX_SPAWN_SETSIGMASK))
210                          != 0)))
211           || (err = posix_spawnp (&child, prog_path, &actions,
212                                   attrs_allocated ? &attrs : NULL, prog_argv,
213                                   environ))
214              != 0))
215     {
216       if (actions_allocated)
217         posix_spawn_file_actions_destroy (&actions);
218       if (attrs_allocated)
219         posix_spawnattr_destroy (&attrs);
220       if (slave_process)
221         unblock_fatal_signals ();
222       if (termsigp != NULL)
223         *termsigp = 0;
224       if (exit_on_error || !null_stderr)
225         error (exit_on_error ? EXIT_FAILURE : 0, err,
226                _("%s subprocess failed"), progname);
227       return 127;
228     }
229   posix_spawn_file_actions_destroy (&actions);
230   if (attrs_allocated)
231     posix_spawnattr_destroy (&attrs);
232   if (slave_process)
233     {
234       register_slave_subprocess (child);
235       unblock_fatal_signals ();
236     }
237
238   return wait_subprocess (child, progname, ignore_sigpipe, null_stderr,
239                           slave_process, exit_on_error, termsigp);
240
241 #endif
242 }