LCOV - code coverage report
Current view: | top level - Modules - _posixsubprocess.c (source / functions) |  |  | Hit | Total | Coverage
Test: | CPython 3.12 LCOV report [commit 5e6661bce9] |  | Lines: | 2 | 338 | 0.6 %
Date: | 2023-03-20 08:15:36 |  | Functions: | 1 | 14 | 7.1 %
|  |  | Branches: | 0 | 310 | 0.0 %

               Branch data     Line data    Source code
           1                 :            : /* Authors: Gregory P. Smith & Jeffrey Yasskin */
           2                 :            : #ifndef Py_BUILD_CORE_BUILTIN
           3                 :            : #  define Py_BUILD_CORE_MODULE 1
           4                 :            : #endif
           5                 :            :
           6                 :            : #include "Python.h"
           7                 :            : #include "pycore_fileutils.h"
           8                 :            : #if defined(HAVE_PIPE2) && !defined(_GNU_SOURCE)
           9                 :            : # define _GNU_SOURCE
          10                 :            : #endif
          11                 :            : #include <unistd.h>
          12                 :            : #include <fcntl.h>
          13                 :            : #ifdef HAVE_SYS_TYPES_H
          14                 :            : #include <sys/types.h>
          15                 :            : #endif
          16                 :            : #if defined(HAVE_SYS_STAT_H)
          17                 :            : #include <sys/stat.h>
          18                 :            : #endif
          19                 :            : #ifdef HAVE_SYS_SYSCALL_H
          20                 :            : #include <sys/syscall.h>
          21                 :            : #endif
          22                 :            : #if defined(HAVE_SYS_RESOURCE_H)
          23                 :            : #include <sys/resource.h>
          24                 :            : #endif
          25                 :            : #ifdef HAVE_DIRENT_H
          26                 :            : #include <dirent.h>
          27                 :            : #endif
          28                 :            : #ifdef HAVE_GRP_H
          29                 :            : #include <grp.h>
          30                 :            : #endif /* HAVE_GRP_H */
          31                 :            :
          32                 :            : #include "posixmodule.h"
          33                 :            :
          34                 :            : #ifdef _Py_MEMORY_SANITIZER
          35                 :            : # include <sanitizer/msan_interface.h>
          36                 :            : #endif
          37                 :            :
          38                 :            : #if defined(__ANDROID__) && __ANDROID_API__ < 21 && !defined(SYS_getdents64)
          39                 :            : # include <sys/linux-syscalls.h>
          40                 :            : # define SYS_getdents64  __NR_getdents64
          41                 :            : #endif
          42                 :            :
          43                 :            : #if defined(__linux__) && defined(HAVE_VFORK) && defined(HAVE_SIGNAL_H) && \
          44                 :            :     defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
          45                 :            : /* If this is ever expanded to non-Linux platforms, verify what calls are
          46                 :            :  * allowed after vfork(). Ex: setsid() may be disallowed on macOS? */
          47                 :            : # include <signal.h>
          48                 :            : # define VFORK_USABLE 1
          49                 :            : #endif
          50                 :            :
          51                 :            : #if defined(__sun) && defined(__SVR4)
          52                 :            : /* readdir64 is used to work around Solaris 9 bug 6395699. */
          53                 :            : # define readdir readdir64
          54                 :            : # define dirent dirent64
          55                 :            : # if !defined(HAVE_DIRFD)
          56                 :            : /* Some versions of Solaris lack dirfd(). */
          57                 :            : #  define dirfd(dirp) ((dirp)->dd_fd)
          58                 :            : #  define HAVE_DIRFD
          59                 :            : # endif
          60                 :            : #endif
          61                 :            :
          62                 :            : #if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__DragonFly__)
          63                 :            : # define FD_DIR "/dev/fd"
          64                 :            : #else
          65                 :            : # define FD_DIR "/proc/self/fd"
          66                 :            : #endif
          67                 :            :
          68                 :            : #ifdef NGROUPS_MAX
          69                 :            : #define MAX_GROUPS NGROUPS_MAX
          70                 :            : #else
          71                 :            : #define MAX_GROUPS 64
          72                 :            : #endif
          73                 :            :
          74                 :            : #define POSIX_CALL(call)   do { if ((call) == -1) goto error; } while (0)
          75                 :            :
          76                 :            : static struct PyModuleDef _posixsubprocessmodule;
          77                 :            :
          78                 :            : /* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
          79                 :            : static int
          80                 :          0 : _pos_int_from_ascii(const char *name)
          81                 :            : {
          82                 :          0 :     int num = 0;
          83   [ #  #  #  # ]:          0 :     while (*name >= '0' && *name <= '9') {
          84                 :          0 :         num = num * 10 + (*name - '0');
          85                 :          0 :         ++name;
          86                 :            :     }
          87         [ #  # ]:          0 :     if (*name)
          88                 :          0 :         return -1;  /* Non digit found, not a number. */
          89                 :          0 :     return num;
          90                 :            : }
          91                 :            :
          92                 :            :
          93                 :            : #if defined(__FreeBSD__) || defined(__DragonFly__)
          94                 :            : /* When /dev/fd isn't mounted it is often a static directory populated
          95                 :            :  * with 0 1 2 or entries for 0 .. 63 on FreeBSD, NetBSD, OpenBSD and DragonFlyBSD.
          96                 :            :  * NetBSD and OpenBSD have a /proc fs available (though not necessarily
          97                 :            :  * mounted) and do not have fdescfs for /dev/fd.  MacOS X has a devfs
          98                 :            :  * that properly supports /dev/fd.
          99                 :            :  */
         100                 :            : static int
         101                 :            : _is_fdescfs_mounted_on_dev_fd(void)
         102                 :            : {
         103                 :            :     struct stat dev_stat;
         104                 :            :     struct stat dev_fd_stat;
         105                 :            :     if (stat("/dev", &dev_stat) != 0)
         106                 :            :         return 0;
         107                 :            :     if (stat(FD_DIR, &dev_fd_stat) != 0)
         108                 :            :         return 0;
         109                 :            :     if (dev_stat.st_dev == dev_fd_stat.st_dev)
         110                 :            :         return 0;  /* / == /dev == /dev/fd means it is static. #fail */
         111                 :            :     return 1;
         112                 :            : }
         113                 :            : #endif
         114                 :            :
         115                 :            :
         116                 :            : /* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
         117                 :            : static int
         118                 :          0 : _sanity_check_python_fd_sequence(PyObject *fd_sequence)
         119                 :            : {
         120                 :            :     Py_ssize_t seq_idx;
         121                 :          0 :     long prev_fd = -1;
         122         [ #  # ]:          0 :     for (seq_idx = 0; seq_idx < PyTuple_GET_SIZE(fd_sequence); ++seq_idx) {
         123                 :          0 :         PyObject* py_fd = PyTuple_GET_ITEM(fd_sequence, seq_idx);
         124                 :            :         long iter_fd;
         125         [ #  # ]:          0 :         if (!PyLong_Check(py_fd)) {
         126                 :          0 :             return 1;
         127                 :            :         }
         128                 :          0 :         iter_fd = PyLong_AsLong(py_fd);
         129   [ #  #  #  #  :          0 :         if (iter_fd < 0 || iter_fd <= prev_fd || iter_fd > INT_MAX) {
                       #  # ]
         130                 :            :             /* Negative, overflow, unsorted, too big for a fd. */
         131                 :          0 :             return 1;
         132                 :            :         }
         133                 :          0 :         prev_fd = iter_fd;
         134                 :            :     }
         135                 :          0 :     return 0;
         136                 :            : }
         137                 :            :
         138                 :            :
         139                 :            : /* Is fd found in the sorted Python Sequence? */
         140                 :            : static int
         141                 :          0 : _is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
         142                 :            : {
         143                 :            :     /* Binary search. */
         144                 :          0 :     Py_ssize_t search_min = 0;
         145                 :          0 :     Py_ssize_t search_max = PyTuple_GET_SIZE(fd_sequence) - 1;
         146         [ #  # ]:          0 :     if (search_max < 0)
         147                 :          0 :         return 0;
         148                 :            :     do {
         149                 :          0 :         long middle = (search_min + search_max) / 2;
         150                 :          0 :         long middle_fd = PyLong_AsLong(PyTuple_GET_ITEM(fd_sequence, middle));
         151         [ #  # ]:          0 :         if (fd == middle_fd)
         152                 :          0 :             return 1;
         153         [ #  # ]:          0 :         if (fd > middle_fd)
         154                 :          0 :             search_min = middle + 1;
         155                 :            :         else
         156                 :          0 :             search_max = middle - 1;
         157         [ #  # ]:          0 :     } while (search_min <= search_max);
         158                 :          0 :     return 0;
         159                 :            : }
         160                 :            :
         161                 :            : static int
         162                 :          0 : make_inheritable(PyObject *py_fds_to_keep, int errpipe_write)
         163                 :            : {
         164                 :            :     Py_ssize_t i, len;
         165                 :            :
         166                 :          0 :     len = PyTuple_GET_SIZE(py_fds_to_keep);
         167         [ #  # ]:          0 :     for (i = 0; i < len; ++i) {
         168                 :          0 :         PyObject* fdobj = PyTuple_GET_ITEM(py_fds_to_keep, i);
         169                 :          0 :         long fd = PyLong_AsLong(fdobj);
         170                 :            :         assert(!PyErr_Occurred());
         171                 :            :         assert(0 <= fd && fd <= INT_MAX);
         172         [ #  # ]:          0 :         if (fd == errpipe_write) {
         173                 :            :             /* errpipe_write is part of py_fds_to_keep. It must be closed at
         174                 :            :                exec(), but kept open in the child process until exec() is
         175                 :            :                called. */
         176                 :          0 :             continue;
         177                 :            :         }
         178         [ #  # ]:          0 :         if (_Py_set_inheritable_async_safe((int)fd, 1, NULL) < 0)
         179                 :          0 :             return -1;
         180                 :            :     }
         181                 :          0 :     return 0;
         182                 :            : }
         183                 :            :
         184                 :            :
         185                 :            : /* Get the maximum file descriptor that could be opened by this process.
         186                 :            :  * This function is async signal safe for use between fork() and exec().
         187                 :            :  */
         188                 :            : static long
         189                 :          0 : safe_get_max_fd(void)
         190                 :            : {
         191                 :            :     long local_max_fd;
         192                 :            : #if defined(__NetBSD__)
         193                 :            :     local_max_fd = fcntl(0, F_MAXFD);
         194                 :            :     if (local_max_fd >= 0)
         195                 :            :         return local_max_fd;
         196                 :            : #endif
         197                 :            : #if defined(HAVE_SYS_RESOURCE_H) && defined(__OpenBSD__)
         198                 :            :     struct rlimit rl;
         199                 :            :     /* Not on the POSIX async signal safe functions list but likely
         200                 :            :      * safe.  TODO - Someone should audit OpenBSD to make sure. */
         201                 :            :     if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
         202                 :            :         return (long) rl.rlim_max;
         203                 :            : #endif
         204                 :            : #ifdef _SC_OPEN_MAX
         205                 :          0 :     local_max_fd = sysconf(_SC_OPEN_MAX);
         206         [ #  # ]:          0 :     if (local_max_fd == -1)
         207                 :            : #endif
         208                 :          0 :         local_max_fd = 256;  /* Matches legacy Lib/subprocess.py behavior. */
         209                 :          0 :     return local_max_fd;
         210                 :            : }
         211                 :            :
         212                 :            :
         213                 :            : /* Close all file descriptors in the given range except for those in
         214                 :            :  * py_fds_to_keep by invoking closer on each subrange.
         215                 :            :  *
         216                 :            :  * If end_fd == -1, it's guessed via safe_get_max_fd(), but it isn't
         217                 :            :  * possible to know for sure what the max fd to go up to is for
         218                 :            :  * processes with the capability of raising their maximum, or in case
         219                 :            :  * a process opened a high fd and then lowered its maximum.
         220                 :            :  */
         221                 :            : static int
         222                 :          0 : _close_range_except(int start_fd,
         223                 :            :                     int end_fd,
         224                 :            :                     PyObject *py_fds_to_keep,
         225                 :            :                     int (*closer)(int, int))
         226                 :            : {
         227         [ #  # ]:          0 :     if (end_fd == -1) {
         228         [ #  # ]:          0 :         end_fd = Py_MIN(safe_get_max_fd(), INT_MAX);
         229                 :            :     }
         230                 :          0 :     Py_ssize_t num_fds_to_keep = PyTuple_GET_SIZE(py_fds_to_keep);
         231                 :            :     Py_ssize_t keep_seq_idx;
         232                 :            :     /* As py_fds_to_keep is sorted we can loop through the list closing
         233                 :            :      * fds in between any in the keep list falling within our range. */
         234         [ #  # ]:          0 :     for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
         235                 :          0 :         PyObject* py_keep_fd = PyTuple_GET_ITEM(py_fds_to_keep, keep_seq_idx);
         236                 :          0 :         int keep_fd = PyLong_AsLong(py_keep_fd);
         237         [ #  # ]:          0 :         if (keep_fd < start_fd)
         238                 :          0 :             continue;
         239         [ #  # ]:          0 :         if (closer(start_fd, keep_fd - 1) != 0)
         240                 :          0 :             return -1;
         241                 :          0 :         start_fd = keep_fd + 1;
         242                 :            :     }
         243         [ #  # ]:          0 :     if (start_fd <= end_fd) {
         244         [ #  # ]:          0 :         if (closer(start_fd, end_fd) != 0)
         245                 :          0 :             return -1;
         246                 :            :     }
         247                 :          0 :     return 0;
         248                 :            : }
         249                 :            :
         250                 :            : #if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
         251                 :            : /* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
         252                 :            :  * only to read a directory of short file descriptor number names.  The kernel
         253                 :            :  * will return an error if we didn't give it enough space.  Highly Unlikely.
         254                 :            :  * This structure is very old and stable: It will not change unless the kernel
         255                 :            :  * chooses to break compatibility with all existing binaries.  Highly Unlikely.
         256                 :            :  */
         257                 :            : struct linux_dirent64 {
         258                 :            :    unsigned long long d_ino;
         259                 :            :    long long d_off;
         260                 :            :    unsigned short d_reclen;     /* Length of this linux_dirent */
         261                 :            :    unsigned char  d_type;
         262                 :            :    char           d_name[256];  /* Filename (null-terminated) */
         263                 :            : };
         264                 :            :
         265                 :            : static int
         266                 :          0 : _brute_force_closer(int first, int last)
         267                 :            : {
         268         [ #  # ]:          0 :     for (int i = first; i <= last; i++) {
         269                 :            :         /* Ignore errors */
         270                 :          0 :         (void)close(i);
         271                 :            :     }
         272                 :          0 :     return 0;
         273                 :            : }
         274                 :            :
         275                 :            : /* Close all open file descriptors in the range from start_fd and higher
         276                 :            :  * Do not close any in the sorted py_fds_to_keep list.
         277                 :            :  *
         278                 :            :  * This version is async signal safe as it does not make any unsafe C library
         279                 :            :  * calls, malloc calls or handle any locks.  It is _unfortunate_ to be forced
         280                 :            :  * to resort to making a kernel system call directly but this is the ONLY api
         281                 :            :  * available that does no harm.  opendir/readdir/closedir perform memory
         282                 :            :  * allocation and locking so while they usually work they are not guaranteed
         283                 :            :  * to (especially if you have replaced your malloc implementation).  A version
         284                 :            :  * of this function that uses those can be found in the _maybe_unsafe variant.
         285                 :            :  *
         286                 :            :  * This is Linux specific because that is all I am ready to test it on.  It
         287                 :            :  * should be easy to add OS specific dirent or dirent64 structures and modify
         288                 :            :  * it with some cpp #define magic to work on other OSes as well if you want.
         289                 :            :  */
         290                 :            : static void
         291                 :          0 : _close_open_fds_safe(int start_fd, PyObject* py_fds_to_keep)
         292                 :            : {
         293                 :            :     int fd_dir_fd;
         294                 :            :
         295                 :          0 :     fd_dir_fd = _Py_open_noraise(FD_DIR, O_RDONLY);
         296         [ #  # ]:          0 :     if (fd_dir_fd == -1) {
         297                 :            :         /* No way to get a list of open fds. */
         298                 :          0 :         _close_range_except(start_fd, -1, py_fds_to_keep, _brute_force_closer);
         299                 :          0 :         return;
         300                 :            :     } else {
         301                 :            :         char buffer[sizeof(struct linux_dirent64)];
         302                 :            :         int bytes;
         303         [ #  # ]:          0 :         while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
         304                 :            :                                 (struct linux_dirent64 *)buffer,
         305                 :            :                                 sizeof(buffer))) > 0) {
         306                 :            :             struct linux_dirent64 *entry;
         307                 :            :             int offset;
         308                 :            : #ifdef _Py_MEMORY_SANITIZER
         309                 :            :             __msan_unpoison(buffer, bytes);
         310                 :            : #endif
         311         [ #  # ]:          0 :             for (offset = 0; offset < bytes; offset += entry->d_reclen) {
         312                 :            :                 int fd;
         313                 :          0 :                 entry = (struct linux_dirent64 *)(buffer + offset);
         314         [ #  # ]:          0 :                 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
         315                 :          0 :                     continue;  /* Not a number. */
         316   [ #  #  #  #  :          0 :                 if (fd != fd_dir_fd && fd >= start_fd &&
                       #  # ]
         317                 :          0 :                     !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
         318                 :          0 :                     close(fd);
         319                 :            :                 }
         320                 :            :             }
         321                 :            :         }
         322                 :          0 :         close(fd_dir_fd);
         323                 :            :     }
         324                 :            : }
         325                 :            :
         326                 :            : #define _close_open_fds_fallback _close_open_fds_safe
         327                 :            :
         328                 :            : #else  /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
         329                 :            :
         330                 :            : static int
         331                 :            : _unsafe_closer(int first, int last)
         332                 :            : {
         333                 :            :     _Py_closerange(first, last);
         334                 :            :     return 0;
         335                 :            : }
         336                 :            :
         337                 :            : /* Close all open file descriptors from start_fd and higher.
         338                 :            :  * Do not close any in the sorted py_fds_to_keep tuple.
         339                 :            :  *
         340                 :            :  * This function violates the strict use of async signal safe functions. :(
         341                 :            :  * It calls opendir(), readdir() and closedir().  Of these, the one most
         342                 :            :  * likely to ever cause a problem is opendir() as it performs an internal
         343                 :            :  * malloc().  Practically this should not be a problem.  The Java VM makes the
         344                 :            :  * same calls between fork and exec in its own UNIXProcess_md.c implementation.
         345                 :            :  *
         346                 :            :  * readdir_r() is not used because it provides no benefit.  It is typically
         347                 :            :  * implemented as readdir() followed by memcpy().  See also:
         348                 :            :  *   http://womble.decadent.org.uk/readdir_r-advisory.html
         349                 :            :  */
         350                 :            : static void
         351                 :            : _close_open_fds_maybe_unsafe(int start_fd, PyObject* py_fds_to_keep)
         352                 :            : {
         353                 :            :     DIR *proc_fd_dir;
         354                 :            : #ifndef HAVE_DIRFD
         355                 :            :     while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep)) {
         356                 :            :         ++start_fd;
         357                 :            :     }
         358                 :            :     /* Close our lowest fd before we call opendir so that it is likely to
         359                 :            :      * reuse that fd otherwise we might close opendir's file descriptor in
         360                 :            :      * our loop.  This trick assumes that fd's are allocated on a lowest
         361                 :            :      * available basis. */
         362                 :            :     close(start_fd);
         363                 :            :     ++start_fd;
         364                 :            : #endif
         365                 :            :
         366                 :            : #if defined(__FreeBSD__) || defined(__DragonFly__)
         367                 :            :     if (!_is_fdescfs_mounted_on_dev_fd())
         368                 :            :         proc_fd_dir = NULL;
         369                 :            :     else
         370                 :            : #endif
         371                 :            :         proc_fd_dir = opendir(FD_DIR);
         372                 :            :     if (!proc_fd_dir) {
         373                 :            :         /* No way to get a list of open fds. */
         374                 :            :         _close_range_except(start_fd, -1, py_fds_to_keep, _unsafe_closer);
         375                 :            :     } else {
         376                 :            :         struct dirent *dir_entry;
         377                 :            : #ifdef HAVE_DIRFD
         378                 :            :         int fd_used_by_opendir = dirfd(proc_fd_dir);
         379                 :            : #else
         380                 :            :         int fd_used_by_opendir = start_fd - 1;
         381                 :            : #endif
         382                 :            :         errno = 0;
         383                 :            :         while ((dir_entry = readdir(proc_fd_dir))) {
         384                 :            :             int fd;
         385                 :            :             if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
         386                 :            :                 continue;  /* Not a number. */
         387                 :            :             if (fd != fd_used_by_opendir && fd >= start_fd &&
         388                 :            :                 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
         389                 :            :                 close(fd);
         390                 :            :             }
         391                 :            :             errno = 0;
         392                 :            :         }
         393                 :            :         if (errno) {
         394                 :            :             /* readdir error, revert behavior. Highly Unlikely. */
         395                 :            :             _close_range_except(start_fd, -1, py_fds_to_keep, _unsafe_closer);
         396                 :            :         }
         397                 :            :         closedir(proc_fd_dir);
         398                 :            :     }
         399                 :            : }
         400                 :            :
         401                 :            : #define _close_open_fds_fallback _close_open_fds_maybe_unsafe
         402                 :            :
         403                 :            : #endif  /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
         404                 :            :
         405                 :            : /* We can use close_range() library function only if it's known to be
         406                 :            :  * async-signal-safe.
         407                 :            :  *
         408                 :            :  * On Linux, glibc explicitly documents it to be a thin wrapper over
         409                 :            :  * the system call, and other C libraries are likely to follow glibc.
         410                 :            :  */
         411                 :            : #if defined(HAVE_CLOSE_RANGE) && \
         412                 :            :     (defined(__linux__) || defined(__FreeBSD__))
         413                 :            : #define HAVE_ASYNC_SAFE_CLOSE_RANGE
         414                 :            :
         415                 :            : static int
         416                 :            : _close_range_closer(int first, int last)
         417                 :            : {
         418                 :            :     return close_range(first, last, 0);
         419                 :            : }
         420                 :            : #endif
         421                 :            :
         422                 :            : static void
         423                 :          0 : _close_open_fds(int start_fd, PyObject* py_fds_to_keep)
         424                 :            : {
         425                 :            : #ifdef HAVE_ASYNC_SAFE_CLOSE_RANGE
         426                 :            :     if (_close_range_except(
         427                 :            :             start_fd, INT_MAX, py_fds_to_keep,
         428                 :            :             _close_range_closer) == 0) {
         429                 :            :         return;
         430                 :            :     }
         431                 :            : #endif
         432                 :          0 :     _close_open_fds_fallback(start_fd, py_fds_to_keep);
         433                 :          0 : }
         434                 :            :
         435                 :            : #ifdef VFORK_USABLE
         436                 :            : /* Reset dispositions for all signals to SIG_DFL except for ignored
         437                 :            :  * signals. This way we ensure that no signal handlers can run
         438                 :            :  * after we unblock signals in a child created by vfork().
         439                 :            :  */
         440                 :            : static void
         441                 :          0 : reset_signal_handlers(const sigset_t *child_sigmask)
         442                 :            : {
         443                 :          0 :     struct sigaction sa_dfl = {.sa_handler = SIG_DFL};
         444         [ #  # ]:          0 :     for (int sig = 1; sig < _NSIG; sig++) {
         445                 :            :         /* Dispositions for SIGKILL and SIGSTOP can't be changed. */
         446   [ #  #  #  # ]:          0 :         if (sig == SIGKILL || sig == SIGSTOP) {
         447                 :          0 :             continue;
         448                 :            :         }
         449                 :            :
         450                 :            :         /* There is no need to reset the disposition of signals that will
         451                 :            :          * remain blocked across execve() since the kernel will do it. */
         452         [ #  # ]:          0 :         if (sigismember(child_sigmask, sig) == 1) {
         453                 :          0 :             continue;
         454                 :            :         }
         455                 :            :
         456                 :            :         struct sigaction sa;
         457                 :            :         /* C libraries usually return EINVAL for signals used
         458                 :            :          * internally (e.g. for thread cancellation), so simply
         459                 :            :          * skip errors here. */
         460         [ #  # ]:          0 :         if (sigaction(sig, NULL, &sa) == -1) {
         461                 :          0 :             continue;
         462                 :            :         }
         463                 :            :
         464                 :            :         /* void *h works as these fields are both pointer types already. */
         465         [ #  # ]:          0 :         void *h = (sa.sa_flags & SA_SIGINFO ? (void *)sa.sa_sigaction :
         466                 :            :                                               (void *)sa.sa_handler);
         467   [ #  #  #  # ]:          0 :         if (h == SIG_IGN || h == SIG_DFL) {
         468                 :          0 :             continue;
         469                 :            :         }
         470                 :            :
         471                 :            :         /* This call can't reasonably fail, but if it does, terminating
         472                 :            :          * the child seems to be too harsh, so ignore errors. */
         473                 :          0 :         (void) sigaction(sig, &sa_dfl, NULL);
         474                 :            :     }
         475                 :          0 : }
         476                 :            : #endif /* VFORK_USABLE */
         477                 :            :
         478                 :            :
         479                 :            : /*
         480                 :            :  * This function is code executed in the child process immediately after
         481                 :            :  * (v)fork to set things up and call exec().
         482                 :            :  *
         483                 :            :  * All of the code in this function must only use async-signal-safe functions,
         484                 :            :  * listed at `man 7 signal` or
         485                 :            :  * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
         486                 :            :  *
         487                 :            :  * This restriction is documented at
         488                 :            :  * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
         489                 :            :  *
         490                 :            :  * If this function is called after vfork(), even more care must be taken.
         491                 :            :  * The lack of preparations that C libraries normally take on fork(),
         492                 :            :  * as well as sharing the address space with the parent, might make even
         493                 :            :  * async-signal-safe functions vfork-unsafe. In particular, on Linux,
         494                 :            :  * set*id() and setgroups() library functions must not be called, since
         495                 :            :  * they have to interact with the library-level thread list and send
         496                 :            :  * library-internal signals to implement per-process credentials semantics
         497                 :            :  * required by POSIX but not supported natively on Linux. Another reason to
         498                 :            :  * avoid this family of functions is that sharing an address space between
         499                 :            :  * processes running with different privileges is inherently insecure.
         500                 :            :  * See bpo-35823 for further discussion and references.
         501                 :            :  *
         502                 :            :  * In some C libraries, setrlimit() has the same thread list/signalling
         503                 :            :  * behavior since resource limits were per-thread attributes before
         504                 :            :  * Linux 2.6.10. Musl, as of 1.2.1, is known to have this issue
         505                 :            :  * (https://www.openwall.com/lists/musl/2020/10/15/6).
         506                 :            :  *
         507                 :            :  * If vfork-unsafe functionality is desired after vfork(), consider using
         508                 :            :  * syscall() to obtain it.
         509                 :            :  */
         510                 :            : Py_NO_INLINE static void
         511                 :          0 : child_exec(char *const exec_array[],
         512                 :            :            char *const argv[],
         513                 :            :            char *const envp[],
         514                 :            :            const char *cwd,
         515                 :            :            int p2cread, int p2cwrite,
         516                 :            :            int c2pread, int c2pwrite,
         517                 :            :            int errread, int errwrite,
         518                 :            :            int errpipe_read, int errpipe_write,
         519                 :            :            int close_fds, int restore_signals,
         520                 :            :            int call_setsid, pid_t pgid_to_set,
         521                 :            :            gid_t gid,
         522                 :            :            Py_ssize_t extra_group_size, const gid_t *extra_groups,
         523                 :            :            uid_t uid, int child_umask,
         524                 :            :            const void *child_sigmask,
         525                 :            :            PyObject *py_fds_to_keep,
         526                 :            :            PyObject *preexec_fn,
         527                 :            :            PyObject *preexec_fn_args_tuple)
         528                 :            : {
         529                 :          0 :     int i, saved_errno, reached_preexec = 0;
         530                 :            :     PyObject *result;
         531                 :          0 :     const char* err_msg = "";
         532                 :            :     /* Buffer large enough to hold a hex integer.  We can't malloc. */
         533                 :            :     char hex_errno[sizeof(saved_errno)*2+1];
         534                 :            :
         535         [ #  # ]:          0 :     if (make_inheritable(py_fds_to_keep, errpipe_write) < 0)
         536                 :          0 :         goto error;
         537                 :            :
         538                 :            :     /* Close parent's pipe ends. */
         539         [ #  # ]:          0 :     if (p2cwrite != -1)
         540         [ #  # ]:          0 :         POSIX_CALL(close(p2cwrite));
         541         [ #  # ]:          0 :     if (c2pread != -1)
         542         [ #  # ]:          0 :         POSIX_CALL(close(c2pread));
         543         [ #  # ]:          0 :     if (errread != -1)
         544         [ #  # ]:          0 :         POSIX_CALL(close(errread));
         545         [ #  # ]:          0 :     POSIX_CALL(close(errpipe_read));
         546                 :            :
         547                 :            :     /* When duping fds, if there arises a situation where one of the fds is
         548                 :            :        either 0, 1 or 2, it is possible that it is overwritten (#12607). */
         549         [ #  # ]:          0 :     if (c2pwrite == 0) {
         550         [ #  # ]:          0 :         POSIX_CALL(c2pwrite = dup(c2pwrite));
         551                 :            :         /* issue32270 */
         552         [ #  # ]:          0 :         if (_Py_set_inheritable_async_safe(c2pwrite, 0, NULL) < 0) {
         553                 :          0 :             goto error;
         554                 :            :         }
         555                 :            :     }
         556   [ #  #  #  # ]:          0 :     while (errwrite == 0 || errwrite == 1) {
         557         [ #  # ]:          0 :         POSIX_CALL(errwrite = dup(errwrite));
         558                 :            :         /* issue32270 */
         559         [ #  # ]:          0 :         if (_Py_set_inheritable_async_safe(errwrite, 0, NULL) < 0) {
         560                 :          0 :             goto error;
         561                 :            :         }
         562                 :            :     }
         563                 :            :
         564                 :            :     /* Dup fds for child.
         565                 :            :        dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
         566                 :            :        would be a no-op (issue #10806). */
         567         [ #  # ]:          0 :     if (p2cread == 0) {
         568         [ #  # ]:          0 :         if (_Py_set_inheritable_async_safe(p2cread, 1, NULL) < 0)
         569                 :          0 :             goto error;
         570                 :            :     }
         571         [ #  # ]:          0 :     else if (p2cread != -1)
         572         [ #  # ]:          0 :         POSIX_CALL(dup2(p2cread, 0));  /* stdin */
         573                 :            :
         574         [ #  # ]:          0 :     if (c2pwrite == 1) {
         575         [ #  # ]:          0 :         if (_Py_set_inheritable_async_safe(c2pwrite, 1, NULL) < 0)
         576                 :          0 :             goto error;
         577                 :            :     }
         578         [ #  # ]:          0 :     else if (c2pwrite != -1)
         579         [ #  # ]:          0 :         POSIX_CALL(dup2(c2pwrite, 1));  /* stdout */
         580                 :            :
         581         [ #  # ]:          0 :     if (errwrite == 2) {
         582         [ #  # ]:          0 :         if (_Py_set_inheritable_async_safe(errwrite, 1, NULL) < 0)
         583                 :          0 :             goto error;
         584                 :            :     }
         585         [ #  # ]:          0 :     else if (errwrite != -1)
         586         [ #  # ]:          0 :         POSIX_CALL(dup2(errwrite, 2));  /* stderr */
         587                 :            :
         588                 :            :     /* We no longer manually close p2cread, c2pwrite, and errwrite here as
         589                 :            :      * _close_open_fds takes care when it is not already non-inheritable. */
         590                 :            :
         591         [ #  # ]:          0 :     if (cwd)
         592         [ #  # ]:          0 :         POSIX_CALL(chdir(cwd));
         593                 :            :
         594         [ #  # ]:          0 :     if (child_umask >= 0)
         595                 :          0 :         umask(child_umask);  /* umask() always succeeds. */
         596                 :            :
         597         [ #  # ]:          0 :     if (restore_signals)
         598                 :          0 :         _Py_RestoreSignals();
         599                 :            :
         600                 :            : #ifdef VFORK_USABLE
         601         [ #  # ]:          0 :     if (child_sigmask) {
         602                 :          0 :         reset_signal_handlers(child_sigmask);
         603         [ #  # ]:          0 :         if ((errno = pthread_sigmask(SIG_SETMASK, child_sigmask, NULL))) {
         604                 :          0 :             goto error;
         605                 :            :         }
         606                 :            :     }
         607                 :            : #endif
         608                 :            :
         609                 :            : #ifdef HAVE_SETSID
         610         [ #  # ]:          0 :     if (call_setsid)
         611         [ #  # ]:          0 :         POSIX_CALL(setsid());
         612                 :            : #endif
         613                 :            :
         614                 :            : #ifdef HAVE_SETPGID
         615                 :            :     static_assert(_Py_IS_TYPE_SIGNED(pid_t), "pid_t is unsigned");
         616         [ #  # ]:          0 :     if (pgid_to_set >= 0) {
         617         [ #  # ]:          0 :         POSIX_CALL(setpgid(0, pgid_to_set));
         618                 :            :     }
         619                 :            : #endif
         620                 :            :
         621                 :            : #ifdef HAVE_SETGROUPS
         622         [ #  # ]:          0 :     if (extra_group_size > 0)
         623         [ #  # ]:          0 :         POSIX_CALL(setgroups(extra_group_size, extra_groups));
         624                 :            : #endif /* HAVE_SETGROUPS */
         625                 :            :
         626                 :            : #ifdef HAVE_SETREGID
         627         [ #  # ]:          0 :     if (gid != (gid_t)-1)
         628         [ #  # ]:          0 :         POSIX_CALL(setregid(gid, gid));
         629                 :            : #endif /* HAVE_SETREGID */
         630                 :            :
         631                 :            : #ifdef HAVE_SETREUID
         632         [ #  # ]:          0 :     if (uid != (uid_t)-1)
         633         [ #  # ]:          0 :         POSIX_CALL(setreuid(uid, uid));
         634                 :            : #endif /* HAVE_SETREUID */
         635                 :            :
         636                 :            :
         637                 :          0 :     reached_preexec = 1;
         638   [ #  #  #  # ]:          0 :     if (preexec_fn != Py_None && preexec_fn_args_tuple) {
         639                 :            :         /* This is where the user has asked us to deadlock their program. */
         640                 :          0 :         result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
         641         [ #  # ]:          0 :         if (result == NULL) {
         642                 :            :             /* Stringifying the exception or traceback would involve
         643                 :            :              * memory allocation and thus potential for deadlock.
         644                 :            :              * We've already faced potential deadlock by calling back
         645                 :            :              * into Python in the first place, so it probably doesn't
         646                 :            :              * matter but we avoid it to minimize the possibility. */
         647                 :          0 :             err_msg = "Exception occurred in preexec_fn.";
         648                 :          0 :             errno = 0;  /* We don't want to report an OSError. */
         649                 :          0 :             goto error;
         650                 :            :         }
         651                 :            :         /* Py_DECREF(result); - We're about to exec so why bother? */
         652                 :            :     }
         653                 :            :
         654                 :            :     /* close FDs after executing preexec_fn, which might open FDs */
         655         [ #  # ]:          0 :     if (close_fds) {
         656                 :            :         /* TODO HP-UX could use pstat_getproc() if anyone cares about it. */
         657                 :          0 :         _close_open_fds(3, py_fds_to_keep);
         658                 :            :     }
         659                 :            :
         660                 :            :     /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
         661                 :            :     /* given the executable_list generated by Lib/subprocess.py.     */
         662                 :          0 :     saved_errno = 0;
         663         [ #  # ]:          0 :     for (i = 0; exec_array[i] != NULL; ++i) {
         664                 :          0 :         const char *executable = exec_array[i];
         665         [ #  # ]:          0 :         if (envp) {
         666                 :          0 :             execve(executable, argv, envp);
         667                 :            :         } else {
         668                 :          0 :             execv(executable, argv);
         669                 :            :         }
         670   [ #  #  #  #  :          0 :         if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
                       #  # ]
         671                 :          0 :             saved_errno = errno;
         672                 :            :         }
         673                 :            :     }
         674                 :            :     /* Report the first exec error, not the last. */
         675         [ #  # ]:          0 :     if (saved_errno)
         676                 :          0 :         errno = saved_errno;
         677                 :            :
         678                 :          0 : error:
         679                 :          0 :     saved_errno = errno;
         680                 :            :     /* Report the posix error to our parent process. */
         681                 :            :     /* We ignore all write() return values as the total size of our writes is
         682                 :            :        less than PIPEBUF and we cannot do anything about an error anyways.
         683                 :            :        Use _Py_write_noraise() to retry write() if it is interrupted by a
         684                 :            :        signal (fails with EINTR). */
         685         [ #  # ]:          0 :     if (saved_errno) {
         686                 :            :         char *cur;
         687                 :          0 :         _Py_write_noraise(errpipe_write, "OSError:", 8);
         688                 :          0 :         cur = hex_errno + sizeof(hex_errno);
         689   [ #  #  #  # ]:          0 :         while (saved_errno != 0 && cur != hex_errno) {
         690                 :          0 :             *--cur = Py_hexdigits[saved_errno % 16];
         691                 :          0 :             saved_errno /= 16;
         692                 :            :         }
         693                 :          0 :         _Py_write_noraise(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
         694                 :          0 :         _Py_write_noraise(errpipe_write, ":", 1);
         695         [ #  # ]:          0 :         if (!reached_preexec) {
         696                 :            :             /* Indicate to the parent that the error happened before exec(). */
         697                 :          0 :             _Py_write_noraise(errpipe_write, "noexec", 6);
         698                 :            :         }
         699                 :            :         /* We can't call strerror(saved_errno).  It is not async signal safe.
         700                 :            :          * The parent process will look the error message up. */
         701                 :            :     } else {
         702                 :          0 :         _Py_write_noraise(errpipe_write, "SubprocessError:0:", 18);
         703                 :          0 :         _Py_write_noraise(errpipe_write, err_msg, strlen(err_msg));
         704                 :            :     }
         705                 :          0 : }
         706                 :            :
         707                 :            :
         708                 :            : /* The main purpose of this wrapper function is to isolate vfork() from both
         709                 :            :  * subprocess_fork_exec() and child_exec(). A child process created via
         710                 :            :  * vfork() executes on the same stack as the parent process while the latter is
         711                 :            :  * suspended, so this function should not be inlined to avoid compiler bugs
         712                 :            :  * that might clobber data needed by the parent later. Additionally,
         713                 :            :  * child_exec() should not be inlined to avoid spurious -Wclobber warnings from
         714                 :            :  * GCC (see bpo-35823).
         715                 :            :  */
         716                 :            : Py_NO_INLINE static pid_t
         717                 :          0 : do_fork_exec(char *const exec_array[],
         718                 :            :              char *const argv[],
         719                 :            :              char *const envp[],
         720                 :            :              const char *cwd,
         721                 :            :              int p2cread, int p2cwrite,
         722                 :            :              int c2pread, int c2pwrite,
         723                 :            :              int errread, int errwrite,
         724                 :            :              int errpipe_read, int errpipe_write,
         725                 :            :              int close_fds, int restore_signals,
         726                 :            :              int call_setsid, pid_t pgid_to_set,
         727                 :            :              gid_t gid,
         728                 :            :              Py_ssize_t extra_group_size, const gid_t *extra_groups,
         729                 :            :              uid_t uid, int child_umask,
         730                 :            :              const void *child_sigmask,
         731                 :            :              PyObject *py_fds_to_keep,
         732                 :            :              PyObject *preexec_fn,
         733                 :            :              PyObject *preexec_fn_args_tuple)
         734                 :            : {
         735                 :            :
         736                 :            :     pid_t pid;
         737                 :            :
         738                 :            : #ifdef VFORK_USABLE
         739         [ #  # ]:          0 :     if (child_sigmask) {
         740                 :            :         /* These are checked by our caller; verify them in debug builds. */
         741                 :            :         assert(uid == (uid_t)-1);
         742                 :            :         assert(gid == (gid_t)-1);
         743                 :            :         assert(extra_group_size < 0);
         744                 :            :         assert(preexec_fn == Py_None);
         745                 :            :
         746                 :          0 :         pid = vfork();
         747         [ #  # ]:          0 :         if (pid == -1) {
         748                 :            :             /* If vfork() fails, fall back to using fork(). When it isn't
         749                 :            :              * allowed in a process by the kernel, vfork can return -1
         750                 :            :              * with errno EINVAL. https://bugs.python.org/issue47151. */
         751                 :          0 :             pid = fork();
         752                 :            :         }
         753                 :            :     } else
         754                 :            : #endif
         755                 :            :     {
         756                 :          0 :         pid = fork();
         757                 :            :     }
         758                 :            :
         759         [ #  # ]:          0 :     if (pid != 0) {
         760                 :          0 :         return pid;
         761                 :            :     }
         762                 :            :
         763                 :            :     /* Child process.
         764                 :            :      * See the comment above child_exec() for restrictions imposed on
         765                 :            :      * the code below.
         766                 :            :      */
         767                 :            :
         768         [ #  # ]:          0 :     if (preexec_fn != Py_None) {
         769                 :            :         /* We'll be calling back into Python later so we need to do this.
         770                 :            :          * This call may not be async-signal-safe but neither is calling
         771                 :            :          * back into Python.  The user asked us to use hope as a strategy
         772                 :            :          * to avoid deadlock... */
         773                 :          0 :         PyOS_AfterFork_Child();
         774                 :            :     }
         775                 :            :
         776                 :          0 :     child_exec(exec_array, argv, envp, cwd,
         777                 :            :                p2cread, p2cwrite, c2pread, c2pwrite,
         778                 :            :                errread, errwrite, errpipe_read, errpipe_write,
         779                 :            :                close_fds, restore_signals, call_setsid, pgid_to_set,
         780                 :            :                gid, extra_group_size, extra_groups,
         781                 :            :                uid, child_umask, child_sigmask,
         782                 :            :                py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
         783                 :          0 :     _exit(255);
         784                 :            :     return 0;  /* Dead code to avoid a potential compiler warning. */
         785                 :            : }
         786                 :            :
         787                 :            :
         788                 :            : static PyObject *
         789                 :          0 : subprocess_fork_exec(PyObject *module, PyObject *args)
         790                 :            : {
         791                 :          0 :     PyObject *gc_module = NULL;
         792                 :            :     PyObject *executable_list, *py_fds_to_keep;
         793                 :            :     PyObject *env_list, *preexec_fn;
         794                 :          0 :     PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
         795                 :          0 :     PyObject *preexec_fn_args_tuple = NULL;
         796                 :            :     PyObject *extra_groups_packed;
         797                 :            :     PyObject *uid_object, *gid_object;
         798                 :            :     int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
         799                 :            :     int errpipe_read, errpipe_write, close_fds, restore_signals;
         800                 :            :     int call_setsid;
         801                 :          0 :     pid_t pgid_to_set = -1;
         802                 :          0 :     gid_t *extra_groups = NULL;
         803                 :            :     int child_umask;
         804                 :          0 :     PyObject *cwd_obj, *cwd_obj2 = NULL;
         805                 :            :     const char *cwd;
         806                 :          0 :     pid_t pid = -1;
         807                 :          0 :     int need_to_reenable_gc = 0;
         808                 :          0 :     char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
         809                 :          0 :     Py_ssize_t arg_num, extra_group_size = 0;
         810                 :          0 :     int need_after_fork = 0;
         811                 :          0 :     int saved_errno = 0;
         812                 :            :     int allow_vfork;
         813                 :            :
         814         [ #  # ]:          0 :     if (!PyArg_ParseTuple(
         815                 :            :             args, "OOpO!OOiiiiiiiipp" _Py_PARSE_PID "OOOiOp:fork_exec",
         816                 :            :             &process_args, &executable_list,
         817                 :            :             &close_fds, &PyTuple_Type, &py_fds_to_keep,
         818                 :            :             &cwd_obj, &env_list,
         819                 :            :             &p2cread, &p2cwrite, &c2pread, &c2pwrite,
         820                 :            :             &errread, &errwrite, &errpipe_read, &errpipe_write,
         821                 :            :             &restore_signals, &call_setsid, &pgid_to_set,
         822                 :            :             &gid_object, &extra_groups_packed, &uid_object, &child_umask,
         823                 :            :             &preexec_fn, &allow_vfork))
         824                 :          0 :         return NULL;
         825                 :            :
         826                 :          0 :     PyInterpreterState *interp = PyInterpreterState_Get();
         827   [ #  #  #  # ]:          0 :     if ((preexec_fn != Py_None) && (interp != PyInterpreterState_Main())) {
         828                 :          0 :         PyErr_SetString(PyExc_RuntimeError,
         829                 :            :                         "preexec_fn not supported within subinterpreters");
         830                 :          0 :         return NULL;
         831                 :            :     }
         832                 :            :
         833   [ #  #  #  # ]:          0 :     if (close_fds && errpipe_write < 3) {  /* precondition */
         834                 :          0 :         PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
         835                 :          0 :         return NULL;
         836                 :            :     }
         837         [ #  # ]:          0 :     if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
         838                 :          0 :         PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
         839                 :          0 :         return NULL;
         840                 :            :     }
         841                 :            :
         842                 :            :     /* We need to call gc.disable() when we'll be calling preexec_fn */
         843         [ #  # ]:          0 :     if (preexec_fn != Py_None) {
         844                 :          0 :         need_to_reenable_gc = PyGC_Disable();
         845                 :            :     }
         846                 :            :
         847                 :          0 :     exec_array = _PySequence_BytesToCharpArray(executable_list);
         848         [ #  # ]:          0 :     if (!exec_array)
         849                 :          0 :         goto cleanup;
         850                 :            :
         851                 :            :     /* Convert args and env into appropriate arguments for exec() */
         852                 :            :     /* These conversions are done in the parent process to avoid allocating
         853                 :            :        or freeing memory in the child process. */
         854         [ #  # ]:          0 :     if (process_args != Py_None) {
         855                 :            :         Py_ssize_t num_args;
         856                 :            :         /* Equivalent to:  */
         857                 :            :         /*  tuple(PyUnicode_FSConverter(arg) for arg in process_args)  */
         858                 :          0 :         fast_args = PySequence_Fast(process_args, "argv must be a tuple");
         859         [ #  # ]:          0 :         if (fast_args == NULL)
         860                 :          0 :             goto cleanup;
         861         [ #  # ]:          0 :         num_args = PySequence_Fast_GET_SIZE(fast_args);
         862                 :          0 :         converted_args = PyTuple_New(num_args);
         863         [ #  # ]:          0 :         if (converted_args == NULL)
         864                 :          0 :             goto cleanup;
         865         [ #  # ]:          0 :         for (arg_num = 0; arg_num < num_args; ++arg_num) {
         866                 :            :             PyObject *borrowed_arg, *converted_arg;
         867   [ #  #  #  # ]:          0 :             if (PySequence_Fast_GET_SIZE(fast_args) != num_args) {
         868                 :          0 :                 PyErr_SetString(PyExc_RuntimeError, "args changed during iteration");
         869                 :          0 :                 goto cleanup;
         870                 :            :             }
         871         [ #  # ]:          0 :             borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
         872         [ #  # ]:          0 :             if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
         873                 :          0 :                 goto cleanup;
         874                 :          0 :             PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
         875                 :            :         }
         876                 :            :
         877                 :          0 :         argv = _PySequence_BytesToCharpArray(converted_args);
         878         [ #  # ]:          0 :         Py_CLEAR(converted_args);
         879         [ #  # ]:          0 :         Py_CLEAR(fast_args);
         880         [ #  # ]:          0 :         if (!argv)
         881                 :          0 :             goto cleanup;
         882                 :            :     }
         883                 :            :
         884         [ #  # ]:          0 :     if (env_list != Py_None) {
         885                 :          0 :         envp = _PySequence_BytesToCharpArray(env_list);
         886         [ #  # ]:          0 :         if (!envp)
         887                 :          0 :             goto cleanup;
         888                 :            :     }
         889                 :            :
         890         [ #  # ]:          0 :     if (cwd_obj != Py_None) {
         891         [ #  # ]:          0 :         if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
         892                 :          0 :             goto cleanup;
         893                 :          0 :         cwd = PyBytes_AsString(cwd_obj2);
         894                 :            :     } else {
         895                 :          0 :         cwd = NULL;
         896                 :            :     }
         897                 :            :
         898         [ #  # ]:          0 :     if (extra_groups_packed != Py_None) {
         899                 :            : #ifdef HAVE_SETGROUPS
         900         [ #  # ]:          0 :         if (!PyList_Check(extra_groups_packed)) {
         901                 :          0 :             PyErr_SetString(PyExc_TypeError,
         902                 :            :                     "setgroups argument must be a list");
         903                 :          0 :             goto cleanup;
         904                 :            :         }
         905                 :          0 :         extra_group_size = PySequence_Size(extra_groups_packed);
         906                 :            :
         907         [ #  # ]:          0 :         if (extra_group_size < 0)
         908                 :          0 :             goto cleanup;
         909                 :            :
         910         [ #  # ]:          0 :         if (extra_group_size > MAX_GROUPS) {
         911                 :          0 :             PyErr_SetString(PyExc_ValueError, "too many extra_groups");
         912                 :          0 :             goto cleanup;
         913                 :            :         }
         914                 :            :
         915                 :            :         /* Deliberately keep extra_groups == NULL for extra_group_size == 0 */
         916         [ #  # ]:          0 :         if (extra_group_size > 0) {
         917                 :          0 :             extra_groups = PyMem_RawMalloc(extra_group_size * sizeof(gid_t));
         918         [ #  # ]:          0 :             if (extra_groups == NULL) {
         919                 :          0 :                 PyErr_SetString(PyExc_MemoryError,
         920                 :            :                         "failed to allocate memory for group list");
         921                 :          0 :                 goto cleanup;
         922                 :            :             }
         923                 :            :         }
         924                 :            :
         925         [ #  # ]:          0 :         for (Py_ssize_t i = 0; i < extra_group_size; i++) {
         926                 :            :             PyObject *elem;
         927                 :          0 :             elem = PySequence_GetItem(extra_groups_packed, i);
         928         [ #  # ]:          0 :             if (!elem)
         929                 :          0 :                 goto cleanup;
         930         [ #  # ]:          0 :             if (!PyLong_Check(elem)) {
         931                 :          0 :                 PyErr_SetString(PyExc_TypeError,
         932                 :            :                                 "extra_groups must be integers");
         933                 :          0 :                 Py_DECREF(elem);
         934                 :          0 :                 goto cleanup;
         935                 :            :             } else {
         936                 :            :                 gid_t gid;
         937         [ #  # ]:          0 :                 if (!_Py_Gid_Converter(elem, &gid)) {
         938                 :          0 :                     Py_DECREF(elem);
         939                 :          0 :                     PyErr_SetString(PyExc_ValueError, "invalid group id");
         940                 :          0 :                     goto cleanup;
         941                 :            :                 }
         942                 :          0 :                 extra_groups[i] = gid;
         943                 :            :             }
         944                 :          0 :             Py_DECREF(elem);
         945                 :            :         }
         946                 :            :
         947                 :            : #else /* HAVE_SETGROUPS */
         948                 :            :         PyErr_BadInternalCall();
         949                 :            :         goto cleanup;
         950                 :            : #endif /* HAVE_SETGROUPS */
         951                 :            :     }
         952                 :            :
         953                 :          0 :     gid_t gid = (gid_t)-1;
         954         [ #  # ]:          0 :     if (gid_object != Py_None) {
         955                 :            : #ifdef HAVE_SETREGID
         956         [ #  # ]:          0 :         if (!_Py_Gid_Converter(gid_object, &gid))
         957                 :          0 :             goto cleanup;
         958                 :            :
         959                 :            : #else /* HAVE_SETREGID */
         960                 :            :         PyErr_BadInternalCall();
         961                 :            :         goto cleanup;
         962                 :            : #endif /* HAVE_SETREUID */
         963                 :            :     }
         964                 :            :
         965                 :          0 :     uid_t uid = (uid_t)-1;
         966         [ #  # ]:          0 :     if (uid_object != Py_None) {
         967                 :            : #ifdef HAVE_SETREUID
         968         [ #  # ]:          0 :         if (!_Py_Uid_Converter(uid_object, &uid))
         969                 :          0 :             goto cleanup;
         970                 :            :
         971                 :            : #else /* HAVE_SETREUID */
         972                 :            :         PyErr_BadInternalCall();
         973                 :            :         goto cleanup;
         974                 :            : #endif /* HAVE_SETREUID */
         975                 :            :     }
         976                 :            :
         977                 :            :     /* This must be the last thing done before fork() because we do not
         978                 :            :      * want to call PyOS_BeforeFork() if there is any chance of another
         979                 :            :      * error leading to the cleanup: code without calling fork(). */
         980         [ #  # ]:          0 :     if (preexec_fn != Py_None) {
         981                 :          0 :         preexec_fn_args_tuple = PyTuple_New(0);
         982         [ #  # ]:          0 :         if (!preexec_fn_args_tuple)
         983                 :          0 :             goto cleanup;
         984                 :          0 :         PyOS_BeforeFork();
         985                 :          0 :         need_after_fork = 1;
         986                 :            :     }
         987                 :            :
         988                 :            :     /* NOTE: When old_sigmask is non-NULL, do_fork_exec() may use vfork(). */
         989                 :          0 :     const void *old_sigmask = NULL;
         990                 :            : #ifdef VFORK_USABLE
         991                 :            :     /* Use vfork() only if it's safe. See the comment above child_exec(). */
         992                 :            :     sigset_t old_sigs;
         993   [ #  #  #  # ]:          0 :     if (preexec_fn == Py_None && allow_vfork &&
         994   [ #  #  #  #  :          0 :         uid == (uid_t)-1 && gid == (gid_t)-1 && extra_group_size < 0) {
                       #  # ]
         995                 :            :         /* Block all signals to ensure that no signal handlers are run in the
         996                 :            :          * child process while it shares memory with us. Note that signals
         997                 :            :          * used internally by C libraries won't be blocked by
         998                 :            :          * pthread_sigmask(), but signal handlers installed by C libraries
         999                 :            :          * normally service only signals originating from *within the process*,
        1000                 :            :          * so it should be sufficient to consider any library function that
        1001                 :            :          * might send such a signal to be vfork-unsafe and do not call it in
        1002                 :            :          * the child.
        1003                 :            :          */
        1004                 :            :         sigset_t all_sigs;
        1005                 :          0 :         sigfillset(&all_sigs);
        1006         [ #  # ]:          0 :         if ((saved_errno = pthread_sigmask(SIG_BLOCK, &all_sigs, &old_sigs))) {
        1007                 :          0 :             goto cleanup;
        1008                 :            :         }
        1009                 :          0 :         old_sigmask = &old_sigs;
        1010                 :            :     }
        1011                 :            : #endif
        1012                 :            :
        1013                 :          0 :     pid = do_fork_exec(exec_array, argv, envp, cwd,
        1014                 :            :                        p2cread, p2cwrite, c2pread, c2pwrite,
        1015                 :            :                        errread, errwrite, errpipe_read, errpipe_write,
        1016                 :            :                        close_fds, restore_signals, call_setsid, pgid_to_set,
        1017                 :            :                        gid, extra_group_size, extra_groups,
        1018                 :            :                        uid, child_umask, old_sigmask,
        1019                 :            :                        py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
        1020                 :            :
        1021                 :            :     /* Parent (original) process */
        1022         [ #  # ]:          0 :     if (pid == -1) {
        1023                 :            :         /* Capture errno for the exception. */
        1024                 :          0 :         saved_errno = errno;
        1025                 :            :     }
        1026                 :            :
        1027                 :            : #ifdef VFORK_USABLE
        1028         [ #  # ]:          0 :     if (old_sigmask) {
        1029                 :            :         /* vfork() semantics guarantees that the parent is blocked
        1030                 :            :          * until the child performs _exit() or execve(), so it is safe
        1031                 :            :          * to unblock signals once we're here.
        1032                 :            :          * Note that in environments where vfork() is implemented as fork(),
        1033                 :            :          * such as QEMU user-mode emulation, the parent won't be blocked,
        1034                 :            :          * but it won't share the address space with the child,
        1035                 :            :          * so it's still safe to unblock the signals.
        1036                 :            :          *
        1037                 :            :          * We don't handle errors here because this call can't fail
        1038                 :            :          * if valid arguments are given, and because there is no good
        1039                 :            :          * way for the caller to deal with a failure to restore
        1040                 :            :          * the thread signal mask. */
        1041                 :          0 :         (void) pthread_sigmask(SIG_SETMASK, old_sigmask, NULL);
        1042                 :            :     }
        1043                 :            : #endif
        1044                 :            :
        1045         [ #  # ]:          0 :     if (need_after_fork)
        1046                 :          0 :         PyOS_AfterFork_Parent();
        1047                 :            :
        1048                 :          0 : cleanup:
        1049         [ #  # ]:          0 :     if (saved_errno != 0) {
        1050                 :          0 :         errno = saved_errno;
        1051                 :            :         /* We can't call this above as PyOS_AfterFork_Parent() calls back
        1052                 :            :          * into Python code which would see the unreturned error. */
        1053                 :          0 :         PyErr_SetFromErrno(PyExc_OSError);
        1054                 :            :     }
        1055                 :            :
        1056                 :          0 :     Py_XDECREF(preexec_fn_args_tuple);
        1057                 :          0 :     PyMem_RawFree(extra_groups);
        1058                 :          0 :     Py_XDECREF(cwd_obj2);
        1059         [ #  # ]:          0 :     if (envp)
        1060                 :          0 :         _Py_FreeCharPArray(envp);
        1061                 :          0 :     Py_XDECREF(converted_args);
        1062                 :          0 :     Py_XDECREF(fast_args);
        1063         [ #  # ]:          0 :     if (argv)
        1064                 :          0 :         _Py_FreeCharPArray(argv);
        1065         [ #  # ]:          0 :     if (exec_array)
        1066                 :          0 :         _Py_FreeCharPArray(exec_array);
        1067                 :            :
        1068         [ #  # ]:          0 :     if (need_to_reenable_gc) {
        1069                 :          0 :         PyGC_Enable();
        1070                 :            :     }
        1071                 :          0 :     Py_XDECREF(gc_module);
        1072                 :            :
        1073         [ #  # ]:          0 :     return pid == -1 ? NULL : PyLong_FromPid(pid);
        1074                 :            : }
        1075                 :            :
        1076                 :            :
        1077                 :            : PyDoc_STRVAR(subprocess_fork_exec_doc,
        1078                 :            : "fork_exec(args, executable_list, close_fds, pass_fds, cwd, env,\n\
        1079                 :            :           p2cread, p2cwrite, c2pread, c2pwrite,\n\
        1080                 :            :           errread, errwrite, errpipe_read, errpipe_write,\n\
        1081                 :            :           restore_signals, call_setsid, pgid_to_set,\n\
        1082                 :            :           gid, extra_groups, uid,\n\
        1083                 :            :           preexec_fn)\n\
        1084                 :            : \n\
        1085                 :            : Forks a child process, closes parent file descriptors as appropriate in the\n\
        1086                 :            : child and dups the few that are needed before calling exec() in the child\n\
        1087                 :            : process.\n\
        1088                 :            : \n\
        1089                 :            : If close_fds is true, close file descriptors 3 and higher, except those listed\n\
        1090                 :            : in the sorted tuple pass_fds.\n\
        1091                 :            : \n\
        1092                 :            : The preexec_fn, if supplied, will be called immediately before closing file\n\
        1093                 :            : descriptors and exec.\n\
        1094                 :            : WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
        1095                 :            :          It may trigger infrequent, difficult to debug deadlocks.\n\
        1096                 :            : \n\
        1097                 :            : If an error occurs in the child process before the exec, it is\n\
        1098                 :            : serialized and written to the errpipe_write fd per subprocess.py.\n\
        1099                 :            : \n\
        1100                 :            : Returns: the child process's PID.\n\
        1101                 :            : \n\
        1102                 :            : Raises: Only on an error in the parent process.\n\
        1103                 :            : ");
        1104                 :            :
        1105                 :            : /* module level code ********************************************************/
        1106                 :            :
        1107                 :            : PyDoc_STRVAR(module_doc,
        1108                 :            : "A POSIX helper for the subprocess module.");
        1109                 :            :
        1110                 :            : static PyMethodDef module_methods[] = {
        1111                 :            :     {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
        1112                 :            :     {NULL, NULL}  /* sentinel */
        1113                 :            : };
        1114                 :            :
        1115                 :            : static PyModuleDef_Slot _posixsubprocess_slots[] = {
        1116                 :            :     {0, NULL}
        1117                 :            : };
        1118                 :            :
        1119                 :            : static struct PyModuleDef _posixsubprocessmodule = {
        1120                 :            :         PyModuleDef_HEAD_INIT,
        1121                 :            :         .m_name = "_posixsubprocess",
        1122                 :            :         .m_doc = module_doc,
        1123                 :            :         .m_size = 0,
        1124                 :            :         .m_methods = module_methods,
        1125                 :            :         .m_slots = _posixsubprocess_slots,
        1126                 :            : };
        1127                 :            :
        1128                 :            : PyMODINIT_FUNC
        1129                 :          2 : PyInit__posixsubprocess(void)
        1130                 :            : {
        1131                 :          2 :     return PyModuleDef_Init(&_posixsubprocessmodule);
        1132                 :            : }

Generated by: LCOV version 1.14