1 /* POSIX spawn interface. Linux version.
2 Copyright (C) 2016-2018 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/>. */
23 #include <sys/resource.h>
25 #include <sys/param.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 <libc-pointer-arith.h>
34 #include "spawn_int.h"
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:
41 1. That no signal handlers must run in child context, to avoid corrupting
43 2. The parent must ensure child's stack freeing.
44 3. Child must synchronize with parent to enforce 2. and to possible
47 The first issue is solved by blocking all signals in child, even
48 the NPTL-internal ones (SIGCANCEL and SIGSETXID). The second and
49 third issue is done by a stack allocation in parent, and by using a
50 field in struct spawn_args where the child can write an error
51 code. CLONE_VFORK ensures that the parent does not run until the
52 child has either exec'ed successfully or exited. */
55 /* The Unix standard contains a long explanation of the way to signal
56 an error after the fork() was successful. Since no new wait status
57 was wanted there is no way to signal an error using one of the
58 available methods. The committee chose to signal an error by a
59 normal program exit with the exit code 127. */
60 #define SPAWN_ERROR 127
63 # define CLONE(__fn, __stackbase, __stacksize, __flags, __args) \
64 __clone2 (__fn, __stackbase, __stacksize, __flags, __args, 0, 0, 0)
66 # define CLONE(__fn, __stack, __stacksize, __flags, __args) \
67 __clone (__fn, __stack, __flags, __args)
70 /* Since ia64 wants the stackbase w/clone2, re-use the grows-up macro. */
71 #if _STACK_GROWS_UP || defined (__ia64__)
72 # define STACK(__stack, __stack_size) (__stack)
73 #elif _STACK_GROWS_DOWN
74 # define STACK(__stack, __stack_size) (__stack + __stack_size)
78 struct posix_spawn_args
82 int (*exec
) (const char *, char *const *, char *const *);
83 const posix_spawn_file_actions_t
*fa
;
84 const posix_spawnattr_t
*restrict attr
;
92 /* Older version requires that shell script without shebang definition
93 to be called explicitly using /bin/sh (_PATH_BSHELL). */
95 maybe_script_execute (struct posix_spawn_args
*args
)
97 if (SHLIB_COMPAT (libc
, GLIBC_2_2
, GLIBC_2_15
)
98 && (args
->xflags
& SPAWN_XFLAGS_TRY_SHELL
) && errno
== ENOEXEC
)
100 char *const *argv
= args
->argv
;
101 ptrdiff_t argc
= args
->argc
;
103 /* Construct an argument list for the shell. */
104 char *new_argv
[argc
+ 2];
105 new_argv
[0] = (char *) _PATH_BSHELL
;
106 new_argv
[1] = (char *) args
->file
;
108 memcpy (new_argv
+ 2, argv
+ 1, argc
* sizeof(char *));
112 /* Execute the shell. */
113 args
->exec (new_argv
[0], new_argv
, args
->envp
);
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). */
121 __spawni_child (void *arguments
)
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
;
127 /* The child must ensure that no signal handler are enabled because it shared
128 memory with parent, so the signal disposition must be either SIG_DFL or
129 SIG_IGN. It does by iterating over all signals and although it could
130 possibly be more optimized (by tracking which signal potentially have a
131 signal handler), it might requires system specific solutions (since the
132 sigset_t data type can be very different on different architectures). */
134 memset (&sa
, '\0', sizeof (sa
));
137 __sigprocmask (SIG_BLOCK
, 0, &hset
);
138 for (int sig
= 1; sig
< _NSIG
; ++sig
)
140 if ((attr
->__flags
& POSIX_SPAWN_SETSIGDEF
)
141 && __sigismember (&attr
->__sd
, sig
))
143 sa
.sa_handler
= SIG_DFL
;
145 else if (__sigismember (&hset
, sig
))
147 if (__is_internal_signal (sig
))
148 sa
.sa_handler
= SIG_IGN
;
151 __libc_sigaction (sig
, 0, &sa
);
152 if (sa
.sa_handler
== SIG_IGN
)
154 sa
.sa_handler
= SIG_DFL
;
160 __libc_sigaction (sig
, &sa
, 0);
163 #ifdef _POSIX_PRIORITY_SCHEDULING
164 /* Set the scheduling algorithm and parameters. */
165 if ((attr
->__flags
& (POSIX_SPAWN_SETSCHEDPARAM
| POSIX_SPAWN_SETSCHEDULER
))
166 == POSIX_SPAWN_SETSCHEDPARAM
)
168 if (__sched_setparam (0, &attr
->__sp
) == -1)
171 else if ((attr
->__flags
& POSIX_SPAWN_SETSCHEDULER
) != 0)
173 if (__sched_setscheduler (0, attr
->__policy
, &attr
->__sp
) == -1)
178 if ((attr
->__flags
& POSIX_SPAWN_SETSID
) != 0
182 /* Set the process group ID. */
183 if ((attr
->__flags
& POSIX_SPAWN_SETPGROUP
) != 0
184 && __setpgid (0, attr
->__pgrp
) != 0)
187 /* Set the effective user and group IDs. */
188 if ((attr
->__flags
& POSIX_SPAWN_RESETIDS
) != 0
189 && (local_seteuid (__getuid ()) != 0
190 || local_setegid (__getgid ()) != 0))
193 /* Execute the file actions. */
194 if (file_actions
!= 0)
197 struct rlimit64 fdlimit
;
198 bool have_fdlimit
= false;
200 for (cnt
= 0; cnt
< file_actions
->__used
; ++cnt
)
202 struct __spawn_action
*action
= &file_actions
->__actions
[cnt
];
207 if (__close_nocancel (action
->action
.close_action
.fd
) != 0)
211 __getrlimit64 (RLIMIT_NOFILE
, &fdlimit
);
215 /* Signal errors only for file descriptors out of range. */
216 if (action
->action
.close_action
.fd
< 0
217 || action
->action
.close_action
.fd
>= fdlimit
.rlim_cur
)
224 /* POSIX states that if fildes was already an open file descriptor,
225 it shall be closed before the new file is opened. This avoid
226 pontential issues when posix_spawn plus addopen action is called
227 with the process already at maximum number of file descriptor
228 opened and also for multiple actions on single-open special
229 paths (like /dev/watchdog). */
230 __close_nocancel (action
->action
.open_action
.fd
);
232 int ret
= __open_nocancel (action
->action
.open_action
.path
,
234 open_action
.oflag
| O_LARGEFILE
,
235 action
->action
.open_action
.mode
);
242 /* Make sure the desired file descriptor is used. */
243 if (ret
!= action
->action
.open_action
.fd
)
245 if (__dup2 (new_fd
, action
->action
.open_action
.fd
)
246 != action
->action
.open_action
.fd
)
249 if (__close_nocancel (new_fd
) != 0)
256 if (__dup2 (action
->action
.dup2_action
.fd
,
257 action
->action
.dup2_action
.newfd
)
258 != action
->action
.dup2_action
.newfd
)
263 if (__chdir (action
->action
.chdir_action
.path
) != 0)
267 case spawn_do_fchdir
:
268 if (__fchdir (action
->action
.fchdir_action
.fd
) != 0)
275 /* Set the initial signal mask of the child if POSIX_SPAWN_SETSIGMASK
276 is set, otherwise restore the previous one. */
277 __sigprocmask (SIG_SETMASK
, (attr
->__flags
& POSIX_SPAWN_SETSIGMASK
)
278 ? &attr
->__ss
: &args
->oldmask
, 0);
280 args
->exec (args
->file
, args
->argv
, args
->envp
);
282 /* This is compatibility function required to enable posix_spawn run
283 script without shebang definition for older posix_spawn versions
285 maybe_script_execute (args
);
288 /* errno should have an appropriate non-zero value; otherwise,
289 there's a bug in glibc or the kernel. For lack of an error code
290 (EINTERNALBUG) describing that, use ECHILD. Another option would
291 be to set args->err to some negative sentinel and have the parent
292 abort(), but that seems needlessly harsh. */
293 args
->err
= errno
? : ECHILD
;
297 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
298 Before running the process perform the actions described in FILE-ACTIONS. */
300 __spawnix (pid_t
* pid
, const char *file
,
301 const posix_spawn_file_actions_t
* file_actions
,
302 const posix_spawnattr_t
* attrp
, char *const argv
[],
303 char *const envp
[], int xflags
,
304 int (*exec
) (const char *, char *const *, char *const *))
307 struct posix_spawn_args args
;
310 /* To avoid imposing hard limits on posix_spawn{p} the total number of
311 arguments is first calculated to allocate a mmap to hold all possible
314 /* Linux allows at most max (0x7FFFFFFF, 1/4 stack size) arguments
315 to be used in a execve call. We limit to INT_MAX minus one due the
316 compatiblity code that may execute a shell script (maybe_script_execute)
317 where it will construct another argument list with an additional
319 ptrdiff_t limit
= INT_MAX
- 1;
320 while (argv
[argc
++] != NULL
)
327 int prot
= (PROT_READ
| PROT_WRITE
328 | ((GL (dl_stack_flags
) & PF_X
) ? PROT_EXEC
: 0));
330 /* Add a slack area for child's stack. */
331 size_t argv_size
= (argc
* sizeof (void *)) + 512;
332 /* We need at least a few pages in case the compiler's stack checking is
333 enabled. In some configs, it is known to use at least 24KiB. We use
334 32KiB to be "safe" from anything the compiler might do. Besides, the
335 extra pages won't actually be allocated unless they get used. */
336 argv_size
+= (32 * 1024);
337 size_t stack_size
= ALIGN_UP (argv_size
, GLRO(dl_pagesize
));
338 void *stack
= __mmap (NULL
, stack_size
, prot
,
339 MAP_PRIVATE
| MAP_ANONYMOUS
| MAP_STACK
, -1, 0);
340 if (__glibc_unlikely (stack
== MAP_FAILED
))
343 /* Disable asynchronous cancellation. */
345 __libc_ptf_call (__pthread_setcancelstate
,
346 (PTHREAD_CANCEL_DISABLE
, &state
), 0);
348 /* Child must set args.err to something non-negative - we rely on
349 the parent and child sharing VM. */
353 args
.fa
= file_actions
;
354 args
.attr
= attrp
? attrp
: &(const posix_spawnattr_t
) { 0 };
358 args
.xflags
= xflags
;
360 __libc_signal_block_all (&args
.oldmask
);
362 /* The clone flags used will create a new child that will run in the same
363 memory space (CLONE_VM) and the execution of calling thread will be
364 suspend until the child calls execve or _exit.
366 Also since the calling thread execution will be suspend, there is not
367 need for CLONE_SETTLS. Although parent and child share the same TLS
368 namespace, there will be no concurrent access for TLS variables (errno
370 new_pid
= CLONE (__spawni_child
, STACK (stack
, stack_size
), stack_size
,
371 CLONE_VM
| CLONE_VFORK
| SIGCHLD
, &args
);
373 /* It needs to collect the case where the auxiliary process was created
374 but failed to execute the file (due either any preparation step or
375 for execve itself). */
378 /* Also, it handles the unlikely case where the auxiliary process was
379 terminated before calling execve as if it was successfully. The
380 args.err is set to 0 as default and changed to a positive value
381 only in case of failure, so in case of premature termination
382 due a signal args.err will remain zeroed and it will be up to
383 caller to actually collect it. */
386 /* There still an unlikely case where the child is cancelled after
387 setting args.err, due to a positive error value. Also there is
388 possible pid reuse race (where the kernel allocated the same pid
389 to an unrelated process). Unfortunately due synchronization
390 issues where the kernel might not have the process collected
391 the waitpid below can not use WNOHANG. */
392 __waitpid (new_pid
, NULL
, 0);
397 __munmap (stack
, stack_size
);
399 if ((ec
== 0) && (pid
!= NULL
))
402 __libc_signal_restore_set (&args
.oldmask
);
404 __libc_ptf_call (__pthread_setcancelstate
, (state
, NULL
), 0);
409 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
410 Before running the process perform the actions described in FILE-ACTIONS. */
412 __spawni (pid_t
* pid
, const char *file
,
413 const posix_spawn_file_actions_t
* acts
,
414 const posix_spawnattr_t
* attrp
, char *const argv
[],
415 char *const envp
[], int xflags
)
417 /* It uses __execvpex to avoid run ENOEXEC in non compatibility mode (it
418 will be handled by maybe_script_execute). */
419 return __spawnix (pid
, file
, acts
, attrp
, argv
, envp
, xflags
,
420 xflags
& SPAWN_XFLAGS_USE_PATH
? __execvpex
:__execve
);