2010-03-14 03:49:55 -03:00
|
|
|
/* Authors: Gregory P. Smith & Jeffrey Yasskin */
|
|
|
|
#include "Python.h"
|
2020-10-13 17:04:44 -03:00
|
|
|
#include "pycore_fileutils.h"
|
2011-05-26 09:10:08 -03:00
|
|
|
#if defined(HAVE_PIPE2) && !defined(_GNU_SOURCE)
|
|
|
|
# define _GNU_SOURCE
|
2010-12-13 03:59:39 -04:00
|
|
|
#endif
|
2010-03-14 03:49:55 -03:00
|
|
|
#include <unistd.h>
|
2010-12-13 03:59:39 -04:00
|
|
|
#include <fcntl.h>
|
2012-01-21 18:01:08 -04:00
|
|
|
#ifdef HAVE_SYS_TYPES_H
|
|
|
|
#include <sys/types.h>
|
|
|
|
#endif
|
2019-10-12 17:24:56 -03:00
|
|
|
#if defined(HAVE_SYS_STAT_H)
|
2012-01-22 01:01:24 -04:00
|
|
|
#include <sys/stat.h>
|
|
|
|
#endif
|
2012-01-21 18:01:08 -04:00
|
|
|
#ifdef HAVE_SYS_SYSCALL_H
|
|
|
|
#include <sys/syscall.h>
|
|
|
|
#endif
|
2015-04-26 03:43:34 -03:00
|
|
|
#if defined(HAVE_SYS_RESOURCE_H)
|
|
|
|
#include <sys/resource.h>
|
|
|
|
#endif
|
2012-01-21 18:01:08 -04:00
|
|
|
#ifdef HAVE_DIRENT_H
|
|
|
|
#include <dirent.h>
|
|
|
|
#endif
|
2019-09-12 14:15:44 -03:00
|
|
|
#ifdef HAVE_GRP_H
|
|
|
|
#include <grp.h>
|
|
|
|
#endif /* HAVE_GRP_H */
|
|
|
|
|
|
|
|
#include "posixmodule.h"
|
2012-01-21 18:01:08 -04:00
|
|
|
|
2018-11-13 02:01:22 -04:00
|
|
|
#ifdef _Py_MEMORY_SANITIZER
|
2018-11-12 16:07:14 -04:00
|
|
|
# include <sanitizer/msan_interface.h>
|
|
|
|
#endif
|
|
|
|
|
2016-06-15 06:35:29 -03:00
|
|
|
#if defined(__ANDROID__) && __ANDROID_API__ < 21 && !defined(SYS_getdents64)
|
2014-04-14 17:31:21 -03:00
|
|
|
# include <sys/linux-syscalls.h>
|
|
|
|
# define SYS_getdents64 __NR_getdents64
|
|
|
|
#endif
|
|
|
|
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
#if defined(__linux__) && defined(HAVE_VFORK) && defined(HAVE_SIGNAL_H) && \
|
|
|
|
defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
|
2020-10-24 16:07:35 -03:00
|
|
|
/* If this is ever expanded to non-Linux platforms, verify what calls are
|
|
|
|
* allowed after vfork(). Ex: setsid() may be disallowed on macOS? */
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
# include <signal.h>
|
|
|
|
# define VFORK_USABLE 1
|
|
|
|
#endif
|
|
|
|
|
2018-12-30 22:16:40 -04:00
|
|
|
#if defined(__sun) && defined(__SVR4)
|
2012-01-21 19:16:17 -04:00
|
|
|
/* readdir64 is used to work around Solaris 9 bug 6395699. */
|
|
|
|
# define readdir readdir64
|
|
|
|
# define dirent dirent64
|
|
|
|
# if !defined(HAVE_DIRFD)
|
2012-01-21 18:01:08 -04:00
|
|
|
/* Some versions of Solaris lack dirfd(). */
|
2012-01-21 19:19:11 -04:00
|
|
|
# define dirfd(dirp) ((dirp)->dd_fd)
|
2012-01-21 19:16:17 -04:00
|
|
|
# define HAVE_DIRFD
|
|
|
|
# endif
|
2012-01-21 18:01:08 -04:00
|
|
|
#endif
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2020-11-19 03:24:15 -04:00
|
|
|
#if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__DragonFly__)
|
2012-01-22 01:01:24 -04:00
|
|
|
# define FD_DIR "/dev/fd"
|
|
|
|
#else
|
|
|
|
# define FD_DIR "/proc/self/fd"
|
|
|
|
#endif
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2019-09-12 14:15:44 -03:00
|
|
|
#ifdef NGROUPS_MAX
|
|
|
|
#define MAX_GROUPS NGROUPS_MAX
|
|
|
|
#else
|
|
|
|
#define MAX_GROUPS 64
|
|
|
|
#endif
|
|
|
|
|
2013-08-27 19:53:59 -03:00
|
|
|
#define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0)
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2019-09-10 08:01:20 -03:00
|
|
|
typedef struct {
|
|
|
|
PyObject* disable;
|
|
|
|
PyObject* enable;
|
|
|
|
PyObject* isenabled;
|
|
|
|
} _posixsubprocessstate;
|
|
|
|
|
|
|
|
static struct PyModuleDef _posixsubprocessmodule;
|
|
|
|
|
2020-03-16 10:15:01 -03:00
|
|
|
static inline _posixsubprocessstate*
|
|
|
|
get_posixsubprocess_state(PyObject *module)
|
|
|
|
{
|
|
|
|
void *state = PyModule_GetState(module);
|
|
|
|
assert(state != NULL);
|
|
|
|
return (_posixsubprocessstate *)state;
|
|
|
|
}
|
|
|
|
|
2020-11-01 01:33:08 -04:00
|
|
|
/* If gc was disabled, call gc.enable(). Ignore errors. */
|
|
|
|
static void
|
2020-11-21 15:28:14 -04:00
|
|
|
_enable_gc(int need_to_reenable_gc, PyObject *gc_module, _posixsubprocessstate *state)
|
2010-03-14 03:49:55 -03:00
|
|
|
{
|
|
|
|
PyObject *result;
|
2015-11-29 22:21:41 -04:00
|
|
|
PyObject *exctype, *val, *tb;
|
2011-10-09 05:38:36 -03:00
|
|
|
|
2015-11-29 22:21:41 -04:00
|
|
|
if (need_to_reenable_gc) {
|
|
|
|
PyErr_Fetch(&exctype, &val, &tb);
|
2020-02-11 12:46:57 -04:00
|
|
|
result = PyObject_CallMethodNoArgs(
|
2020-11-21 15:28:14 -04:00
|
|
|
gc_module, state->enable);
|
2020-11-01 01:33:08 -04:00
|
|
|
if (result == NULL) {
|
|
|
|
/* We might have created a child process at this point, we
|
|
|
|
* we have no good way to handle a failure to reenable GC
|
|
|
|
* and return information about the child process. */
|
|
|
|
PyErr_Print();
|
|
|
|
}
|
|
|
|
Py_XDECREF(result);
|
2015-11-29 22:21:41 -04:00
|
|
|
if (exctype != NULL) {
|
|
|
|
PyErr_Restore(exctype, val, tb);
|
|
|
|
}
|
|
|
|
}
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2012-01-21 18:01:08 -04:00
|
|
|
/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
|
2012-01-22 21:04:46 -04:00
|
|
|
static int
|
2015-12-25 14:01:53 -04:00
|
|
|
_pos_int_from_ascii(const char *name)
|
2012-01-21 18:01:08 -04:00
|
|
|
{
|
|
|
|
int num = 0;
|
|
|
|
while (*name >= '0' && *name <= '9') {
|
|
|
|
num = num * 10 + (*name - '0');
|
|
|
|
++name;
|
|
|
|
}
|
|
|
|
if (*name)
|
|
|
|
return -1; /* Non digit found, not a number. */
|
|
|
|
return num;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-11-19 03:24:15 -04:00
|
|
|
#if defined(__FreeBSD__) || defined(__DragonFly__)
|
2012-01-22 01:01:24 -04:00
|
|
|
/* When /dev/fd isn't mounted it is often a static directory populated
|
2020-11-19 03:24:15 -04:00
|
|
|
* with 0 1 2 or entries for 0 .. 63 on FreeBSD, NetBSD, OpenBSD and DragonFlyBSD.
|
2012-01-22 01:01:24 -04:00
|
|
|
* NetBSD and OpenBSD have a /proc fs available (though not necessarily
|
|
|
|
* mounted) and do not have fdescfs for /dev/fd. MacOS X has a devfs
|
|
|
|
* that properly supports /dev/fd.
|
|
|
|
*/
|
2012-01-22 21:04:46 -04:00
|
|
|
static int
|
2012-03-07 14:06:33 -04:00
|
|
|
_is_fdescfs_mounted_on_dev_fd(void)
|
2012-01-22 01:01:24 -04:00
|
|
|
{
|
|
|
|
struct stat dev_stat;
|
|
|
|
struct stat dev_fd_stat;
|
|
|
|
if (stat("/dev", &dev_stat) != 0)
|
|
|
|
return 0;
|
|
|
|
if (stat(FD_DIR, &dev_fd_stat) != 0)
|
2013-08-27 19:53:59 -03:00
|
|
|
return 0;
|
2012-01-22 01:01:24 -04:00
|
|
|
if (dev_stat.st_dev == dev_fd_stat.st_dev)
|
|
|
|
return 0; /* / == /dev == /dev/fd means it is static. #fail */
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
2012-01-21 18:01:08 -04:00
|
|
|
/* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
|
2012-01-22 21:04:46 -04:00
|
|
|
static int
|
|
|
|
_sanity_check_python_fd_sequence(PyObject *fd_sequence)
|
2012-01-21 18:01:08 -04:00
|
|
|
{
|
2017-04-19 15:12:46 -03:00
|
|
|
Py_ssize_t seq_idx;
|
2012-01-21 18:01:08 -04:00
|
|
|
long prev_fd = -1;
|
2017-04-19 15:12:46 -03:00
|
|
|
for (seq_idx = 0; seq_idx < PyTuple_GET_SIZE(fd_sequence); ++seq_idx) {
|
|
|
|
PyObject* py_fd = PyTuple_GET_ITEM(fd_sequence, seq_idx);
|
|
|
|
long iter_fd;
|
|
|
|
if (!PyLong_Check(py_fd)) {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
iter_fd = PyLong_AsLong(py_fd);
|
2015-11-16 01:15:26 -04:00
|
|
|
if (iter_fd < 0 || iter_fd <= prev_fd || iter_fd > INT_MAX) {
|
2017-04-19 15:12:46 -03:00
|
|
|
/* Negative, overflow, unsorted, too big for a fd. */
|
2012-01-21 18:01:08 -04:00
|
|
|
return 1;
|
|
|
|
}
|
2015-11-16 01:15:26 -04:00
|
|
|
prev_fd = iter_fd;
|
2012-01-21 18:01:08 -04:00
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* Is fd found in the sorted Python Sequence? */
|
2012-01-22 21:04:46 -04:00
|
|
|
static int
|
|
|
|
_is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
|
2012-01-21 18:01:08 -04:00
|
|
|
{
|
|
|
|
/* Binary search. */
|
|
|
|
Py_ssize_t search_min = 0;
|
2017-04-19 15:12:46 -03:00
|
|
|
Py_ssize_t search_max = PyTuple_GET_SIZE(fd_sequence) - 1;
|
2012-01-21 18:01:08 -04:00
|
|
|
if (search_max < 0)
|
|
|
|
return 0;
|
|
|
|
do {
|
|
|
|
long middle = (search_min + search_max) / 2;
|
2017-04-19 15:12:46 -03:00
|
|
|
long middle_fd = PyLong_AsLong(PyTuple_GET_ITEM(fd_sequence, middle));
|
2012-01-21 18:01:08 -04:00
|
|
|
if (fd == middle_fd)
|
|
|
|
return 1;
|
|
|
|
if (fd > middle_fd)
|
|
|
|
search_min = middle + 1;
|
|
|
|
else
|
|
|
|
search_max = middle - 1;
|
|
|
|
} while (search_min <= search_max);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2013-08-27 19:53:59 -03:00
|
|
|
static int
|
|
|
|
make_inheritable(PyObject *py_fds_to_keep, int errpipe_write)
|
|
|
|
{
|
|
|
|
Py_ssize_t i, len;
|
|
|
|
|
2017-04-19 15:12:46 -03:00
|
|
|
len = PyTuple_GET_SIZE(py_fds_to_keep);
|
2013-08-27 19:53:59 -03:00
|
|
|
for (i = 0; i < len; ++i) {
|
2017-04-19 15:12:46 -03:00
|
|
|
PyObject* fdobj = PyTuple_GET_ITEM(py_fds_to_keep, i);
|
2013-08-27 19:53:59 -03:00
|
|
|
long fd = PyLong_AsLong(fdobj);
|
|
|
|
assert(!PyErr_Occurred());
|
|
|
|
assert(0 <= fd && fd <= INT_MAX);
|
|
|
|
if (fd == errpipe_write) {
|
|
|
|
/* errpipe_write is part of py_fds_to_keep. It must be closed at
|
|
|
|
exec(), but kept open in the child process until exec() is
|
|
|
|
called. */
|
|
|
|
continue;
|
|
|
|
}
|
2018-02-06 02:09:34 -04:00
|
|
|
if (_Py_set_inheritable_async_safe((int)fd, 1, NULL) < 0)
|
2013-08-27 19:53:59 -03:00
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2012-01-21 18:01:08 -04:00
|
|
|
|
2014-06-01 17:18:28 -03:00
|
|
|
/* Get the maximum file descriptor that could be opened by this process.
|
|
|
|
* This function is async signal safe for use between fork() and exec().
|
|
|
|
*/
|
|
|
|
static long
|
|
|
|
safe_get_max_fd(void)
|
|
|
|
{
|
|
|
|
long local_max_fd;
|
|
|
|
#if defined(__NetBSD__)
|
|
|
|
local_max_fd = fcntl(0, F_MAXFD);
|
|
|
|
if (local_max_fd >= 0)
|
|
|
|
return local_max_fd;
|
|
|
|
#endif
|
2015-04-26 03:43:34 -03:00
|
|
|
#if defined(HAVE_SYS_RESOURCE_H) && defined(__OpenBSD__)
|
|
|
|
struct rlimit rl;
|
|
|
|
/* Not on the POSIX async signal safe functions list but likely
|
|
|
|
* safe. TODO - Someone should audit OpenBSD to make sure. */
|
|
|
|
if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
|
|
|
|
return (long) rl.rlim_max;
|
|
|
|
#endif
|
2014-06-01 17:18:28 -03:00
|
|
|
#ifdef _SC_OPEN_MAX
|
|
|
|
local_max_fd = sysconf(_SC_OPEN_MAX);
|
|
|
|
if (local_max_fd == -1)
|
|
|
|
#endif
|
|
|
|
local_max_fd = 256; /* Matches legacy Lib/subprocess.py behavior. */
|
|
|
|
return local_max_fd;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* Close all file descriptors in the range from start_fd and higher
|
|
|
|
* except for those in py_fds_to_keep. If the range defined by
|
|
|
|
* [start_fd, safe_get_max_fd()) is large this will take a long
|
|
|
|
* time as it calls close() on EVERY possible fd.
|
|
|
|
*
|
|
|
|
* It isn't possible to know for sure what the max fd to go up to
|
|
|
|
* is for processes with the capability of raising their maximum.
|
2012-01-21 18:01:08 -04:00
|
|
|
*/
|
2012-01-22 21:04:46 -04:00
|
|
|
static void
|
2014-06-01 17:18:28 -03:00
|
|
|
_close_fds_by_brute_force(long start_fd, PyObject *py_fds_to_keep)
|
2012-01-21 18:01:08 -04:00
|
|
|
{
|
2014-06-01 17:18:28 -03:00
|
|
|
long end_fd = safe_get_max_fd();
|
2017-04-19 15:12:46 -03:00
|
|
|
Py_ssize_t num_fds_to_keep = PyTuple_GET_SIZE(py_fds_to_keep);
|
2012-01-21 18:01:08 -04:00
|
|
|
Py_ssize_t keep_seq_idx;
|
|
|
|
/* As py_fds_to_keep is sorted we can loop through the list closing
|
2017-11-05 09:37:50 -04:00
|
|
|
* fds in between any in the keep list falling within our range. */
|
2012-01-21 18:01:08 -04:00
|
|
|
for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
|
2017-04-19 15:12:46 -03:00
|
|
|
PyObject* py_keep_fd = PyTuple_GET_ITEM(py_fds_to_keep, keep_seq_idx);
|
2012-01-21 18:01:08 -04:00
|
|
|
int keep_fd = PyLong_AsLong(py_keep_fd);
|
|
|
|
if (keep_fd < start_fd)
|
|
|
|
continue;
|
2020-10-11 15:54:11 -03:00
|
|
|
_Py_closerange(start_fd, keep_fd - 1);
|
2012-01-21 18:01:08 -04:00
|
|
|
start_fd = keep_fd + 1;
|
|
|
|
}
|
|
|
|
if (start_fd <= end_fd) {
|
2020-10-11 15:54:11 -03:00
|
|
|
_Py_closerange(start_fd, end_fd);
|
2012-01-21 18:01:08 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
|
|
|
|
/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
|
|
|
|
* only to read a directory of short file descriptor number names. The kernel
|
|
|
|
* will return an error if we didn't give it enough space. Highly Unlikely.
|
|
|
|
* This structure is very old and stable: It will not change unless the kernel
|
|
|
|
* chooses to break compatibility with all existing binaries. Highly Unlikely.
|
|
|
|
*/
|
2013-03-03 14:45:05 -04:00
|
|
|
struct linux_dirent64 {
|
2012-06-05 17:26:39 -03:00
|
|
|
unsigned long long d_ino;
|
2013-03-03 14:45:05 -04:00
|
|
|
long long d_off;
|
2012-01-21 18:01:08 -04:00
|
|
|
unsigned short d_reclen; /* Length of this linux_dirent */
|
2013-03-03 14:45:05 -04:00
|
|
|
unsigned char d_type;
|
2012-01-21 18:01:08 -04:00
|
|
|
char d_name[256]; /* Filename (null-terminated) */
|
|
|
|
};
|
|
|
|
|
2014-06-01 17:46:36 -03:00
|
|
|
/* Close all open file descriptors in the range from start_fd and higher
|
|
|
|
* Do not close any in the sorted py_fds_to_keep list.
|
2012-01-21 18:01:08 -04:00
|
|
|
*
|
|
|
|
* This version is async signal safe as it does not make any unsafe C library
|
|
|
|
* calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
|
|
|
|
* to resort to making a kernel system call directly but this is the ONLY api
|
|
|
|
* available that does no harm. opendir/readdir/closedir perform memory
|
|
|
|
* allocation and locking so while they usually work they are not guaranteed
|
|
|
|
* to (especially if you have replaced your malloc implementation). A version
|
|
|
|
* of this function that uses those can be found in the _maybe_unsafe variant.
|
|
|
|
*
|
|
|
|
* This is Linux specific because that is all I am ready to test it on. It
|
|
|
|
* should be easy to add OS specific dirent or dirent64 structures and modify
|
|
|
|
* it with some cpp #define magic to work on other OSes as well if you want.
|
|
|
|
*/
|
2012-01-22 21:04:46 -04:00
|
|
|
static void
|
2014-06-01 17:18:28 -03:00
|
|
|
_close_open_fds_safe(int start_fd, PyObject* py_fds_to_keep)
|
2012-01-21 18:01:08 -04:00
|
|
|
{
|
|
|
|
int fd_dir_fd;
|
2013-08-27 19:53:59 -03:00
|
|
|
|
2015-03-29 21:18:31 -03:00
|
|
|
fd_dir_fd = _Py_open_noraise(FD_DIR, O_RDONLY);
|
2012-01-21 18:01:08 -04:00
|
|
|
if (fd_dir_fd == -1) {
|
|
|
|
/* No way to get a list of open fds. */
|
2014-06-01 17:18:28 -03:00
|
|
|
_close_fds_by_brute_force(start_fd, py_fds_to_keep);
|
2012-01-21 18:01:08 -04:00
|
|
|
return;
|
|
|
|
} else {
|
2013-03-03 14:45:05 -04:00
|
|
|
char buffer[sizeof(struct linux_dirent64)];
|
2012-01-21 18:01:08 -04:00
|
|
|
int bytes;
|
2013-03-03 14:45:05 -04:00
|
|
|
while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
|
|
|
|
(struct linux_dirent64 *)buffer,
|
2012-01-21 18:01:08 -04:00
|
|
|
sizeof(buffer))) > 0) {
|
2013-03-03 14:45:05 -04:00
|
|
|
struct linux_dirent64 *entry;
|
2012-01-21 18:01:08 -04:00
|
|
|
int offset;
|
2018-11-13 02:01:22 -04:00
|
|
|
#ifdef _Py_MEMORY_SANITIZER
|
2018-11-12 16:07:14 -04:00
|
|
|
__msan_unpoison(buffer, bytes);
|
|
|
|
#endif
|
2012-01-21 18:01:08 -04:00
|
|
|
for (offset = 0; offset < bytes; offset += entry->d_reclen) {
|
|
|
|
int fd;
|
2013-03-03 14:45:05 -04:00
|
|
|
entry = (struct linux_dirent64 *)(buffer + offset);
|
2012-01-21 18:01:08 -04:00
|
|
|
if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
|
|
|
|
continue; /* Not a number. */
|
2014-06-01 17:18:28 -03:00
|
|
|
if (fd != fd_dir_fd && fd >= start_fd &&
|
2012-01-21 18:01:08 -04:00
|
|
|
!_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
|
2015-04-02 11:24:46 -03:00
|
|
|
close(fd);
|
2012-01-21 18:01:08 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-04-02 11:24:46 -03:00
|
|
|
close(fd_dir_fd);
|
2012-01-21 18:01:08 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-06-01 17:18:28 -03:00
|
|
|
#define _close_open_fds _close_open_fds_safe
|
2012-01-21 18:01:08 -04:00
|
|
|
|
|
|
|
#else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
|
|
|
|
|
|
|
|
|
2014-06-01 17:18:28 -03:00
|
|
|
/* Close all open file descriptors from start_fd and higher.
|
2017-04-19 15:12:46 -03:00
|
|
|
* Do not close any in the sorted py_fds_to_keep tuple.
|
2012-01-21 18:01:08 -04:00
|
|
|
*
|
|
|
|
* This function violates the strict use of async signal safe functions. :(
|
2012-01-21 19:16:17 -04:00
|
|
|
* It calls opendir(), readdir() and closedir(). Of these, the one most
|
2012-01-21 18:01:08 -04:00
|
|
|
* likely to ever cause a problem is opendir() as it performs an internal
|
|
|
|
* malloc(). Practically this should not be a problem. The Java VM makes the
|
|
|
|
* same calls between fork and exec in its own UNIXProcess_md.c implementation.
|
|
|
|
*
|
|
|
|
* readdir_r() is not used because it provides no benefit. It is typically
|
|
|
|
* implemented as readdir() followed by memcpy(). See also:
|
|
|
|
* http://womble.decadent.org.uk/readdir_r-advisory.html
|
|
|
|
*/
|
2012-01-22 21:04:46 -04:00
|
|
|
static void
|
2014-06-01 17:18:28 -03:00
|
|
|
_close_open_fds_maybe_unsafe(long start_fd, PyObject* py_fds_to_keep)
|
2012-01-21 18:01:08 -04:00
|
|
|
{
|
|
|
|
DIR *proc_fd_dir;
|
|
|
|
#ifndef HAVE_DIRFD
|
2014-06-01 17:18:28 -03:00
|
|
|
while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep)) {
|
2012-01-21 18:01:08 -04:00
|
|
|
++start_fd;
|
|
|
|
}
|
|
|
|
/* Close our lowest fd before we call opendir so that it is likely to
|
|
|
|
* reuse that fd otherwise we might close opendir's file descriptor in
|
|
|
|
* our loop. This trick assumes that fd's are allocated on a lowest
|
|
|
|
* available basis. */
|
2015-04-02 11:24:46 -03:00
|
|
|
close(start_fd);
|
2012-01-21 18:01:08 -04:00
|
|
|
++start_fd;
|
|
|
|
#endif
|
|
|
|
|
2020-11-19 03:24:15 -04:00
|
|
|
#if defined(__FreeBSD__) || defined(__DragonFly__)
|
2012-01-22 01:01:24 -04:00
|
|
|
if (!_is_fdescfs_mounted_on_dev_fd())
|
|
|
|
proc_fd_dir = NULL;
|
|
|
|
else
|
|
|
|
#endif
|
|
|
|
proc_fd_dir = opendir(FD_DIR);
|
2012-01-21 18:01:08 -04:00
|
|
|
if (!proc_fd_dir) {
|
|
|
|
/* No way to get a list of open fds. */
|
2014-06-01 17:18:28 -03:00
|
|
|
_close_fds_by_brute_force(start_fd, py_fds_to_keep);
|
2012-01-21 18:01:08 -04:00
|
|
|
} else {
|
2012-01-21 19:16:17 -04:00
|
|
|
struct dirent *dir_entry;
|
2012-01-21 18:01:08 -04:00
|
|
|
#ifdef HAVE_DIRFD
|
2012-01-21 19:19:11 -04:00
|
|
|
int fd_used_by_opendir = dirfd(proc_fd_dir);
|
2012-01-21 18:01:08 -04:00
|
|
|
#else
|
|
|
|
int fd_used_by_opendir = start_fd - 1;
|
|
|
|
#endif
|
|
|
|
errno = 0;
|
2012-01-21 19:16:17 -04:00
|
|
|
while ((dir_entry = readdir(proc_fd_dir))) {
|
2012-01-21 18:01:08 -04:00
|
|
|
int fd;
|
|
|
|
if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
|
|
|
|
continue; /* Not a number. */
|
2014-06-01 17:18:28 -03:00
|
|
|
if (fd != fd_used_by_opendir && fd >= start_fd &&
|
2012-01-21 18:01:08 -04:00
|
|
|
!_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
|
2015-04-02 11:24:46 -03:00
|
|
|
close(fd);
|
2012-01-21 18:01:08 -04:00
|
|
|
}
|
|
|
|
errno = 0;
|
|
|
|
}
|
|
|
|
if (errno) {
|
|
|
|
/* readdir error, revert behavior. Highly Unlikely. */
|
2014-06-01 17:18:28 -03:00
|
|
|
_close_fds_by_brute_force(start_fd, py_fds_to_keep);
|
2012-01-21 18:01:08 -04:00
|
|
|
}
|
|
|
|
closedir(proc_fd_dir);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-06-01 17:18:28 -03:00
|
|
|
#define _close_open_fds _close_open_fds_maybe_unsafe
|
2012-01-21 18:01:08 -04:00
|
|
|
|
|
|
|
#endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
|
|
|
|
|
|
|
|
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
#ifdef VFORK_USABLE
|
|
|
|
/* Reset dispositions for all signals to SIG_DFL except for ignored
|
|
|
|
* signals. This way we ensure that no signal handlers can run
|
|
|
|
* after we unblock signals in a child created by vfork().
|
|
|
|
*/
|
|
|
|
static void
|
|
|
|
reset_signal_handlers(const sigset_t *child_sigmask)
|
|
|
|
{
|
|
|
|
struct sigaction sa_dfl = {.sa_handler = SIG_DFL};
|
|
|
|
for (int sig = 1; sig < _NSIG; sig++) {
|
|
|
|
/* Dispositions for SIGKILL and SIGSTOP can't be changed. */
|
|
|
|
if (sig == SIGKILL || sig == SIGSTOP) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* There is no need to reset the disposition of signals that will
|
|
|
|
* remain blocked across execve() since the kernel will do it. */
|
|
|
|
if (sigismember(child_sigmask, sig) == 1) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
struct sigaction sa;
|
|
|
|
/* C libraries usually return EINVAL for signals used
|
|
|
|
* internally (e.g. for thread cancellation), so simply
|
|
|
|
* skip errors here. */
|
|
|
|
if (sigaction(sig, NULL, &sa) == -1) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* void *h works as these fields are both pointer types already. */
|
|
|
|
void *h = (sa.sa_flags & SA_SIGINFO ? (void *)sa.sa_sigaction :
|
|
|
|
(void *)sa.sa_handler);
|
|
|
|
if (h == SIG_IGN || h == SIG_DFL) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* This call can't reasonably fail, but if it does, terminating
|
|
|
|
* the child seems to be too harsh, so ignore errors. */
|
|
|
|
(void) sigaction(sig, &sa_dfl, NULL);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#endif /* VFORK_USABLE */
|
|
|
|
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
/*
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
* This function is code executed in the child process immediately after
|
|
|
|
* (v)fork to set things up and call exec().
|
2010-03-14 03:49:55 -03:00
|
|
|
*
|
|
|
|
* All of the code in this function must only use async-signal-safe functions,
|
|
|
|
* listed at `man 7 signal` or
|
|
|
|
* http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
|
|
|
|
*
|
|
|
|
* This restriction is documented at
|
|
|
|
* http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
*
|
|
|
|
* If this function is called after vfork(), even more care must be taken.
|
|
|
|
* The lack of preparations that C libraries normally take on fork(),
|
|
|
|
* as well as sharing the address space with the parent, might make even
|
|
|
|
* async-signal-safe functions vfork-unsafe. In particular, on Linux,
|
|
|
|
* set*id() and setgroups() library functions must not be called, since
|
|
|
|
* they have to interact with the library-level thread list and send
|
|
|
|
* library-internal signals to implement per-process credentials semantics
|
|
|
|
* required by POSIX but not supported natively on Linux. Another reason to
|
|
|
|
* avoid this family of functions is that sharing an address space between
|
|
|
|
* processes running with different privileges is inherently insecure.
|
|
|
|
* See bpo-35823 for further discussion and references.
|
|
|
|
*
|
|
|
|
* In some C libraries, setrlimit() has the same thread list/signalling
|
|
|
|
* behavior since resource limits were per-thread attributes before
|
|
|
|
* Linux 2.6.10. Musl, as of 1.2.1, is known to have this issue
|
|
|
|
* (https://www.openwall.com/lists/musl/2020/10/15/6).
|
|
|
|
*
|
|
|
|
* If vfork-unsafe functionality is desired after vfork(), consider using
|
|
|
|
* syscall() to obtain it.
|
2010-03-14 03:49:55 -03:00
|
|
|
*/
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
_Py_NO_INLINE static void
|
2012-01-22 21:04:46 -04:00
|
|
|
child_exec(char *const exec_array[],
|
|
|
|
char *const argv[],
|
|
|
|
char *const envp[],
|
|
|
|
const char *cwd,
|
|
|
|
int p2cread, int p2cwrite,
|
|
|
|
int c2pread, int c2pwrite,
|
|
|
|
int errread, int errwrite,
|
|
|
|
int errpipe_read, int errpipe_write,
|
|
|
|
int close_fds, int restore_signals,
|
|
|
|
int call_setsid,
|
2019-09-12 14:15:44 -03:00
|
|
|
int call_setgid, gid_t gid,
|
|
|
|
int call_setgroups, size_t groups_size, const gid_t *groups,
|
2019-10-12 17:24:56 -03:00
|
|
|
int call_setuid, uid_t uid, int child_umask,
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
const void *child_sigmask,
|
2012-01-22 21:04:46 -04:00
|
|
|
PyObject *py_fds_to_keep,
|
|
|
|
PyObject *preexec_fn,
|
|
|
|
PyObject *preexec_fn_args_tuple)
|
2010-03-14 03:49:55 -03:00
|
|
|
{
|
2015-04-01 13:35:53 -03:00
|
|
|
int i, saved_errno, reached_preexec = 0;
|
2010-03-14 03:49:55 -03:00
|
|
|
PyObject *result;
|
2010-12-22 01:22:17 -04:00
|
|
|
const char* err_msg = "";
|
2010-03-14 03:49:55 -03:00
|
|
|
/* Buffer large enough to hold a hex integer. We can't malloc. */
|
|
|
|
char hex_errno[sizeof(saved_errno)*2+1];
|
|
|
|
|
2013-08-27 19:53:59 -03:00
|
|
|
if (make_inheritable(py_fds_to_keep, errpipe_write) < 0)
|
|
|
|
goto error;
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
/* Close parent's pipe ends. */
|
2013-08-27 19:53:59 -03:00
|
|
|
if (p2cwrite != -1)
|
2010-03-14 03:49:55 -03:00
|
|
|
POSIX_CALL(close(p2cwrite));
|
2013-08-27 19:53:59 -03:00
|
|
|
if (c2pread != -1)
|
2010-03-14 03:49:55 -03:00
|
|
|
POSIX_CALL(close(c2pread));
|
2013-08-27 19:53:59 -03:00
|
|
|
if (errread != -1)
|
2010-03-14 03:49:55 -03:00
|
|
|
POSIX_CALL(close(errread));
|
|
|
|
POSIX_CALL(close(errpipe_read));
|
|
|
|
|
2011-07-27 02:16:31 -03:00
|
|
|
/* When duping fds, if there arises a situation where one of the fds is
|
|
|
|
either 0, 1 or 2, it is possible that it is overwritten (#12607). */
|
2018-09-10 21:46:22 -03:00
|
|
|
if (c2pwrite == 0) {
|
2011-07-27 02:16:31 -03:00
|
|
|
POSIX_CALL(c2pwrite = dup(c2pwrite));
|
2018-09-10 21:46:22 -03:00
|
|
|
/* issue32270 */
|
|
|
|
if (_Py_set_inheritable_async_safe(c2pwrite, 0, NULL) < 0) {
|
|
|
|
goto error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
while (errwrite == 0 || errwrite == 1) {
|
2011-07-27 02:16:31 -03:00
|
|
|
POSIX_CALL(errwrite = dup(errwrite));
|
2018-09-10 21:46:22 -03:00
|
|
|
/* issue32270 */
|
|
|
|
if (_Py_set_inheritable_async_safe(errwrite, 0, NULL) < 0) {
|
|
|
|
goto error;
|
|
|
|
}
|
|
|
|
}
|
2011-07-27 02:16:31 -03:00
|
|
|
|
2011-01-03 14:23:55 -04:00
|
|
|
/* Dup fds for child.
|
|
|
|
dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
|
|
|
|
would be a no-op (issue #10806). */
|
|
|
|
if (p2cread == 0) {
|
2018-02-06 02:09:34 -04:00
|
|
|
if (_Py_set_inheritable_async_safe(p2cread, 1, NULL) < 0)
|
2013-08-27 19:53:59 -03:00
|
|
|
goto error;
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
2013-08-27 19:53:59 -03:00
|
|
|
else if (p2cread != -1)
|
|
|
|
POSIX_CALL(dup2(p2cread, 0)); /* stdin */
|
|
|
|
|
2011-01-03 14:23:55 -04:00
|
|
|
if (c2pwrite == 1) {
|
2018-02-06 02:09:34 -04:00
|
|
|
if (_Py_set_inheritable_async_safe(c2pwrite, 1, NULL) < 0)
|
2013-08-27 19:53:59 -03:00
|
|
|
goto error;
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
2013-08-27 19:53:59 -03:00
|
|
|
else if (c2pwrite != -1)
|
|
|
|
POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
|
|
|
|
|
2011-01-03 14:23:55 -04:00
|
|
|
if (errwrite == 2) {
|
2018-02-06 02:09:34 -04:00
|
|
|
if (_Py_set_inheritable_async_safe(errwrite, 1, NULL) < 0)
|
2013-08-27 19:53:59 -03:00
|
|
|
goto error;
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
2013-08-27 19:53:59 -03:00
|
|
|
else if (errwrite != -1)
|
|
|
|
POSIX_CALL(dup2(errwrite, 2)); /* stderr */
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2018-09-10 21:46:22 -03:00
|
|
|
/* We no longer manually close p2cread, c2pwrite, and errwrite here as
|
|
|
|
* _close_open_fds takes care when it is not already non-inheritable. */
|
2010-03-14 03:49:55 -03:00
|
|
|
|
|
|
|
if (cwd)
|
|
|
|
POSIX_CALL(chdir(cwd));
|
|
|
|
|
2019-10-12 17:24:56 -03:00
|
|
|
if (child_umask >= 0)
|
|
|
|
umask(child_umask); /* umask() always succeeds. */
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
if (restore_signals)
|
|
|
|
_Py_RestoreSignals();
|
|
|
|
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
#ifdef VFORK_USABLE
|
|
|
|
if (child_sigmask) {
|
|
|
|
reset_signal_handlers(child_sigmask);
|
2020-10-24 14:47:38 -03:00
|
|
|
if ((errno = pthread_sigmask(SIG_SETMASK, child_sigmask, NULL))) {
|
|
|
|
goto error;
|
|
|
|
}
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
#ifdef HAVE_SETSID
|
|
|
|
if (call_setsid)
|
|
|
|
POSIX_CALL(setsid());
|
|
|
|
#endif
|
|
|
|
|
2019-09-12 14:15:44 -03:00
|
|
|
#ifdef HAVE_SETGROUPS
|
|
|
|
if (call_setgroups)
|
|
|
|
POSIX_CALL(setgroups(groups_size, groups));
|
|
|
|
#endif /* HAVE_SETGROUPS */
|
|
|
|
|
|
|
|
#ifdef HAVE_SETREGID
|
|
|
|
if (call_setgid)
|
|
|
|
POSIX_CALL(setregid(gid, gid));
|
|
|
|
#endif /* HAVE_SETREGID */
|
|
|
|
|
|
|
|
#ifdef HAVE_SETREUID
|
|
|
|
if (call_setuid)
|
|
|
|
POSIX_CALL(setreuid(uid, uid));
|
|
|
|
#endif /* HAVE_SETREUID */
|
|
|
|
|
|
|
|
|
2012-10-10 07:34:47 -03:00
|
|
|
reached_preexec = 1;
|
2010-03-14 03:49:55 -03:00
|
|
|
if (preexec_fn != Py_None && preexec_fn_args_tuple) {
|
|
|
|
/* This is where the user has asked us to deadlock their program. */
|
|
|
|
result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
|
|
|
|
if (result == NULL) {
|
|
|
|
/* Stringifying the exception or traceback would involve
|
|
|
|
* memory allocation and thus potential for deadlock.
|
|
|
|
* We've already faced potential deadlock by calling back
|
|
|
|
* into Python in the first place, so it probably doesn't
|
|
|
|
* matter but we avoid it to minimize the possibility. */
|
|
|
|
err_msg = "Exception occurred in preexec_fn.";
|
|
|
|
errno = 0; /* We don't want to report an OSError. */
|
|
|
|
goto error;
|
|
|
|
}
|
|
|
|
/* Py_DECREF(result); - We're about to exec so why bother? */
|
|
|
|
}
|
|
|
|
|
2013-08-25 13:24:45 -03:00
|
|
|
/* close FDs after executing preexec_fn, which might open FDs */
|
|
|
|
if (close_fds) {
|
|
|
|
/* TODO HP-UX could use pstat_getproc() if anyone cares about it. */
|
2014-06-01 17:18:28 -03:00
|
|
|
_close_open_fds(3, py_fds_to_keep);
|
2013-08-25 13:24:45 -03:00
|
|
|
}
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
/* This loop matches the Lib/os.py _execvpe()'s PATH search when */
|
|
|
|
/* given the executable_list generated by Lib/subprocess.py. */
|
|
|
|
saved_errno = 0;
|
|
|
|
for (i = 0; exec_array[i] != NULL; ++i) {
|
|
|
|
const char *executable = exec_array[i];
|
|
|
|
if (envp) {
|
|
|
|
execve(executable, argv, envp);
|
|
|
|
} else {
|
|
|
|
execv(executable, argv);
|
|
|
|
}
|
|
|
|
if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
|
|
|
|
saved_errno = errno;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Report the first exec error, not the last. */
|
|
|
|
if (saved_errno)
|
|
|
|
errno = saved_errno;
|
|
|
|
|
|
|
|
error:
|
|
|
|
saved_errno = errno;
|
|
|
|
/* Report the posix error to our parent process. */
|
2012-01-21 16:31:25 -04:00
|
|
|
/* We ignore all write() return values as the total size of our writes is
|
2015-04-01 13:35:53 -03:00
|
|
|
less than PIPEBUF and we cannot do anything about an error anyways.
|
|
|
|
Use _Py_write_noraise() to retry write() if it is interrupted by a
|
|
|
|
signal (fails with EINTR). */
|
2010-03-14 03:49:55 -03:00
|
|
|
if (saved_errno) {
|
|
|
|
char *cur;
|
2015-04-01 13:35:53 -03:00
|
|
|
_Py_write_noraise(errpipe_write, "OSError:", 8);
|
2010-03-14 03:49:55 -03:00
|
|
|
cur = hex_errno + sizeof(hex_errno);
|
2016-09-27 16:03:51 -03:00
|
|
|
while (saved_errno != 0 && cur != hex_errno) {
|
2015-04-25 20:42:38 -03:00
|
|
|
*--cur = Py_hexdigits[saved_errno % 16];
|
2010-03-14 03:49:55 -03:00
|
|
|
saved_errno /= 16;
|
|
|
|
}
|
2015-04-01 13:35:53 -03:00
|
|
|
_Py_write_noraise(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
|
|
|
|
_Py_write_noraise(errpipe_write, ":", 1);
|
2012-10-10 07:34:47 -03:00
|
|
|
if (!reached_preexec) {
|
|
|
|
/* Indicate to the parent that the error happened before exec(). */
|
2015-04-01 13:35:53 -03:00
|
|
|
_Py_write_noraise(errpipe_write, "noexec", 6);
|
2012-10-10 07:34:47 -03:00
|
|
|
}
|
2010-03-14 03:49:55 -03:00
|
|
|
/* We can't call strerror(saved_errno). It is not async signal safe.
|
|
|
|
* The parent process will look the error message up. */
|
|
|
|
} else {
|
2015-04-01 13:35:53 -03:00
|
|
|
_Py_write_noraise(errpipe_write, "SubprocessError:0:", 18);
|
|
|
|
_Py_write_noraise(errpipe_write, err_msg, strlen(err_msg));
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
/* The main purpose of this wrapper function is to isolate vfork() from both
|
|
|
|
* subprocess_fork_exec() and child_exec(). A child process created via
|
|
|
|
* vfork() executes on the same stack as the parent process while the latter is
|
|
|
|
* suspended, so this function should not be inlined to avoid compiler bugs
|
|
|
|
* that might clobber data needed by the parent later. Additionally,
|
|
|
|
* child_exec() should not be inlined to avoid spurious -Wclobber warnings from
|
|
|
|
* GCC (see bpo-35823).
|
|
|
|
*/
|
|
|
|
_Py_NO_INLINE static pid_t
|
|
|
|
do_fork_exec(char *const exec_array[],
|
|
|
|
char *const argv[],
|
|
|
|
char *const envp[],
|
|
|
|
const char *cwd,
|
|
|
|
int p2cread, int p2cwrite,
|
|
|
|
int c2pread, int c2pwrite,
|
|
|
|
int errread, int errwrite,
|
|
|
|
int errpipe_read, int errpipe_write,
|
|
|
|
int close_fds, int restore_signals,
|
|
|
|
int call_setsid,
|
|
|
|
int call_setgid, gid_t gid,
|
|
|
|
int call_setgroups, size_t groups_size, const gid_t *groups,
|
|
|
|
int call_setuid, uid_t uid, int child_umask,
|
|
|
|
const void *child_sigmask,
|
|
|
|
PyObject *py_fds_to_keep,
|
|
|
|
PyObject *preexec_fn,
|
|
|
|
PyObject *preexec_fn_args_tuple)
|
|
|
|
{
|
|
|
|
|
|
|
|
pid_t pid;
|
|
|
|
|
|
|
|
#ifdef VFORK_USABLE
|
|
|
|
if (child_sigmask) {
|
|
|
|
/* These are checked by our caller; verify them in debug builds. */
|
|
|
|
assert(!call_setuid);
|
|
|
|
assert(!call_setgid);
|
|
|
|
assert(!call_setgroups);
|
|
|
|
assert(preexec_fn == Py_None);
|
|
|
|
|
|
|
|
pid = vfork();
|
|
|
|
} else
|
|
|
|
#endif
|
|
|
|
{
|
|
|
|
pid = fork();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (pid != 0) {
|
|
|
|
return pid;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Child process.
|
|
|
|
* See the comment above child_exec() for restrictions imposed on
|
|
|
|
* the code below.
|
|
|
|
*/
|
|
|
|
|
|
|
|
if (preexec_fn != Py_None) {
|
|
|
|
/* We'll be calling back into Python later so we need to do this.
|
|
|
|
* This call may not be async-signal-safe but neither is calling
|
|
|
|
* back into Python. The user asked us to use hope as a strategy
|
|
|
|
* to avoid deadlock... */
|
|
|
|
PyOS_AfterFork_Child();
|
|
|
|
}
|
|
|
|
|
|
|
|
child_exec(exec_array, argv, envp, cwd,
|
|
|
|
p2cread, p2cwrite, c2pread, c2pwrite,
|
|
|
|
errread, errwrite, errpipe_read, errpipe_write,
|
|
|
|
close_fds, restore_signals, call_setsid,
|
|
|
|
call_setgid, gid, call_setgroups, groups_size, groups,
|
|
|
|
call_setuid, uid, child_umask, child_sigmask,
|
|
|
|
py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
|
|
|
|
_exit(255);
|
|
|
|
return 0; /* Dead code to avoid a potential compiler warning. */
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
static PyObject *
|
2020-11-21 15:28:14 -04:00
|
|
|
subprocess_fork_exec(PyObject *module, PyObject *args)
|
2010-03-14 03:49:55 -03:00
|
|
|
{
|
|
|
|
PyObject *gc_module = NULL;
|
2012-08-15 18:20:39 -03:00
|
|
|
PyObject *executable_list, *py_fds_to_keep;
|
2010-03-14 03:49:55 -03:00
|
|
|
PyObject *env_list, *preexec_fn;
|
2010-03-15 03:07:42 -03:00
|
|
|
PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
|
2010-03-14 03:49:55 -03:00
|
|
|
PyObject *preexec_fn_args_tuple = NULL;
|
2019-09-12 14:15:44 -03:00
|
|
|
PyObject *groups_list;
|
|
|
|
PyObject *uid_object, *gid_object;
|
2010-03-14 03:49:55 -03:00
|
|
|
int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
|
|
|
|
int errpipe_read, errpipe_write, close_fds, restore_signals;
|
|
|
|
int call_setsid;
|
2019-09-12 14:15:44 -03:00
|
|
|
int call_setgid = 0, call_setgroups = 0, call_setuid = 0;
|
|
|
|
uid_t uid;
|
|
|
|
gid_t gid, *groups = NULL;
|
2019-10-12 17:24:56 -03:00
|
|
|
int child_umask;
|
2020-10-25 21:09:32 -03:00
|
|
|
PyObject *cwd_obj, *cwd_obj2 = NULL;
|
2010-03-14 03:49:55 -03:00
|
|
|
const char *cwd;
|
2020-11-01 01:33:08 -04:00
|
|
|
pid_t pid = -1;
|
2010-03-14 03:49:55 -03:00
|
|
|
int need_to_reenable_gc = 0;
|
|
|
|
char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
|
2019-09-12 14:15:44 -03:00
|
|
|
Py_ssize_t arg_num, num_groups = 0;
|
2017-05-27 12:50:54 -03:00
|
|
|
int need_after_fork = 0;
|
2018-09-13 08:30:10 -03:00
|
|
|
int saved_errno = 0;
|
2020-11-21 15:28:14 -04:00
|
|
|
_posixsubprocessstate *state = get_posixsubprocess_state(module);
|
2010-03-14 03:49:55 -03:00
|
|
|
|
|
|
|
if (!PyArg_ParseTuple(
|
2019-10-12 17:24:56 -03:00
|
|
|
args, "OOpO!OOiiiiiiiiiiOOOiO:fork_exec",
|
2017-04-19 15:12:46 -03:00
|
|
|
&process_args, &executable_list,
|
|
|
|
&close_fds, &PyTuple_Type, &py_fds_to_keep,
|
2010-04-16 20:49:32 -03:00
|
|
|
&cwd_obj, &env_list,
|
2010-03-14 03:49:55 -03:00
|
|
|
&p2cread, &p2cwrite, &c2pread, &c2pwrite,
|
|
|
|
&errread, &errwrite, &errpipe_read, &errpipe_write,
|
2019-09-12 14:15:44 -03:00
|
|
|
&restore_signals, &call_setsid,
|
2019-10-12 17:24:56 -03:00
|
|
|
&gid_object, &groups_list, &uid_object, &child_umask,
|
2019-09-12 14:15:44 -03:00
|
|
|
&preexec_fn))
|
2010-03-14 03:49:55 -03:00
|
|
|
return NULL;
|
|
|
|
|
2019-08-27 18:36:56 -03:00
|
|
|
if ((preexec_fn != Py_None) &&
|
2020-03-13 14:15:33 -03:00
|
|
|
(PyInterpreterState_Get() != PyInterpreterState_Main())) {
|
2019-08-27 18:36:56 -03:00
|
|
|
PyErr_SetString(PyExc_RuntimeError,
|
|
|
|
"preexec_fn not supported within subinterpreters");
|
2018-09-14 18:17:20 -03:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2013-12-01 04:12:24 -04:00
|
|
|
if (close_fds && errpipe_write < 3) { /* precondition */
|
|
|
|
PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
|
|
|
|
return NULL;
|
|
|
|
}
|
2012-01-21 18:01:08 -04:00
|
|
|
if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
|
|
|
|
PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
|
2010-12-04 07:22:11 -04:00
|
|
|
return NULL;
|
|
|
|
}
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2020-05-01 06:33:44 -03:00
|
|
|
PyInterpreterState *interp = PyInterpreterState_Get();
|
|
|
|
const PyConfig *config = _PyInterpreterState_GetConfig(interp);
|
|
|
|
if (config->_isolated_interpreter) {
|
|
|
|
PyErr_SetString(PyExc_RuntimeError,
|
|
|
|
"subprocess not supported for isolated subinterpreters");
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
/* We need to call gc.disable() when we'll be calling preexec_fn */
|
|
|
|
if (preexec_fn != Py_None) {
|
|
|
|
PyObject *result;
|
2013-08-27 19:53:59 -03:00
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
gc_module = PyImport_ImportModule("gc");
|
|
|
|
if (gc_module == NULL)
|
|
|
|
return NULL;
|
2020-02-11 12:46:57 -04:00
|
|
|
result = PyObject_CallMethodNoArgs(
|
2020-11-21 15:28:14 -04:00
|
|
|
gc_module, state->isenabled);
|
2010-03-19 13:53:08 -03:00
|
|
|
if (result == NULL) {
|
|
|
|
Py_DECREF(gc_module);
|
2010-03-14 03:49:55 -03:00
|
|
|
return NULL;
|
2010-03-19 13:53:08 -03:00
|
|
|
}
|
2010-03-14 03:49:55 -03:00
|
|
|
need_to_reenable_gc = PyObject_IsTrue(result);
|
|
|
|
Py_DECREF(result);
|
2010-03-19 13:53:08 -03:00
|
|
|
if (need_to_reenable_gc == -1) {
|
|
|
|
Py_DECREF(gc_module);
|
2010-03-14 03:49:55 -03:00
|
|
|
return NULL;
|
2010-03-19 13:53:08 -03:00
|
|
|
}
|
2020-02-11 12:46:57 -04:00
|
|
|
result = PyObject_CallMethodNoArgs(
|
2020-11-21 15:28:14 -04:00
|
|
|
gc_module, state->disable);
|
2010-03-19 13:53:08 -03:00
|
|
|
if (result == NULL) {
|
|
|
|
Py_DECREF(gc_module);
|
2010-03-14 03:49:55 -03:00
|
|
|
return NULL;
|
2010-03-19 13:53:08 -03:00
|
|
|
}
|
2010-03-14 03:49:55 -03:00
|
|
|
Py_DECREF(result);
|
|
|
|
}
|
|
|
|
|
|
|
|
exec_array = _PySequence_BytesToCharpArray(executable_list);
|
2014-10-05 12:25:19 -03:00
|
|
|
if (!exec_array)
|
|
|
|
goto cleanup;
|
2010-03-14 03:49:55 -03:00
|
|
|
|
|
|
|
/* Convert args and env into appropriate arguments for exec() */
|
|
|
|
/* These conversions are done in the parent process to avoid allocating
|
|
|
|
or freeing memory in the child process. */
|
|
|
|
if (process_args != Py_None) {
|
2010-03-15 03:07:42 -03:00
|
|
|
Py_ssize_t num_args;
|
2010-03-14 03:49:55 -03:00
|
|
|
/* Equivalent to: */
|
|
|
|
/* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
|
2010-03-15 03:07:42 -03:00
|
|
|
fast_args = PySequence_Fast(process_args, "argv must be a tuple");
|
2012-08-20 09:36:47 -03:00
|
|
|
if (fast_args == NULL)
|
|
|
|
goto cleanup;
|
2010-03-15 03:07:42 -03:00
|
|
|
num_args = PySequence_Fast_GET_SIZE(fast_args);
|
|
|
|
converted_args = PyTuple_New(num_args);
|
2010-03-14 03:49:55 -03:00
|
|
|
if (converted_args == NULL)
|
|
|
|
goto cleanup;
|
2010-03-15 03:07:42 -03:00
|
|
|
for (arg_num = 0; arg_num < num_args; ++arg_num) {
|
2010-03-14 03:49:55 -03:00
|
|
|
PyObject *borrowed_arg, *converted_arg;
|
2017-04-19 15:12:46 -03:00
|
|
|
if (PySequence_Fast_GET_SIZE(fast_args) != num_args) {
|
|
|
|
PyErr_SetString(PyExc_RuntimeError, "args changed during iteration");
|
|
|
|
goto cleanup;
|
|
|
|
}
|
2010-03-15 03:07:42 -03:00
|
|
|
borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
|
2010-03-14 03:49:55 -03:00
|
|
|
if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
|
|
|
|
goto cleanup;
|
|
|
|
PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
|
|
|
|
}
|
|
|
|
|
|
|
|
argv = _PySequence_BytesToCharpArray(converted_args);
|
|
|
|
Py_CLEAR(converted_args);
|
2010-03-15 03:07:42 -03:00
|
|
|
Py_CLEAR(fast_args);
|
2010-03-14 03:49:55 -03:00
|
|
|
if (!argv)
|
|
|
|
goto cleanup;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (env_list != Py_None) {
|
|
|
|
envp = _PySequence_BytesToCharpArray(env_list);
|
|
|
|
if (!envp)
|
|
|
|
goto cleanup;
|
|
|
|
}
|
|
|
|
|
2010-04-16 20:49:32 -03:00
|
|
|
if (cwd_obj != Py_None) {
|
|
|
|
if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
|
|
|
|
goto cleanup;
|
2010-04-22 09:08:36 -03:00
|
|
|
cwd = PyBytes_AsString(cwd_obj2);
|
2010-04-16 20:49:32 -03:00
|
|
|
} else {
|
|
|
|
cwd = NULL;
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
|
|
|
|
2019-09-12 14:15:44 -03:00
|
|
|
if (groups_list != Py_None) {
|
|
|
|
#ifdef HAVE_SETGROUPS
|
|
|
|
Py_ssize_t i;
|
2020-12-29 08:58:27 -04:00
|
|
|
gid_t gid;
|
2019-09-12 14:15:44 -03:00
|
|
|
|
|
|
|
if (!PyList_Check(groups_list)) {
|
|
|
|
PyErr_SetString(PyExc_TypeError,
|
|
|
|
"setgroups argument must be a list");
|
|
|
|
goto cleanup;
|
|
|
|
}
|
|
|
|
num_groups = PySequence_Size(groups_list);
|
|
|
|
|
|
|
|
if (num_groups < 0)
|
|
|
|
goto cleanup;
|
|
|
|
|
|
|
|
if (num_groups > MAX_GROUPS) {
|
|
|
|
PyErr_SetString(PyExc_ValueError, "too many groups");
|
|
|
|
goto cleanup;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ((groups = PyMem_RawMalloc(num_groups * sizeof(gid_t))) == NULL) {
|
|
|
|
PyErr_SetString(PyExc_MemoryError,
|
|
|
|
"failed to allocate memory for group list");
|
|
|
|
goto cleanup;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (i = 0; i < num_groups; i++) {
|
|
|
|
PyObject *elem;
|
|
|
|
elem = PySequence_GetItem(groups_list, i);
|
|
|
|
if (!elem)
|
|
|
|
goto cleanup;
|
|
|
|
if (!PyLong_Check(elem)) {
|
|
|
|
PyErr_SetString(PyExc_TypeError,
|
|
|
|
"groups must be integers");
|
|
|
|
Py_DECREF(elem);
|
|
|
|
goto cleanup;
|
|
|
|
} else {
|
|
|
|
if (!_Py_Gid_Converter(elem, &gid)) {
|
|
|
|
Py_DECREF(elem);
|
|
|
|
PyErr_SetString(PyExc_ValueError, "invalid group id");
|
|
|
|
goto cleanup;
|
|
|
|
}
|
|
|
|
groups[i] = gid;
|
|
|
|
}
|
|
|
|
Py_DECREF(elem);
|
|
|
|
}
|
|
|
|
call_setgroups = 1;
|
|
|
|
|
|
|
|
#else /* HAVE_SETGROUPS */
|
|
|
|
PyErr_BadInternalCall();
|
|
|
|
goto cleanup;
|
|
|
|
#endif /* HAVE_SETGROUPS */
|
|
|
|
}
|
|
|
|
|
|
|
|
if (gid_object != Py_None) {
|
|
|
|
#ifdef HAVE_SETREGID
|
|
|
|
if (!_Py_Gid_Converter(gid_object, &gid))
|
|
|
|
goto cleanup;
|
|
|
|
|
|
|
|
call_setgid = 1;
|
|
|
|
|
|
|
|
#else /* HAVE_SETREGID */
|
|
|
|
PyErr_BadInternalCall();
|
|
|
|
goto cleanup;
|
|
|
|
#endif /* HAVE_SETREUID */
|
|
|
|
}
|
|
|
|
|
|
|
|
if (uid_object != Py_None) {
|
|
|
|
#ifdef HAVE_SETREUID
|
|
|
|
if (!_Py_Uid_Converter(uid_object, &uid))
|
|
|
|
goto cleanup;
|
|
|
|
|
|
|
|
call_setuid = 1;
|
|
|
|
|
|
|
|
#else /* HAVE_SETREUID */
|
|
|
|
PyErr_BadInternalCall();
|
|
|
|
goto cleanup;
|
|
|
|
#endif /* HAVE_SETREUID */
|
|
|
|
}
|
|
|
|
|
2017-05-29 14:03:41 -03:00
|
|
|
/* This must be the last thing done before fork() because we do not
|
|
|
|
* want to call PyOS_BeforeFork() if there is any chance of another
|
|
|
|
* error leading to the cleanup: code without calling fork(). */
|
|
|
|
if (preexec_fn != Py_None) {
|
|
|
|
preexec_fn_args_tuple = PyTuple_New(0);
|
|
|
|
if (!preexec_fn_args_tuple)
|
|
|
|
goto cleanup;
|
|
|
|
PyOS_BeforeFork();
|
|
|
|
need_after_fork = 1;
|
|
|
|
}
|
|
|
|
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
/* NOTE: When old_sigmask is non-NULL, do_fork_exec() may use vfork(). */
|
|
|
|
const void *old_sigmask = NULL;
|
|
|
|
#ifdef VFORK_USABLE
|
|
|
|
/* Use vfork() only if it's safe. See the comment above child_exec(). */
|
|
|
|
sigset_t old_sigs;
|
|
|
|
if (preexec_fn == Py_None &&
|
2020-10-24 16:07:35 -03:00
|
|
|
!call_setuid && !call_setgid && !call_setgroups) {
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
/* Block all signals to ensure that no signal handlers are run in the
|
|
|
|
* child process while it shares memory with us. Note that signals
|
|
|
|
* used internally by C libraries won't be blocked by
|
|
|
|
* pthread_sigmask(), but signal handlers installed by C libraries
|
|
|
|
* normally service only signals originating from *within the process*,
|
|
|
|
* so it should be sufficient to consider any library function that
|
|
|
|
* might send such a signal to be vfork-unsafe and do not call it in
|
|
|
|
* the child.
|
2010-03-14 03:49:55 -03:00
|
|
|
*/
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
sigset_t all_sigs;
|
|
|
|
sigfillset(&all_sigs);
|
2020-10-24 14:47:38 -03:00
|
|
|
if ((saved_errno = pthread_sigmask(SIG_BLOCK, &all_sigs, &old_sigs))) {
|
|
|
|
goto cleanup;
|
|
|
|
}
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
old_sigmask = &old_sigs;
|
|
|
|
}
|
|
|
|
#endif
|
2010-03-14 03:49:55 -03:00
|
|
|
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
pid = do_fork_exec(exec_array, argv, envp, cwd,
|
|
|
|
p2cread, p2cwrite, c2pread, c2pwrite,
|
|
|
|
errread, errwrite, errpipe_read, errpipe_write,
|
|
|
|
close_fds, restore_signals, call_setsid,
|
|
|
|
call_setgid, gid, call_setgroups, num_groups, groups,
|
|
|
|
call_setuid, uid, child_umask, old_sigmask,
|
|
|
|
py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2018-09-13 08:30:10 -03:00
|
|
|
/* Parent (original) process */
|
2010-03-14 03:49:55 -03:00
|
|
|
if (pid == -1) {
|
2018-09-13 08:30:10 -03:00
|
|
|
/* Capture errno for the exception. */
|
|
|
|
saved_errno = errno;
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
|
|
|
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
#ifdef VFORK_USABLE
|
|
|
|
if (old_sigmask) {
|
|
|
|
/* vfork() semantics guarantees that the parent is blocked
|
|
|
|
* until the child performs _exit() or execve(), so it is safe
|
|
|
|
* to unblock signals once we're here.
|
|
|
|
* Note that in environments where vfork() is implemented as fork(),
|
|
|
|
* such as QEMU user-mode emulation, the parent won't be blocked,
|
|
|
|
* but it won't share the address space with the child,
|
2020-10-24 14:47:38 -03:00
|
|
|
* so it's still safe to unblock the signals.
|
|
|
|
*
|
|
|
|
* We don't handle errors here because this call can't fail
|
|
|
|
* if valid arguments are given, and because there is no good
|
|
|
|
* way for the caller to deal with a failure to restore
|
|
|
|
* the thread signal mask. */
|
|
|
|
(void) pthread_sigmask(SIG_SETMASK, old_sigmask, NULL);
|
bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe (GH-11671)
* bpo-35823: subprocess: Use vfork() instead of fork() on Linux when safe
When used to run a new executable image, fork() is not a good choice
for process creation, especially if the parent has a large working set:
fork() needs to copy page tables, which is slow, and may fail on systems
where overcommit is disabled, despite that the child is not going to
touch most of its address space.
Currently, subprocess is capable of using posix_spawn() instead, which
normally provides much better performance. However, posix_spawn() does not
support many of child setup operations exposed by subprocess.Popen().
Most notably, it's not possible to express `close_fds=True`, which
happens to be the default, via posix_spawn(). As a result, most users
can't benefit from faster process creation, at least not without
changing their code.
However, Linux provides vfork() system call, which creates a new process
without copying the address space of the parent, and which is actually
used by C libraries to efficiently implement posix_spawn(). Due to sharing
of the address space and even the stack with the parent, extreme care
is required to use vfork(). At least the following restrictions must hold:
* No signal handlers must execute in the child process. Otherwise, they
might clobber memory shared with the parent, potentially confusing it.
* Any library function called after vfork() in the child must be
async-signal-safe (as for fork()), but it must also not interact with any
library state in a way that might break due to address space sharing
and/or lack of any preparations performed by libraries on normal fork().
POSIX.1 permits to call only execve() and _exit(), and later revisions
remove vfork() specification entirely. In practice, however, almost all
operations needed by subprocess.Popen() can be safely implemented on
Linux.
* Due to sharing of the stack with the parent, the child must be careful
not to clobber local variables that are alive across vfork() call.
Compilers are normally aware of this and take extra care with vfork()
(and setjmp(), which has a similar problem).
* In case the parent is privileged, special attention must be paid to vfork()
use, because sharing an address space across different privilege domains
is insecure[1].
This patch adds support for using vfork() instead of fork() on Linux
when it's possible to do safely given the above. In particular:
* vfork() is not used if credential switch is requested. The reverse case
(simple subprocess.Popen() but another application thread switches
credentials concurrently) is not possible for pure-Python apps because
subprocess.Popen() and functions like os.setuid() are mutually excluded
via GIL. We might also consider to add a way to opt-out of vfork() (and
posix_spawn() on platforms where it might be implemented via vfork()) in
a future PR.
* vfork() is not used if `preexec_fn != None`.
With this change, subprocess will still use posix_spawn() if possible, but
will fallback to vfork() on Linux in most cases, and, failing that,
to fork().
[1] https://ewontfix.com/7
Co-authored-by: Gregory P. Smith [Google LLC] <gps@google.com>
2020-10-23 21:47:01 -03:00
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2017-05-27 12:50:54 -03:00
|
|
|
if (need_after_fork)
|
|
|
|
PyOS_AfterFork_Parent();
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2020-11-01 01:33:08 -04:00
|
|
|
cleanup:
|
|
|
|
if (saved_errno != 0) {
|
2018-09-13 08:30:10 -03:00
|
|
|
errno = saved_errno;
|
|
|
|
/* We can't call this above as PyOS_AfterFork_Parent() calls back
|
|
|
|
* into Python code which would see the unreturned error. */
|
|
|
|
PyErr_SetFromErrno(PyExc_OSError);
|
|
|
|
}
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2020-11-01 01:33:08 -04:00
|
|
|
Py_XDECREF(preexec_fn_args_tuple);
|
|
|
|
PyMem_RawFree(groups);
|
2020-10-25 21:09:32 -03:00
|
|
|
Py_XDECREF(cwd_obj2);
|
2010-03-14 03:49:55 -03:00
|
|
|
if (envp)
|
|
|
|
_Py_FreeCharPArray(envp);
|
2020-11-01 01:33:08 -04:00
|
|
|
Py_XDECREF(converted_args);
|
|
|
|
Py_XDECREF(fast_args);
|
2010-03-14 03:49:55 -03:00
|
|
|
if (argv)
|
|
|
|
_Py_FreeCharPArray(argv);
|
2014-10-05 12:25:19 -03:00
|
|
|
if (exec_array)
|
|
|
|
_Py_FreeCharPArray(exec_array);
|
2019-09-12 14:15:44 -03:00
|
|
|
|
2020-11-21 15:28:14 -04:00
|
|
|
_enable_gc(need_to_reenable_gc, gc_module, state);
|
2010-03-14 03:49:55 -03:00
|
|
|
Py_XDECREF(gc_module);
|
2020-11-01 01:33:08 -04:00
|
|
|
|
|
|
|
return pid == -1 ? NULL : PyLong_FromPid(pid);
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
PyDoc_STRVAR(subprocess_fork_exec_doc,
|
2019-09-20 14:01:10 -03:00
|
|
|
"fork_exec(args, executable_list, close_fds, pass_fds, cwd, env,\n\
|
2010-03-14 03:49:55 -03:00
|
|
|
p2cread, p2cwrite, c2pread, c2pwrite,\n\
|
|
|
|
errread, errwrite, errpipe_read, errpipe_write,\n\
|
2019-09-12 14:15:44 -03:00
|
|
|
restore_signals, call_setsid,\n\
|
2019-09-20 14:01:10 -03:00
|
|
|
gid, groups_list, uid,\n\
|
2019-09-12 14:15:44 -03:00
|
|
|
preexec_fn)\n\
|
2010-03-14 03:49:55 -03:00
|
|
|
\n\
|
|
|
|
Forks a child process, closes parent file descriptors as appropriate in the\n\
|
|
|
|
child and dups the few that are needed before calling exec() in the child\n\
|
|
|
|
process.\n\
|
|
|
|
\n\
|
2019-09-20 14:01:10 -03:00
|
|
|
If close_fds is true, close file descriptors 3 and higher, except those listed\n\
|
|
|
|
in the sorted tuple pass_fds.\n\
|
|
|
|
\n\
|
|
|
|
The preexec_fn, if supplied, will be called immediately before closing file\n\
|
|
|
|
descriptors and exec.\n\
|
2010-03-14 03:49:55 -03:00
|
|
|
WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
|
|
|
|
It may trigger infrequent, difficult to debug deadlocks.\n\
|
|
|
|
\n\
|
|
|
|
If an error occurs in the child process before the exec, it is\n\
|
|
|
|
serialized and written to the errpipe_write fd per subprocess.py.\n\
|
|
|
|
\n\
|
|
|
|
Returns: the child process's PID.\n\
|
|
|
|
\n\
|
|
|
|
Raises: Only on an error in the parent process.\n\
|
|
|
|
");
|
|
|
|
|
|
|
|
/* module level code ********************************************************/
|
|
|
|
|
|
|
|
PyDoc_STRVAR(module_doc,
|
|
|
|
"A POSIX helper for the subprocess module.");
|
|
|
|
|
2020-11-21 15:28:14 -04:00
|
|
|
static int
|
|
|
|
_posixsubprocess_exec(PyObject *module)
|
|
|
|
{
|
|
|
|
_posixsubprocessstate *state = get_posixsubprocess_state(module);
|
|
|
|
|
|
|
|
state->disable = PyUnicode_InternFromString("disable");
|
|
|
|
if (state->disable == NULL) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
state->enable = PyUnicode_InternFromString("enable");
|
|
|
|
if (state->enable == NULL) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
state->isenabled = PyUnicode_InternFromString("isenabled");
|
|
|
|
if (state->isenabled == NULL) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
2010-03-14 03:49:55 -03:00
|
|
|
|
|
|
|
static PyMethodDef module_methods[] = {
|
|
|
|
{"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
|
|
|
|
{NULL, NULL} /* sentinel */
|
|
|
|
};
|
|
|
|
|
2020-11-21 15:28:14 -04:00
|
|
|
static PyModuleDef_Slot _posixsubprocess_slots[] = {
|
|
|
|
{Py_mod_exec, _posixsubprocess_exec},
|
|
|
|
{0, NULL}
|
|
|
|
};
|
2010-03-14 03:49:55 -03:00
|
|
|
|
2019-09-10 08:01:20 -03:00
|
|
|
static int _posixsubprocess_traverse(PyObject *m, visitproc visit, void *arg) {
|
2020-03-16 10:15:01 -03:00
|
|
|
Py_VISIT(get_posixsubprocess_state(m)->disable);
|
|
|
|
Py_VISIT(get_posixsubprocess_state(m)->enable);
|
|
|
|
Py_VISIT(get_posixsubprocess_state(m)->isenabled);
|
2019-09-10 08:01:20 -03:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
static int _posixsubprocess_clear(PyObject *m) {
|
2020-03-16 10:15:01 -03:00
|
|
|
Py_CLEAR(get_posixsubprocess_state(m)->disable);
|
|
|
|
Py_CLEAR(get_posixsubprocess_state(m)->enable);
|
|
|
|
Py_CLEAR(get_posixsubprocess_state(m)->isenabled);
|
2019-09-10 08:01:20 -03:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
static void _posixsubprocess_free(void *m) {
|
|
|
|
_posixsubprocess_clear((PyObject *)m);
|
|
|
|
}
|
|
|
|
|
2010-03-14 03:49:55 -03:00
|
|
|
static struct PyModuleDef _posixsubprocessmodule = {
|
2017-11-05 09:37:50 -04:00
|
|
|
PyModuleDef_HEAD_INIT,
|
2020-11-21 15:28:14 -04:00
|
|
|
.m_name = "_posixsubprocess",
|
|
|
|
.m_doc = module_doc,
|
|
|
|
.m_size = sizeof(_posixsubprocessstate),
|
|
|
|
.m_methods = module_methods,
|
|
|
|
.m_slots = _posixsubprocess_slots,
|
|
|
|
.m_traverse = _posixsubprocess_traverse,
|
|
|
|
.m_clear = _posixsubprocess_clear,
|
|
|
|
.m_free = _posixsubprocess_free,
|
2010-03-14 03:49:55 -03:00
|
|
|
};
|
|
|
|
|
|
|
|
PyMODINIT_FUNC
|
|
|
|
PyInit__posixsubprocess(void)
|
|
|
|
{
|
2020-11-21 15:28:14 -04:00
|
|
|
return PyModuleDef_Init(&_posixsubprocessmodule);
|
2010-03-14 03:49:55 -03:00
|
|
|
}
|