Consolidate non cancellable open call
[glibc.git] / sysdeps / unix / sysv / linux / spawni.c
blob4994a07491c1f995c049a1d17b8d242b54164113
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.
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.
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.
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/>. */
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 <libc-pointer-arith.h>
34 #include <ldsodefs.h>
35 #include "spawn_int.h"
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:
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.
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. */
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
63 #ifdef __ia64__
64 # define CLONE(__fn, __stackbase, __stacksize, __flags, __args) \
65 __clone2 (__fn, __stackbase, __stacksize, __flags, __args, 0, 0, 0)
66 #else
67 # define CLONE(__fn, __stack, __stacksize, __flags, __args) \
68 __clone (__fn, __stack, __flags, __args)
69 #endif
71 /* Since ia64 wants the stackbase w/clone2, re-use the grows-up macro. */
72 #if _STACK_GROWS_UP || defined (__ia64__)
73 # define STACK(__stack, __stack_size) (__stack)
74 #elif _STACK_GROWS_DOWN
75 # define STACK(__stack, __stack_size) (__stack + __stack_size)
76 #endif
79 struct posix_spawn_args
81 sigset_t oldmask;
82 const char *file;
83 int (*exec) (const char *, char *const *, char *const *);
84 const posix_spawn_file_actions_t *fa;
85 const posix_spawnattr_t *restrict attr;
86 char *const *argv;
87 ptrdiff_t argc;
88 char *const *envp;
89 int xflags;
90 int err;
93 /* Older version requires that shell script without shebang definition
94 to be called explicitly using /bin/sh (_PATH_BSHELL). */
95 static void
96 maybe_script_execute (struct posix_spawn_args *args)
98 if (SHLIB_COMPAT (libc, GLIBC_2_2, GLIBC_2_15)
99 && (args->xflags & SPAWN_XFLAGS_TRY_SHELL) && errno == ENOEXEC)
101 char *const *argv = args->argv;
102 ptrdiff_t argc = args->argc;
104 /* Construct an argument list for the shell. */
105 char *new_argv[argc + 1];
106 new_argv[0] = (char *) _PATH_BSHELL;
107 new_argv[1] = (char *) args->file;
108 if (argc > 1)
109 memcpy (new_argv + 2, argv + 1, argc * sizeof(char *));
110 else
111 new_argv[2] = NULL;
113 /* Execute the shell. */
114 args->exec (new_argv[0], new_argv, args->envp);
118 /* Function used in the clone call to setup the signals mask, posix_spawn
119 attributes, and file actions. It run on its own stack (provided by the
120 posix_spawn call). */
121 static int
122 __spawni_child (void *arguments)
124 struct posix_spawn_args *args = arguments;
125 const posix_spawnattr_t *restrict attr = args->attr;
126 const posix_spawn_file_actions_t *file_actions = args->fa;
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));
137 sigset_t hset;
138 __sigprocmask (SIG_BLOCK, 0, &hset);
139 for (int sig = 1; sig < _NSIG; ++sig)
141 if ((attr->__flags & POSIX_SPAWN_SETSIGDEF)
142 && sigismember (&attr->__sd, sig))
144 sa.sa_handler = SIG_DFL;
146 else if (sigismember (&hset, sig))
148 if (__nptl_is_internal_signal (sig))
149 sa.sa_handler = SIG_IGN;
150 else
152 __libc_sigaction (sig, 0, &sa);
153 if (sa.sa_handler == SIG_IGN)
154 continue;
155 sa.sa_handler = SIG_DFL;
158 else
159 continue;
161 __libc_sigaction (sig, &sa, 0);
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)
169 if (__sched_setparam (0, &attr->__sp) == -1)
170 goto fail;
172 else if ((attr->__flags & POSIX_SPAWN_SETSCHEDULER) != 0)
174 if (__sched_setscheduler (0, attr->__policy, &attr->__sp) == -1)
175 goto fail;
177 #endif
179 if ((attr->__flags & POSIX_SPAWN_SETSID) != 0
180 && __setsid () < 0)
181 goto fail;
183 /* Set the process group ID. */
184 if ((attr->__flags & POSIX_SPAWN_SETPGROUP) != 0
185 && __setpgid (0, attr->__pgrp) != 0)
186 goto fail;
188 /* Set the effective user and group IDs. */
189 if ((attr->__flags & POSIX_SPAWN_RESETIDS) != 0
190 && (local_seteuid (__getuid ()) != 0
191 || local_setegid (__getgid ()) != 0))
192 goto fail;
194 /* Execute the file actions. */
195 if (file_actions != 0)
197 int cnt;
198 struct rlimit64 fdlimit;
199 bool have_fdlimit = false;
201 for (cnt = 0; cnt < file_actions->__used; ++cnt)
203 struct __spawn_action *action = &file_actions->__actions[cnt];
205 switch (action->tag)
207 case spawn_do_close:
208 if (close_not_cancel (action->action.close_action.fd) != 0)
210 if (!have_fdlimit)
212 __getrlimit64 (RLIMIT_NOFILE, &fdlimit);
213 have_fdlimit = true;
216 /* Signal errors only for file descriptors out of range. */
217 if (action->action.close_action.fd < 0
218 || action->action.close_action.fd >= fdlimit.rlim_cur)
219 goto fail;
221 break;
223 case spawn_do_open:
225 /* POSIX states that if fildes was already an open file descriptor,
226 it shall be closed before the new file is opened. This avoid
227 pontential issues when posix_spawn plus addopen action is called
228 with the process already at maximum number of file descriptor
229 opened and also for multiple actions on single-open special
230 paths (like /dev/watchdog). */
231 close_not_cancel (action->action.open_action.fd);
233 int ret = __open_nocancel (action->action.open_action.path,
234 action->action.
235 open_action.oflag | O_LARGEFILE,
236 action->action.open_action.mode);
238 if (ret == -1)
239 goto fail;
241 int new_fd = ret;
243 /* Make sure the desired file descriptor is used. */
244 if (ret != action->action.open_action.fd)
246 if (__dup2 (new_fd, action->action.open_action.fd)
247 != action->action.open_action.fd)
248 goto fail;
250 if (close_not_cancel (new_fd) != 0)
251 goto fail;
254 break;
256 case spawn_do_dup2:
257 if (__dup2 (action->action.dup2_action.fd,
258 action->action.dup2_action.newfd)
259 != action->action.dup2_action.newfd)
260 goto fail;
261 break;
266 /* Set the initial signal mask of the child if POSIX_SPAWN_SETSIGMASK
267 is set, otherwise restore the previous one. */
268 __sigprocmask (SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK)
269 ? &attr->__ss : &args->oldmask, 0);
271 args->err = 0;
272 args->exec (args->file, args->argv, args->envp);
274 /* This is compatibility function required to enable posix_spawn run
275 script without shebang definition for older posix_spawn versions
276 (2.15). */
277 maybe_script_execute (args);
279 fail:
280 /* errno should have an appropriate non-zero value; otherwise,
281 there's a bug in glibc or the kernel. For lack of an error code
282 (EINTERNALBUG) describing that, use ECHILD. Another option would
283 be to set args->err to some negative sentinel and have the parent
284 abort(), but that seems needlessly harsh. */
285 args->err = errno ? : ECHILD;
286 _exit (SPAWN_ERROR);
289 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
290 Before running the process perform the actions described in FILE-ACTIONS. */
291 static int
292 __spawnix (pid_t * pid, const char *file,
293 const posix_spawn_file_actions_t * file_actions,
294 const posix_spawnattr_t * attrp, char *const argv[],
295 char *const envp[], int xflags,
296 int (*exec) (const char *, char *const *, char *const *))
298 pid_t new_pid;
299 struct posix_spawn_args args;
300 int ec;
302 /* To avoid imposing hard limits on posix_spawn{p} the total number of
303 arguments is first calculated to allocate a mmap to hold all possible
304 values. */
305 ptrdiff_t argc = 0;
306 /* Linux allows at most max (0x7FFFFFFF, 1/4 stack size) arguments
307 to be used in a execve call. We limit to INT_MAX minus one due the
308 compatiblity code that may execute a shell script (maybe_script_execute)
309 where it will construct another argument list with an additional
310 argument. */
311 ptrdiff_t limit = INT_MAX - 1;
312 while (argv[argc++] != NULL)
313 if (argc == limit)
315 errno = E2BIG;
316 return errno;
319 int prot = (PROT_READ | PROT_WRITE
320 | ((GL (dl_stack_flags) & PF_X) ? PROT_EXEC : 0));
322 /* Add a slack area for child's stack. */
323 size_t argv_size = (argc * sizeof (void *)) + 512;
324 /* We need at least a few pages in case the compiler's stack checking is
325 enabled. In some configs, it is known to use at least 24KiB. We use
326 32KiB to be "safe" from anything the compiler might do. Besides, the
327 extra pages won't actually be allocated unless they get used. */
328 argv_size += (32 * 1024);
329 size_t stack_size = ALIGN_UP (argv_size, GLRO(dl_pagesize));
330 void *stack = __mmap (NULL, stack_size, prot,
331 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
332 if (__glibc_unlikely (stack == MAP_FAILED))
333 return errno;
335 /* Disable asynchronous cancellation. */
336 int state;
337 __libc_ptf_call (__pthread_setcancelstate,
338 (PTHREAD_CANCEL_DISABLE, &state), 0);
340 /* Child must set args.err to something non-negative - we rely on
341 the parent and child sharing VM. */
342 args.err = -1;
343 args.file = file;
344 args.exec = exec;
345 args.fa = file_actions;
346 args.attr = attrp ? attrp : &(const posix_spawnattr_t) { 0 };
347 args.argv = argv;
348 args.argc = argc;
349 args.envp = envp;
350 args.xflags = xflags;
352 __libc_signal_block_all (&args.oldmask);
354 /* The clone flags used will create a new child that will run in the same
355 memory space (CLONE_VM) and the execution of calling thread will be
356 suspend until the child calls execve or _exit.
358 Also since the calling thread execution will be suspend, there is not
359 need for CLONE_SETTLS. Although parent and child share the same TLS
360 namespace, there will be no concurrent access for TLS variables (errno
361 for instance). */
362 new_pid = CLONE (__spawni_child, STACK (stack, stack_size), stack_size,
363 CLONE_VM | CLONE_VFORK | SIGCHLD, &args);
365 if (new_pid > 0)
367 ec = args.err;
368 assert (ec >= 0);
369 if (ec != 0)
370 __waitpid (new_pid, NULL, 0);
372 else
373 ec = -new_pid;
375 __munmap (stack, stack_size);
377 if ((ec == 0) && (pid != NULL))
378 *pid = new_pid;
380 __libc_signal_restore_set (&args.oldmask);
382 __libc_ptf_call (__pthread_setcancelstate, (state, NULL), 0);
384 return ec;
387 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
388 Before running the process perform the actions described in FILE-ACTIONS. */
390 __spawni (pid_t * pid, const char *file,
391 const posix_spawn_file_actions_t * acts,
392 const posix_spawnattr_t * attrp, char *const argv[],
393 char *const envp[], int xflags)
395 return __spawnix (pid, file, acts, attrp, argv, envp, xflags,
396 xflags & SPAWN_XFLAGS_USE_PATH ? __execvpe : __execve);