]> git.ipfire.org Git - thirdparty/glibc.git/blob - sysdeps/unix/sysv/linux/spawni.c
Update copyright dates with scripts/update-copyrights.
[thirdparty/glibc.git] / sysdeps / unix / sysv / linux / spawni.c
1 /* POSIX spawn interface. Linux version.
2 Copyright (C) 2016-2017 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library 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 GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
18
19 #include <spawn.h>
20 #include <assert.h>
21 #include <fcntl.h>
22 #include <paths.h>
23 #include <string.h>
24 #include <sys/resource.h>
25 #include <sys/wait.h>
26 #include <sys/param.h>
27 #include <sys/mman.h>
28 #include <not-cancel.h>
29 #include <local-setxid.h>
30 #include <shlib-compat.h>
31 #include <nptl/pthreadP.h>
32 #include <dl-sysdep.h>
33 #include <ldsodefs.h>
34 #include <libc-internal.h>
35 #include "spawn_int.h"
36
37 /* The Linux implementation of posix_spawn{p} uses the clone syscall directly
38 with CLONE_VM and CLONE_VFORK flags and an allocated stack. The new stack
39 and start function solves most the vfork limitation (possible parent
40 clobber due stack spilling). The remaining issue are:
41
42 1. That no signal handlers must run in child context, to avoid corrupting
43 parent's state.
44 2. The parent must ensure child's stack freeing.
45 3. Child must synchronize with parent to enforce 2. and to possible
46 return execv issues.
47
48 The first issue is solved by blocking all signals in child, even
49 the NPTL-internal ones (SIGCANCEL and SIGSETXID). The second and
50 third issue is done by a stack allocation in parent, and by using a
51 field in struct spawn_args where the child can write an error
52 code. CLONE_VFORK ensures that the parent does not run until the
53 child has either exec'ed successfully or exited. */
54
55
56 /* The Unix standard contains a long explanation of the way to signal
57 an error after the fork() was successful. Since no new wait status
58 was wanted there is no way to signal an error using one of the
59 available methods. The committee chose to signal an error by a
60 normal program exit with the exit code 127. */
61 #define SPAWN_ERROR 127
62
63 #ifdef __ia64__
64 # define CLONE(__fn, __stack, __stacksize, __flags, __args) \
65 __clone2 (__fn, __stack, __stacksize, __flags, __args, 0, 0, 0)
66 #else
67 # define CLONE(__fn, __stack, __stacksize, __flags, __args) \
68 __clone (__fn, __stack, __flags, __args)
69 #endif
70
71 #if _STACK_GROWS_DOWN
72 # define STACK(__stack, __stack_size) (__stack + __stack_size)
73 #elif _STACK_GROWS_UP
74 # define STACK(__stack, __stack_size) (__stack)
75 #endif
76
77
78 struct posix_spawn_args
79 {
80 sigset_t oldmask;
81 const char *file;
82 int (*exec) (const char *, char *const *, char *const *);
83 const posix_spawn_file_actions_t *fa;
84 const posix_spawnattr_t *restrict attr;
85 char *const *argv;
86 ptrdiff_t argc;
87 char *const *envp;
88 int xflags;
89 int err;
90 };
91
92 /* Older version requires that shell script without shebang definition
93 to be called explicitly using /bin/sh (_PATH_BSHELL). */
94 static void
95 maybe_script_execute (struct posix_spawn_args *args)
96 {
97 if (SHLIB_COMPAT (libc, GLIBC_2_2, GLIBC_2_15)
98 && (args->xflags & SPAWN_XFLAGS_TRY_SHELL) && errno == ENOEXEC)
99 {
100 char *const *argv = args->argv;
101 ptrdiff_t argc = args->argc;
102
103 /* Construct an argument list for the shell. */
104 char *new_argv[argc + 1];
105 new_argv[0] = (char *) _PATH_BSHELL;
106 new_argv[1] = (char *) args->file;
107 if (argc > 1)
108 memcpy (new_argv + 2, argv + 1, argc * sizeof(char *));
109 else
110 new_argv[2] = NULL;
111
112 /* Execute the shell. */
113 args->exec (new_argv[0], new_argv, args->envp);
114 }
115 }
116
117 /* Function used in the clone call to setup the signals mask, posix_spawn
118 attributes, and file actions. It run on its own stack (provided by the
119 posix_spawn call). */
120 static int
121 __spawni_child (void *arguments)
122 {
123 struct posix_spawn_args *args = arguments;
124 const posix_spawnattr_t *restrict attr = args->attr;
125 const posix_spawn_file_actions_t *file_actions = args->fa;
126 int ret;
127
128 /* The child must ensure that no signal handler are enabled because it shared
129 memory with parent, so the signal disposition must be either SIG_DFL or
130 SIG_IGN. It does by iterating over all signals and although it could
131 possibly be more optimized (by tracking which signal potentially have a
132 signal handler), it might requires system specific solutions (since the
133 sigset_t data type can be very different on different architectures). */
134 struct sigaction sa;
135 memset (&sa, '\0', sizeof (sa));
136
137 sigset_t hset;
138 __sigprocmask (SIG_BLOCK, 0, &hset);
139 for (int sig = 1; sig < _NSIG; ++sig)
140 {
141 if ((attr->__flags & POSIX_SPAWN_SETSIGDEF)
142 && sigismember (&attr->__sd, sig))
143 {
144 sa.sa_handler = SIG_DFL;
145 }
146 else if (sigismember (&hset, sig))
147 {
148 if (__nptl_is_internal_signal (sig))
149 sa.sa_handler = SIG_IGN;
150 else
151 {
152 __libc_sigaction (sig, 0, &sa);
153 if (sa.sa_handler == SIG_IGN)
154 continue;
155 sa.sa_handler = SIG_DFL;
156 }
157 }
158 else
159 continue;
160
161 __libc_sigaction (sig, &sa, 0);
162 }
163
164 #ifdef _POSIX_PRIORITY_SCHEDULING
165 /* Set the scheduling algorithm and parameters. */
166 if ((attr->__flags & (POSIX_SPAWN_SETSCHEDPARAM | POSIX_SPAWN_SETSCHEDULER))
167 == POSIX_SPAWN_SETSCHEDPARAM)
168 {
169 if ((ret = __sched_setparam (0, &attr->__sp)) == -1)
170 goto fail;
171 }
172 else if ((attr->__flags & POSIX_SPAWN_SETSCHEDULER) != 0)
173 {
174 if ((ret = __sched_setscheduler (0, attr->__policy, &attr->__sp)) == -1)
175 goto fail;
176 }
177 #endif
178
179 /* Set the process group ID. */
180 if ((attr->__flags & POSIX_SPAWN_SETPGROUP) != 0
181 && (ret = __setpgid (0, attr->__pgrp)) != 0)
182 goto fail;
183
184 /* Set the effective user and group IDs. */
185 if ((attr->__flags & POSIX_SPAWN_RESETIDS) != 0
186 && ((ret = local_seteuid (__getuid ())) != 0
187 || (ret = local_setegid (__getgid ())) != 0))
188 goto fail;
189
190 /* Execute the file actions. */
191 if (file_actions != 0)
192 {
193 int cnt;
194 struct rlimit64 fdlimit;
195 bool have_fdlimit = false;
196
197 for (cnt = 0; cnt < file_actions->__used; ++cnt)
198 {
199 struct __spawn_action *action = &file_actions->__actions[cnt];
200
201 switch (action->tag)
202 {
203 case spawn_do_close:
204 if ((ret =
205 close_not_cancel (action->action.close_action.fd)) != 0)
206 {
207 if (!have_fdlimit)
208 {
209 __getrlimit64 (RLIMIT_NOFILE, &fdlimit);
210 have_fdlimit = true;
211 }
212
213 /* Signal errors only for file descriptors out of range. */
214 if (action->action.close_action.fd < 0
215 || action->action.close_action.fd >= fdlimit.rlim_cur)
216 goto fail;
217 }
218 break;
219
220 case spawn_do_open:
221 {
222 /* POSIX states that if fildes was already an open file descriptor,
223 it shall be closed before the new file is opened. This avoid
224 pontential issues when posix_spawn plus addopen action is called
225 with the process already at maximum number of file descriptor
226 opened and also for multiple actions on single-open special
227 paths (like /dev/watchdog). */
228 close_not_cancel (action->action.open_action.fd);
229
230 ret = open_not_cancel (action->action.open_action.path,
231 action->action.
232 open_action.oflag | O_LARGEFILE,
233 action->action.open_action.mode);
234
235 if (ret == -1)
236 goto fail;
237
238 int new_fd = ret;
239
240 /* Make sure the desired file descriptor is used. */
241 if (ret != action->action.open_action.fd)
242 {
243 if ((ret = __dup2 (new_fd, action->action.open_action.fd))
244 != action->action.open_action.fd)
245 goto fail;
246
247 if ((ret = close_not_cancel (new_fd)) != 0)
248 goto fail;
249 }
250 }
251 break;
252
253 case spawn_do_dup2:
254 if ((ret = __dup2 (action->action.dup2_action.fd,
255 action->action.dup2_action.newfd))
256 != action->action.dup2_action.newfd)
257 goto fail;
258 break;
259 }
260 }
261 }
262
263 /* Set the initial signal mask of the child if POSIX_SPAWN_SETSIGMASK
264 is set, otherwise restore the previous one. */
265 __sigprocmask (SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK)
266 ? &attr->__ss : &args->oldmask, 0);
267
268 args->err = 0;
269 args->exec (args->file, args->argv, args->envp);
270
271 /* This is compatibility function required to enable posix_spawn run
272 script without shebang definition for older posix_spawn versions
273 (2.15). */
274 maybe_script_execute (args);
275
276 fail:
277 /* errno should have an appropriate non-zero value; otherwise,
278 there's a bug in glibc or the kernel. For lack of an error code
279 (EINTERNALBUG) describing that, use ECHILD. Another option would
280 be to set args->err to some negative sentinel and have the parent
281 abort(), but that seems needlessly harsh. */
282 args->err = errno ? : ECHILD;
283 _exit (SPAWN_ERROR);
284 }
285
286 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
287 Before running the process perform the actions described in FILE-ACTIONS. */
288 static int
289 __spawnix (pid_t * pid, const char *file,
290 const posix_spawn_file_actions_t * file_actions,
291 const posix_spawnattr_t * attrp, char *const argv[],
292 char *const envp[], int xflags,
293 int (*exec) (const char *, char *const *, char *const *))
294 {
295 pid_t new_pid;
296 struct posix_spawn_args args;
297 int ec;
298
299 /* To avoid imposing hard limits on posix_spawn{p} the total number of
300 arguments is first calculated to allocate a mmap to hold all possible
301 values. */
302 ptrdiff_t argc = 0;
303 /* Linux allows at most max (0x7FFFFFFF, 1/4 stack size) arguments
304 to be used in a execve call. We limit to INT_MAX minus one due the
305 compatiblity code that may execute a shell script (maybe_script_execute)
306 where it will construct another argument list with an additional
307 argument. */
308 ptrdiff_t limit = INT_MAX - 1;
309 while (argv[argc++] != NULL)
310 if (argc == limit)
311 {
312 errno = E2BIG;
313 return errno;
314 }
315
316 int prot = (PROT_READ | PROT_WRITE
317 | ((GL (dl_stack_flags) & PF_X) ? PROT_EXEC : 0));
318
319 /* Add a slack area for child's stack. */
320 size_t argv_size = (argc * sizeof (void *)) + 512;
321 size_t stack_size = ALIGN_UP (argv_size, GLRO(dl_pagesize));
322 void *stack = __mmap (NULL, stack_size, prot,
323 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
324 if (__glibc_unlikely (stack == MAP_FAILED))
325 return errno;
326
327 /* Disable asynchronous cancellation. */
328 int state;
329 __libc_ptf_call (__pthread_setcancelstate,
330 (PTHREAD_CANCEL_DISABLE, &state), 0);
331
332 /* Child must set args.err to something non-negative - we rely on
333 the parent and child sharing VM. */
334 args.err = -1;
335 args.file = file;
336 args.exec = exec;
337 args.fa = file_actions;
338 args.attr = attrp ? attrp : &(const posix_spawnattr_t) { 0 };
339 args.argv = argv;
340 args.argc = argc;
341 args.envp = envp;
342 args.xflags = xflags;
343
344 __libc_signal_block_all (&args.oldmask);
345
346 /* The clone flags used will create a new child that will run in the same
347 memory space (CLONE_VM) and the execution of calling thread will be
348 suspend until the child calls execve or _exit.
349
350 Also since the calling thread execution will be suspend, there is not
351 need for CLONE_SETTLS. Although parent and child share the same TLS
352 namespace, there will be no concurrent access for TLS variables (errno
353 for instance). */
354 new_pid = CLONE (__spawni_child, STACK (stack, stack_size), stack_size,
355 CLONE_VM | CLONE_VFORK | SIGCHLD, &args);
356
357 if (new_pid > 0)
358 {
359 ec = args.err;
360 assert (ec >= 0);
361 if (ec != 0)
362 __waitpid (new_pid, NULL, 0);
363 }
364 else
365 ec = -new_pid;
366
367 __munmap (stack, stack_size);
368
369 if ((ec == 0) && (pid != NULL))
370 *pid = new_pid;
371
372 __libc_signal_restore_set (&args.oldmask);
373
374 __libc_ptf_call (__pthread_setcancelstate, (state, NULL), 0);
375
376 return ec;
377 }
378
379 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
380 Before running the process perform the actions described in FILE-ACTIONS. */
381 int
382 __spawni (pid_t * pid, const char *file,
383 const posix_spawn_file_actions_t * acts,
384 const posix_spawnattr_t * attrp, char *const argv[],
385 char *const envp[], int xflags)
386 {
387 return __spawnix (pid, file, acts, attrp, argv, envp, xflags,
388 xflags & SPAWN_XFLAGS_USE_PATH ? __execvpe : __execve);
389 }