1 /* POSIX spawn interface. Linux version.
2 Copyright (C) 2016-2024 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 <https://www.gnu.org/licenses/>. */
19 #include <internal-signals.h>
21 #include <local-setxid.h>
22 #include <not-cancel.h>
24 #include <shlib-compat.h>
26 #include <spawn_int.h>
28 #include <sys/resource.h>
29 #include <clone_internal.h>
31 /* The Linux implementation of posix_spawn{p} uses the clone syscall directly
32 with CLONE_VM and CLONE_VFORK flags and an allocated stack. The new stack
33 and start function solves most the vfork limitation (possible parent
34 clobber due stack spilling). The remaining issue are:
36 1. That no signal handlers must run in child context, to avoid corrupting
38 2. The parent must ensure child's stack freeing.
39 3. Child must synchronize with parent to enforce 2. and to possible
42 The first issue is solved by blocking all signals in child, even
43 the NPTL-internal ones (SIGCANCEL and SIGSETXID). The second and
44 third issue is done by a stack allocation in parent, and by using a
45 field in struct spawn_args where the child can write an error
46 code. CLONE_VFORK ensures that the parent does not run until the
47 child has either exec'ed successfully or exited. */
50 /* The Unix standard contains a long explanation of the way to signal
51 an error after the fork() was successful. Since no new wait status
52 was wanted there is no way to signal an error using one of the
53 available methods. The committee chose to signal an error by a
54 normal program exit with the exit code 127. */
55 #define SPAWN_ERROR 127
58 struct posix_spawn_args
60 internal_sigset_t oldmask
;
62 int (*exec
) (const char *, char *const *, char *const *);
63 const posix_spawn_file_actions_t
*fa
;
64 const posix_spawnattr_t
*restrict attr
;
74 /* Older version requires that shell script without shebang definition
75 to be called explicitly using /bin/sh (_PATH_BSHELL). */
77 maybe_script_execute (struct posix_spawn_args
*args
)
79 if (SHLIB_COMPAT (libc
, GLIBC_2_2
, GLIBC_2_15
)
80 && (args
->xflags
& SPAWN_XFLAGS_TRY_SHELL
) && errno
== ENOEXEC
)
82 char *const *argv
= args
->argv
;
83 ptrdiff_t argc
= args
->argc
;
85 /* Construct an argument list for the shell. */
86 char *new_argv
[argc
+ 2];
87 new_argv
[0] = (char *) _PATH_BSHELL
;
88 new_argv
[1] = (char *) args
->file
;
90 memcpy (new_argv
+ 2, argv
+ 1, argc
* sizeof (char *));
94 /* Execute the shell. */
95 args
->exec (new_argv
[0], new_argv
, args
->envp
);
99 /* Function used in the clone call to setup the signals mask, posix_spawn
100 attributes, and file actions. It run on its own stack (provided by the
101 posix_spawn call). */
103 __spawni_child (void *arguments
)
105 struct posix_spawn_args
*args
= arguments
;
106 const posix_spawnattr_t
*restrict attr
= args
->attr
;
107 const posix_spawn_file_actions_t
*file_actions
= args
->fa
;
109 /* The child must ensure that no signal handler is enabled because it
110 shares memory with parent, so all signal dispositions must be either
111 SIG_DFL or SIG_IGN. If clone3/CLONE_CLEAR_SIGHAND is used, there is
112 only the need to set the defined signals POSIX_SPAWN_SETSIGDEF to
113 SIG_DFL; otherwise, the code iterates over all signals. */
115 memset (&sa
, '\0', sizeof (sa
));
118 __sigprocmask (SIG_BLOCK
, 0, &hset
);
119 for (int sig
= 1; sig
< _NSIG
; ++sig
)
121 if ((attr
->__flags
& POSIX_SPAWN_SETSIGDEF
)
122 && __sigismember (&attr
->__sd
, sig
))
124 sa
.sa_handler
= SIG_DFL
;
126 else if (!args
->use_clone3
&& __sigismember (&hset
, sig
))
128 if (is_internal_signal (sig
))
129 sa
.sa_handler
= SIG_IGN
;
132 __libc_sigaction (sig
, 0, &sa
);
133 if (sa
.sa_handler
== SIG_IGN
|| sa
.sa_handler
== SIG_DFL
)
135 sa
.sa_handler
= SIG_DFL
;
141 __libc_sigaction (sig
, &sa
, 0);
144 #ifdef _POSIX_PRIORITY_SCHEDULING
145 /* Set the scheduling algorithm and parameters. */
146 if ((attr
->__flags
& (POSIX_SPAWN_SETSCHEDPARAM
| POSIX_SPAWN_SETSCHEDULER
))
147 == POSIX_SPAWN_SETSCHEDPARAM
)
149 if (__sched_setparam (0, &attr
->__sp
) == -1)
152 else if ((attr
->__flags
& POSIX_SPAWN_SETSCHEDULER
) != 0)
154 if (__sched_setscheduler (0, attr
->__policy
, &attr
->__sp
) == -1)
159 if ((attr
->__flags
& POSIX_SPAWN_SETSID
) != 0
163 /* Set the process group ID. */
164 if ((attr
->__flags
& POSIX_SPAWN_SETPGROUP
) != 0
165 && __setpgid (0, attr
->__pgrp
) != 0)
168 /* Set the effective user and group IDs. */
169 if ((attr
->__flags
& POSIX_SPAWN_RESETIDS
) != 0
170 && (local_seteuid (__getuid ()) != 0
171 || local_setegid (__getgid ()) != 0))
174 /* Execute the file actions. */
175 if (file_actions
!= 0)
178 struct rlimit64 fdlimit
;
179 bool have_fdlimit
= false;
181 for (cnt
= 0; cnt
< file_actions
->__used
; ++cnt
)
183 struct __spawn_action
*action
= &file_actions
->__actions
[cnt
];
188 if (__close_nocancel (action
->action
.close_action
.fd
) != 0)
192 __getrlimit64 (RLIMIT_NOFILE
, &fdlimit
);
196 /* Signal errors only for file descriptors out of range. */
197 if (action
->action
.close_action
.fd
< 0
198 || action
->action
.close_action
.fd
>= fdlimit
.rlim_cur
)
205 /* POSIX states that if fildes was already an open file descriptor,
206 it shall be closed before the new file is opened. This avoid
207 potential issues when posix_spawn plus addopen action is called
208 with the process already at maximum number of file descriptor
209 opened and also for multiple actions on single-open special
210 paths (like /dev/watchdog). */
211 __close_nocancel (action
->action
.open_action
.fd
);
213 int ret
= __open_nocancel (action
->action
.open_action
.path
,
215 open_action
.oflag
| O_LARGEFILE
,
216 action
->action
.open_action
.mode
);
223 /* Make sure the desired file descriptor is used. */
224 if (ret
!= action
->action
.open_action
.fd
)
226 if (__dup2 (new_fd
, action
->action
.open_action
.fd
)
227 != action
->action
.open_action
.fd
)
230 if (__close_nocancel (new_fd
) != 0)
237 /* Austin Group issue #411 requires adddup2 action with source
238 and destination being equal to remove close-on-exec flag. */
239 if (action
->action
.dup2_action
.fd
240 == action
->action
.dup2_action
.newfd
)
242 int fd
= action
->action
.dup2_action
.newfd
;
243 int flags
= __fcntl (fd
, F_GETFD
, 0);
246 if (__fcntl (fd
, F_SETFD
, flags
& ~FD_CLOEXEC
) == -1)
249 else if (__dup2 (action
->action
.dup2_action
.fd
,
250 action
->action
.dup2_action
.newfd
)
251 != action
->action
.dup2_action
.newfd
)
256 if (__chdir (action
->action
.chdir_action
.path
) != 0)
260 case spawn_do_fchdir
:
261 if (__fchdir (action
->action
.fchdir_action
.fd
) != 0)
265 case spawn_do_closefrom
:
267 int lowfd
= action
->action
.closefrom_action
.from
;
268 int r
= INLINE_SYSCALL_CALL (close_range
, lowfd
, ~0U, 0);
269 if (r
!= 0 && !__closefrom_fallback (lowfd
, false))
273 case spawn_do_tcsetpgrp
:
275 /* Check if it is possible to avoid an extra syscall. */
276 pid_t pgrp
= (attr
->__flags
& POSIX_SPAWN_SETPGROUP
) != 0
278 ? attr
->__pgrp
: __getpgid (0);
279 if (__tcsetpgrp (action
->action
.setpgrp_action
.fd
, pgrp
) != 0)
286 /* Set the initial signal mask of the child if POSIX_SPAWN_SETSIGMASK
287 is set, otherwise restore the previous one. */
288 if (attr
->__flags
& POSIX_SPAWN_SETSIGMASK
)
289 __sigprocmask (SIG_SETMASK
, &attr
->__ss
, NULL
);
291 internal_sigprocmask (SIG_SETMASK
, &args
->oldmask
, NULL
);
293 args
->exec (args
->file
, args
->argv
, args
->envp
);
295 /* This is compatibility function required to enable posix_spawn run
296 script without shebang definition for older posix_spawn versions
298 maybe_script_execute (args
);
301 /* errno should have an appropriate non-zero value; otherwise,
302 there's a bug in glibc or the kernel. For lack of an error code
303 (EINTERNALBUG) describing that, use ECHILD. Another option would
304 be to set args->err to some negative sentinel and have the parent
305 abort(), but that seems needlessly harsh. */
306 args
->err
= errno
? : ECHILD
;
310 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
311 Before running the process perform the actions described in FILE-ACTIONS. */
313 __spawnix (int *pid
, const char *file
,
314 const posix_spawn_file_actions_t
* file_actions
,
315 const posix_spawnattr_t
* attrp
, char *const argv
[],
316 char *const envp
[], int xflags
,
317 int (*exec
) (const char *, char *const *, char *const *))
320 struct posix_spawn_args args
;
323 bool use_pidfd
= xflags
& SPAWN_XFLAGS_RET_PIDFD
;
325 /* For CLONE_PIDFD, older kernels might not fail with unsupported flags or
326 some versions might not support waitid (P_PIDFD). So to avoid the need
327 to handle the error on the helper process, check for full pidfd
329 ENOSYS is returned because without proper waitid support, pidfd_spawn
330 can not be used proporly independently of its arguments. */
331 if (use_pidfd
&& !__clone_pidfd_supported ())
334 /* To avoid imposing hard limits on posix_spawn{p} the total number of
335 arguments is first calculated to allocate a mmap to hold all possible
338 /* Linux allows at most max (0x7FFFFFFF, 1/4 stack size) arguments
339 to be used in a execve call. We limit to INT_MAX minus one due the
340 compatibility code that may execute a shell script (maybe_script_execute)
341 where it will construct another argument list with an additional
343 ptrdiff_t limit
= INT_MAX
- 1;
344 while (argv
[argc
++] != NULL
)
351 int prot
= (PROT_READ
| PROT_WRITE
352 | ((GL (dl_stack_flags
) & PF_X
) ? PROT_EXEC
: 0));
354 /* Add a slack area for child's stack. */
355 size_t argv_size
= (argc
* sizeof (void *)) + 512;
356 /* We need at least a few pages in case the compiler's stack checking is
357 enabled. In some configs, it is known to use at least 24KiB. We use
358 32KiB to be "safe" from anything the compiler might do. Besides, the
359 extra pages won't actually be allocated unless they get used.
360 It also acts the slack for spawn_closefrom (including MIPS64 getdents64
361 where it might use about 1k extra stack space). */
362 argv_size
+= (32 * 1024);
363 size_t stack_size
= ALIGN_UP (argv_size
, GLRO(dl_pagesize
));
364 void *stack
= __mmap (NULL
, stack_size
, prot
,
365 MAP_PRIVATE
| MAP_ANONYMOUS
| MAP_STACK
, -1, 0);
366 if (__glibc_unlikely (stack
== MAP_FAILED
))
369 /* Disable asynchronous cancellation. */
371 __pthread_setcancelstate (PTHREAD_CANCEL_DISABLE
, &state
);
373 /* Child must set args.err to something non-negative - we rely on
374 the parent and child sharing VM. */
378 args
.fa
= file_actions
;
379 args
.attr
= attrp
? attrp
: &(const posix_spawnattr_t
) { 0 };
384 args
.xflags
= xflags
;
386 internal_signal_block_all (&args
.oldmask
);
388 /* The clone flags used will create a new child that will run in the same
389 memory space (CLONE_VM) and the execution of calling thread will be
390 suspend until the child calls execve or _exit.
392 Also since the calling thread execution will be suspend, there is not
393 need for CLONE_SETTLS. Although parent and child share the same TLS
394 namespace, there will be no concurrent access for TLS variables (errno
396 bool set_cgroup
= attrp
? (attrp
->__flags
& POSIX_SPAWN_SETCGROUP
) : false;
397 struct clone_args clone_args
=
399 /* Unsupported flags like CLONE_CLEAR_SIGHAND will be cleared up by
400 __clone_internal_fallback. */
401 .flags
= (set_cgroup
? CLONE_INTO_CGROUP
: 0)
402 | (use_pidfd
? CLONE_PIDFD
: 0)
403 | CLONE_CLEAR_SIGHAND
406 .exit_signal
= SIGCHLD
,
407 .stack
= (uintptr_t) stack
,
408 .stack_size
= stack_size
,
409 .cgroup
= (set_cgroup
? attrp
->__cgroup
: 0),
410 .pidfd
= use_pidfd
? (uintptr_t) &args
.pidfd
: 0,
411 /* This is require for clone fallback, where pidfd is returned
413 .parent_tid
= use_pidfd
? (uintptr_t) &args
.pidfd
: 0,
415 #ifdef HAVE_CLONE3_WRAPPER
416 args
.use_clone3
= true;
417 new_pid
= __clone3 (&clone_args
, sizeof (clone_args
), __spawni_child
,
419 /* clone3 was added in 5.3 and CLONE_CLEAR_SIGHAND in 5.5. */
420 if (new_pid
== -1 && (errno
== ENOSYS
|| errno
== EINVAL
))
423 args
.use_clone3
= false;
425 new_pid
= __clone_internal_fallback (&clone_args
, __spawni_child
,
429 /* No fallback for POSIX_SPAWN_SETCGROUP if clone3 is not
432 #ifdef HAVE_CLONE3_WRAPPER
439 /* It needs to collect the case where the auxiliary process was created
440 but failed to execute the file (due either any preparation step or
441 for execve itself). */
444 /* Also, it handles the unlikely case where the auxiliary process was
445 terminated before calling execve as if it was successfully. The
446 args.err is set to 0 as default and changed to a positive value
447 only in case of failure, so in case of premature termination
448 due a signal args.err will remain zeroed and it will be up to
449 caller to actually collect it. */
452 /* There still an unlikely case where the child is cancelled after
453 setting args.err, due to a positive error value. Also there is
454 possible pid reuse race (where the kernel allocated the same pid
455 to an unrelated process). Unfortunately due synchronization
456 issues where the kernel might not have the process collected
457 the waitpid below can not use WNOHANG. */
458 __waitpid (new_pid
, NULL
, 0);
463 __munmap (stack
, stack_size
);
465 if ((ec
== 0) && (pid
!= NULL
))
466 *pid
= use_pidfd
? args
.pidfd
: new_pid
;
468 internal_signal_restore_set (&args
.oldmask
);
470 __pthread_setcancelstate (state
, NULL
);
475 /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
476 Before running the process perform the actions described in FILE-ACTIONS. */
478 __spawni (pid_t
* pid
, const char *file
,
479 const posix_spawn_file_actions_t
* acts
,
480 const posix_spawnattr_t
* attrp
, char *const argv
[],
481 char *const envp
[], int xflags
)
483 /* It uses __execvpex to avoid run ENOEXEC in non compatibility mode (it
484 will be handled by maybe_script_execute). */
485 return __spawnix (pid
, file
, acts
, attrp
, argv
, envp
, xflags
,
486 xflags
& SPAWN_XFLAGS_USE_PATH
? __execvpex
:__execve
);