Bump to 1.14.1
[platform/upstream/augeas.git] / lib / execute.c
1 /* Creation of autonomous subprocesses.
2    Copyright (C) 2001-2004, 2006-2016 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
52 #if defined EINTR && ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
53
54 /* EINTR handling for close(), open().
55    These functions can return -1/EINTR even though we don't have any
56    signal handlers set up, namely when we get interrupted via SIGSTOP.  */
57
58 static int
59 nonintr_close (int fd)
60 {
61   int retval;
62
63   do
64     retval = close (fd);
65   while (retval < 0 && errno == EINTR);
66
67   return retval;
68 }
69 #define close nonintr_close
70
71 static int
72 nonintr_open (const char *pathname, int oflag, mode_t mode)
73 {
74   int retval;
75
76   do
77     retval = open (pathname, oflag, mode);
78   while (retval < 0 && errno == EINTR);
79
80   return retval;
81 }
82 #undef open /* avoid warning on VMS */
83 #define open nonintr_open
84
85 #endif
86
87
88 /* Execute a command, optionally redirecting any of the three standard file
89    descriptors to /dev/null.  Return its exit code.
90    If it didn't terminate correctly, exit if exit_on_error is true, otherwise
91    return 127.
92    If slave_process is true, the child process will be terminated when its
93    creator receives a catchable fatal signal.  */
94 int
95 execute (const char *progname,
96          const char *prog_path, char **prog_argv,
97          bool ignore_sigpipe,
98          bool null_stdin, bool null_stdout, bool null_stderr,
99          bool slave_process, bool exit_on_error,
100          int *termsigp)
101 {
102 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
103
104   /* Native Windows API.  */
105   int orig_stdin;
106   int orig_stdout;
107   int orig_stderr;
108   int exitcode;
109   int nullinfd;
110   int nulloutfd;
111
112   /* FIXME: Need to free memory allocated by prepare_spawn.  */
113   prog_argv = prepare_spawn (prog_argv);
114
115   /* Save standard file handles of parent process.  */
116   if (null_stdin)
117     orig_stdin = dup_safer_noinherit (STDIN_FILENO);
118   if (null_stdout)
119     orig_stdout = dup_safer_noinherit (STDOUT_FILENO);
120   if (null_stderr)
121     orig_stderr = dup_safer_noinherit (STDERR_FILENO);
122   exitcode = -1;
123
124   /* Create standard file handles of child process.  */
125   nullinfd = -1;
126   nulloutfd = -1;
127   if ((!null_stdin
128        || ((nullinfd = open ("NUL", O_RDONLY, 0)) >= 0
129            && (nullinfd == STDIN_FILENO
130                || (dup2 (nullinfd, STDIN_FILENO) >= 0
131                    && close (nullinfd) >= 0))))
132       && (!(null_stdout || null_stderr)
133           || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
134               && (!null_stdout
135                   || nulloutfd == STDOUT_FILENO
136                   || dup2 (nulloutfd, STDOUT_FILENO) >= 0)
137               && (!null_stderr
138                   || nulloutfd == STDERR_FILENO
139                   || dup2 (nulloutfd, STDERR_FILENO) >= 0)
140               && ((null_stdout && nulloutfd == STDOUT_FILENO)
141                   || (null_stderr && nulloutfd == STDERR_FILENO)
142                   || close (nulloutfd) >= 0))))
143     /* Use spawnvpe and pass the environment explicitly.  This is needed if
144        the program has modified the environment using putenv() or [un]setenv().
145        On Windows, programs have two environments, one in the "environment
146        block" of the process and managed through SetEnvironmentVariable(), and
147        one inside the process, in the location retrieved by the 'environ'
148        macro.  When using spawnvp() without 'e', the child process inherits a
149        copy of the environment block - ignoring the effects of putenv() and
150        [un]setenv().  */
151     {
152       exitcode = spawnvpe (P_WAIT, prog_path, (const char **) prog_argv,
153                            (const char **) environ);
154       if (exitcode < 0 && errno == ENOEXEC)
155         {
156           /* prog is not a native executable.  Try to execute it as a
157              shell script.  Note that prepare_spawn() has already prepended
158              a hidden element "sh.exe" to prog_argv.  */
159           --prog_argv;
160           exitcode = spawnvpe (P_WAIT, prog_argv[0], (const char **) prog_argv,
161                                (const char **) environ);
162         }
163     }
164   if (nulloutfd >= 0)
165     close (nulloutfd);
166   if (nullinfd >= 0)
167     close (nullinfd);
168
169   /* Restore standard file handles of parent process.  */
170   if (null_stderr)
171     undup_safer_noinherit (orig_stderr, STDERR_FILENO);
172   if (null_stdout)
173     undup_safer_noinherit (orig_stdout, STDOUT_FILENO);
174   if (null_stdin)
175     undup_safer_noinherit (orig_stdin, STDIN_FILENO);
176
177   if (termsigp != NULL)
178     *termsigp = 0;
179
180   if (exitcode == -1)
181     {
182       if (exit_on_error || !null_stderr)
183         error (exit_on_error ? EXIT_FAILURE : 0, errno,
184                _("%s subprocess failed"), progname);
185       return 127;
186     }
187
188   return exitcode;
189
190 #else
191
192   /* Unix API.  */
193   /* Note about 127: Some errors during posix_spawnp() cause the function
194      posix_spawnp() to return an error code; some other errors cause the
195      subprocess to exit with return code 127.  It is implementation
196      dependent which error is reported which way.  We treat both cases as
197      equivalent.  */
198   sigset_t blocked_signals;
199   posix_spawn_file_actions_t actions;
200   bool actions_allocated;
201   posix_spawnattr_t attrs;
202   bool attrs_allocated;
203   int err;
204   pid_t child;
205
206   if (slave_process)
207     {
208       sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
209       block_fatal_signals ();
210     }
211   actions_allocated = false;
212   attrs_allocated = false;
213   if ((err = posix_spawn_file_actions_init (&actions)) != 0
214       || (actions_allocated = true,
215           (null_stdin
216             && (err = posix_spawn_file_actions_addopen (&actions,
217                                                         STDIN_FILENO,
218                                                         "/dev/null", O_RDONLY,
219                                                         0))
220                != 0)
221           || (null_stdout
222               && (err = posix_spawn_file_actions_addopen (&actions,
223                                                           STDOUT_FILENO,
224                                                           "/dev/null", O_RDWR,
225                                                           0))
226                  != 0)
227           || (null_stderr
228               && (err = posix_spawn_file_actions_addopen (&actions,
229                                                           STDERR_FILENO,
230                                                           "/dev/null", O_RDWR,
231                                                           0))
232                  != 0)
233           || (slave_process
234               && ((err = posix_spawnattr_init (&attrs)) != 0
235                   || (attrs_allocated = true,
236                       (err = posix_spawnattr_setsigmask (&attrs,
237                                                          &blocked_signals))
238                       != 0
239                       || (err = posix_spawnattr_setflags (&attrs,
240                                                         POSIX_SPAWN_SETSIGMASK))
241                          != 0)))
242           || (err = posix_spawnp (&child, prog_path, &actions,
243                                   attrs_allocated ? &attrs : NULL, prog_argv,
244                                   environ))
245              != 0))
246     {
247       if (actions_allocated)
248         posix_spawn_file_actions_destroy (&actions);
249       if (attrs_allocated)
250         posix_spawnattr_destroy (&attrs);
251       if (slave_process)
252         unblock_fatal_signals ();
253       if (termsigp != NULL)
254         *termsigp = 0;
255       if (exit_on_error || !null_stderr)
256         error (exit_on_error ? EXIT_FAILURE : 0, err,
257                _("%s subprocess failed"), progname);
258       return 127;
259     }
260   posix_spawn_file_actions_destroy (&actions);
261   if (attrs_allocated)
262     posix_spawnattr_destroy (&attrs);
263   if (slave_process)
264     {
265       register_slave_subprocess (child);
266       unblock_fatal_signals ();
267     }
268
269   return wait_subprocess (child, progname, ignore_sigpipe, null_stderr,
270                           slave_process, exit_on_error, termsigp);
271
272 #endif
273 }