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