blob: cbdeecfda1c236b9afdc147e168c24ca80a562f1 [file] [log] [blame]
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001/* Authors: Gregory P. Smith & Jeffrey Yasskin */
2#include "Python.h"
Victor Stinner5572ba72011-05-26 14:10:08 +02003#if defined(HAVE_PIPE2) && !defined(_GNU_SOURCE)
4# define _GNU_SOURCE
Gregory P. Smith51ee2702010-12-13 07:59:39 +00005#endif
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00006#include <unistd.h>
Gregory P. Smith51ee2702010-12-13 07:59:39 +00007#include <fcntl.h>
Gregory P. Smith8facece2012-01-21 14:01:08 -08008#ifdef HAVE_SYS_TYPES_H
9#include <sys/types.h>
10#endif
Gregory P. Smith4842efc2012-01-21 21:01:24 -080011#if defined(HAVE_SYS_STAT_H) && defined(__FreeBSD__)
12#include <sys/stat.h>
13#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080014#ifdef HAVE_SYS_SYSCALL_H
15#include <sys/syscall.h>
16#endif
Gregory P. Smithf9681772015-04-25 23:43:34 -070017#if defined(HAVE_SYS_RESOURCE_H)
18#include <sys/resource.h>
19#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080020#ifdef HAVE_DIRENT_H
21#include <dirent.h>
22#endif
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000023
Gregory P. Smith3015fb82018-11-12 22:01:22 -080024#ifdef _Py_MEMORY_SANITIZER
Gregory P. Smith1584a002018-11-12 12:07:14 -080025# include <sanitizer/msan_interface.h>
26#endif
27
Xavier de Gayec716f182016-06-15 11:35:29 +020028#if defined(__ANDROID__) && __ANDROID_API__ < 21 && !defined(SYS_getdents64)
Gregory P. Smithefeb9da2014-04-14 13:31:21 -070029# include <sys/linux-syscalls.h>
30# define SYS_getdents64 __NR_getdents64
31#endif
32
Jakub Kulík6f9bc722018-12-31 03:16:40 +010033#if defined(__sun) && defined(__SVR4)
Gregory P. Smithe3f78482012-01-21 15:16:17 -080034/* readdir64 is used to work around Solaris 9 bug 6395699. */
35# define readdir readdir64
36# define dirent dirent64
37# if !defined(HAVE_DIRFD)
Gregory P. Smith8facece2012-01-21 14:01:08 -080038/* Some versions of Solaris lack dirfd(). */
Gregory P. Smithe9b7cab2012-01-21 15:19:11 -080039# define dirfd(dirp) ((dirp)->dd_fd)
Gregory P. Smithe3f78482012-01-21 15:16:17 -080040# define HAVE_DIRFD
Gregory P. Smithe3f78482012-01-21 15:16:17 -080041# endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080042#endif
43
Gregory P. Smith4842efc2012-01-21 21:01:24 -080044#if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__))
45# define FD_DIR "/dev/fd"
46#else
47# define FD_DIR "/proc/self/fd"
48#endif
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000049
Victor Stinnerdaf45552013-08-28 00:53:59 +020050#define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000051
Dino Viehland5a7d2e12019-09-10 12:01:20 +010052typedef struct {
53 PyObject* disable;
54 PyObject* enable;
55 PyObject* isenabled;
56} _posixsubprocessstate;
57
58static struct PyModuleDef _posixsubprocessmodule;
59
60#define _posixsubprocessstate(o) ((_posixsubprocessstate *)PyModule_GetState(o))
61#define _posixsubprocessstate_global _posixsubprocessstate(PyState_FindModule(&_posixsubprocessmodule))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000062
Martin Panterafdd5132015-11-30 02:21:41 +000063/* If gc was disabled, call gc.enable(). Return 0 on success. */
Benjamin Peterson91eef982012-01-22 20:04:46 -050064static int
Martin Panterafdd5132015-11-30 02:21:41 +000065_enable_gc(int need_to_reenable_gc, PyObject *gc_module)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000066{
67 PyObject *result;
Martin Panterafdd5132015-11-30 02:21:41 +000068 PyObject *exctype, *val, *tb;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020069
Martin Panterafdd5132015-11-30 02:21:41 +000070 if (need_to_reenable_gc) {
71 PyErr_Fetch(&exctype, &val, &tb);
Dino Viehland5a7d2e12019-09-10 12:01:20 +010072 result = _PyObject_CallMethodNoArgs(
73 gc_module, _posixsubprocessstate_global->enable);
Martin Panterafdd5132015-11-30 02:21:41 +000074 if (exctype != NULL) {
75 PyErr_Restore(exctype, val, tb);
76 }
77 if (result == NULL) {
78 return 1;
79 }
80 Py_DECREF(result);
81 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000082 return 0;
83}
84
85
Gregory P. Smith8facece2012-01-21 14:01:08 -080086/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
Benjamin Peterson91eef982012-01-22 20:04:46 -050087static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020088_pos_int_from_ascii(const char *name)
Gregory P. Smith8facece2012-01-21 14:01:08 -080089{
90 int num = 0;
91 while (*name >= '0' && *name <= '9') {
92 num = num * 10 + (*name - '0');
93 ++name;
94 }
95 if (*name)
96 return -1; /* Non digit found, not a number. */
97 return num;
98}
99
100
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800101#if defined(__FreeBSD__)
102/* When /dev/fd isn't mounted it is often a static directory populated
103 * with 0 1 2 or entries for 0 .. 63 on FreeBSD, NetBSD and OpenBSD.
104 * NetBSD and OpenBSD have a /proc fs available (though not necessarily
105 * mounted) and do not have fdescfs for /dev/fd. MacOS X has a devfs
106 * that properly supports /dev/fd.
107 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500108static int
Ross Lagerwall7f4fdb22012-03-07 20:06:33 +0200109_is_fdescfs_mounted_on_dev_fd(void)
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800110{
111 struct stat dev_stat;
112 struct stat dev_fd_stat;
113 if (stat("/dev", &dev_stat) != 0)
114 return 0;
115 if (stat(FD_DIR, &dev_fd_stat) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200116 return 0;
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800117 if (dev_stat.st_dev == dev_fd_stat.st_dev)
118 return 0; /* / == /dev == /dev/fd means it is static. #fail */
119 return 1;
120}
121#endif
122
123
Gregory P. Smith8facece2012-01-21 14:01:08 -0800124/* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500125static int
126_sanity_check_python_fd_sequence(PyObject *fd_sequence)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800127{
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300128 Py_ssize_t seq_idx;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800129 long prev_fd = -1;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300130 for (seq_idx = 0; seq_idx < PyTuple_GET_SIZE(fd_sequence); ++seq_idx) {
131 PyObject* py_fd = PyTuple_GET_ITEM(fd_sequence, seq_idx);
132 long iter_fd;
133 if (!PyLong_Check(py_fd)) {
134 return 1;
135 }
136 iter_fd = PyLong_AsLong(py_fd);
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -0800137 if (iter_fd < 0 || iter_fd <= prev_fd || iter_fd > INT_MAX) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300138 /* Negative, overflow, unsorted, too big for a fd. */
Gregory P. Smith8facece2012-01-21 14:01:08 -0800139 return 1;
140 }
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -0800141 prev_fd = iter_fd;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800142 }
143 return 0;
144}
145
146
147/* Is fd found in the sorted Python Sequence? */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500148static int
149_is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800150{
151 /* Binary search. */
152 Py_ssize_t search_min = 0;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300153 Py_ssize_t search_max = PyTuple_GET_SIZE(fd_sequence) - 1;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800154 if (search_max < 0)
155 return 0;
156 do {
157 long middle = (search_min + search_max) / 2;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300158 long middle_fd = PyLong_AsLong(PyTuple_GET_ITEM(fd_sequence, middle));
Gregory P. Smith8facece2012-01-21 14:01:08 -0800159 if (fd == middle_fd)
160 return 1;
161 if (fd > middle_fd)
162 search_min = middle + 1;
163 else
164 search_max = middle - 1;
165 } while (search_min <= search_max);
166 return 0;
167}
168
Victor Stinnerdaf45552013-08-28 00:53:59 +0200169static int
170make_inheritable(PyObject *py_fds_to_keep, int errpipe_write)
171{
172 Py_ssize_t i, len;
173
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300174 len = PyTuple_GET_SIZE(py_fds_to_keep);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200175 for (i = 0; i < len; ++i) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300176 PyObject* fdobj = PyTuple_GET_ITEM(py_fds_to_keep, i);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200177 long fd = PyLong_AsLong(fdobj);
178 assert(!PyErr_Occurred());
179 assert(0 <= fd && fd <= INT_MAX);
180 if (fd == errpipe_write) {
181 /* errpipe_write is part of py_fds_to_keep. It must be closed at
182 exec(), but kept open in the child process until exec() is
183 called. */
184 continue;
185 }
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300186 if (_Py_set_inheritable_async_safe((int)fd, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200187 return -1;
188 }
189 return 0;
190}
191
Gregory P. Smith8facece2012-01-21 14:01:08 -0800192
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700193/* Get the maximum file descriptor that could be opened by this process.
194 * This function is async signal safe for use between fork() and exec().
195 */
196static long
197safe_get_max_fd(void)
198{
199 long local_max_fd;
200#if defined(__NetBSD__)
201 local_max_fd = fcntl(0, F_MAXFD);
202 if (local_max_fd >= 0)
203 return local_max_fd;
204#endif
Gregory P. Smithf9681772015-04-25 23:43:34 -0700205#if defined(HAVE_SYS_RESOURCE_H) && defined(__OpenBSD__)
206 struct rlimit rl;
207 /* Not on the POSIX async signal safe functions list but likely
208 * safe. TODO - Someone should audit OpenBSD to make sure. */
209 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
210 return (long) rl.rlim_max;
211#endif
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700212#ifdef _SC_OPEN_MAX
213 local_max_fd = sysconf(_SC_OPEN_MAX);
214 if (local_max_fd == -1)
215#endif
216 local_max_fd = 256; /* Matches legacy Lib/subprocess.py behavior. */
217 return local_max_fd;
218}
219
220
221/* Close all file descriptors in the range from start_fd and higher
222 * except for those in py_fds_to_keep. If the range defined by
223 * [start_fd, safe_get_max_fd()) is large this will take a long
224 * time as it calls close() on EVERY possible fd.
225 *
226 * It isn't possible to know for sure what the max fd to go up to
227 * is for processes with the capability of raising their maximum.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800228 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500229static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700230_close_fds_by_brute_force(long start_fd, PyObject *py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800231{
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700232 long end_fd = safe_get_max_fd();
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300233 Py_ssize_t num_fds_to_keep = PyTuple_GET_SIZE(py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800234 Py_ssize_t keep_seq_idx;
235 int fd_num;
236 /* As py_fds_to_keep is sorted we can loop through the list closing
luzpaza5293b42017-11-05 07:37:50 -0600237 * fds in between any in the keep list falling within our range. */
Gregory P. Smith8facece2012-01-21 14:01:08 -0800238 for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300239 PyObject* py_keep_fd = PyTuple_GET_ITEM(py_fds_to_keep, keep_seq_idx);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800240 int keep_fd = PyLong_AsLong(py_keep_fd);
241 if (keep_fd < start_fd)
242 continue;
243 for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200244 close(fd_num);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800245 }
246 start_fd = keep_fd + 1;
247 }
248 if (start_fd <= end_fd) {
249 for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200250 close(fd_num);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800251 }
252 }
253}
254
255
256#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
257/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
258 * only to read a directory of short file descriptor number names. The kernel
259 * will return an error if we didn't give it enough space. Highly Unlikely.
260 * This structure is very old and stable: It will not change unless the kernel
261 * chooses to break compatibility with all existing binaries. Highly Unlikely.
262 */
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800263struct linux_dirent64 {
Gregory P. Smith58f07a92012-06-05 13:26:39 -0700264 unsigned long long d_ino;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800265 long long d_off;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800266 unsigned short d_reclen; /* Length of this linux_dirent */
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800267 unsigned char d_type;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800268 char d_name[256]; /* Filename (null-terminated) */
269};
270
Gregory P. Smitha26987a2014-06-01 13:46:36 -0700271/* Close all open file descriptors in the range from start_fd and higher
272 * Do not close any in the sorted py_fds_to_keep list.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800273 *
274 * This version is async signal safe as it does not make any unsafe C library
275 * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
276 * to resort to making a kernel system call directly but this is the ONLY api
277 * available that does no harm. opendir/readdir/closedir perform memory
278 * allocation and locking so while they usually work they are not guaranteed
279 * to (especially if you have replaced your malloc implementation). A version
280 * of this function that uses those can be found in the _maybe_unsafe variant.
281 *
282 * This is Linux specific because that is all I am ready to test it on. It
283 * should be easy to add OS specific dirent or dirent64 structures and modify
284 * it with some cpp #define magic to work on other OSes as well if you want.
285 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500286static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700287_close_open_fds_safe(int start_fd, PyObject* py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800288{
289 int fd_dir_fd;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200290
Victor Stinner160e8192015-03-30 02:18:31 +0200291 fd_dir_fd = _Py_open_noraise(FD_DIR, O_RDONLY);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800292 if (fd_dir_fd == -1) {
293 /* No way to get a list of open fds. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700294 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800295 return;
296 } else {
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800297 char buffer[sizeof(struct linux_dirent64)];
Gregory P. Smith8facece2012-01-21 14:01:08 -0800298 int bytes;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800299 while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
300 (struct linux_dirent64 *)buffer,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800301 sizeof(buffer))) > 0) {
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800302 struct linux_dirent64 *entry;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800303 int offset;
Gregory P. Smith3015fb82018-11-12 22:01:22 -0800304#ifdef _Py_MEMORY_SANITIZER
Gregory P. Smith1584a002018-11-12 12:07:14 -0800305 __msan_unpoison(buffer, bytes);
306#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -0800307 for (offset = 0; offset < bytes; offset += entry->d_reclen) {
308 int fd;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800309 entry = (struct linux_dirent64 *)(buffer + offset);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800310 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
311 continue; /* Not a number. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700312 if (fd != fd_dir_fd && fd >= start_fd &&
Gregory P. Smith8facece2012-01-21 14:01:08 -0800313 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200314 close(fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800315 }
316 }
317 }
Victor Stinnere7c74922015-04-02 16:24:46 +0200318 close(fd_dir_fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800319 }
320}
321
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700322#define _close_open_fds _close_open_fds_safe
Gregory P. Smith8facece2012-01-21 14:01:08 -0800323
324#else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
325
326
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700327/* Close all open file descriptors from start_fd and higher.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300328 * Do not close any in the sorted py_fds_to_keep tuple.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800329 *
330 * This function violates the strict use of async signal safe functions. :(
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800331 * It calls opendir(), readdir() and closedir(). Of these, the one most
Gregory P. Smith8facece2012-01-21 14:01:08 -0800332 * likely to ever cause a problem is opendir() as it performs an internal
333 * malloc(). Practically this should not be a problem. The Java VM makes the
334 * same calls between fork and exec in its own UNIXProcess_md.c implementation.
335 *
336 * readdir_r() is not used because it provides no benefit. It is typically
337 * implemented as readdir() followed by memcpy(). See also:
338 * http://womble.decadent.org.uk/readdir_r-advisory.html
339 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500340static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700341_close_open_fds_maybe_unsafe(long start_fd, PyObject* py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800342{
343 DIR *proc_fd_dir;
344#ifndef HAVE_DIRFD
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700345 while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep)) {
Gregory P. Smith8facece2012-01-21 14:01:08 -0800346 ++start_fd;
347 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800348 /* Close our lowest fd before we call opendir so that it is likely to
349 * reuse that fd otherwise we might close opendir's file descriptor in
350 * our loop. This trick assumes that fd's are allocated on a lowest
351 * available basis. */
Victor Stinnere7c74922015-04-02 16:24:46 +0200352 close(start_fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800353 ++start_fd;
354#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -0800355
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800356#if defined(__FreeBSD__)
357 if (!_is_fdescfs_mounted_on_dev_fd())
358 proc_fd_dir = NULL;
359 else
360#endif
361 proc_fd_dir = opendir(FD_DIR);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800362 if (!proc_fd_dir) {
363 /* No way to get a list of open fds. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700364 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800365 } else {
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800366 struct dirent *dir_entry;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800367#ifdef HAVE_DIRFD
Gregory P. Smithe9b7cab2012-01-21 15:19:11 -0800368 int fd_used_by_opendir = dirfd(proc_fd_dir);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800369#else
370 int fd_used_by_opendir = start_fd - 1;
371#endif
372 errno = 0;
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800373 while ((dir_entry = readdir(proc_fd_dir))) {
Gregory P. Smith8facece2012-01-21 14:01:08 -0800374 int fd;
375 if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
376 continue; /* Not a number. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700377 if (fd != fd_used_by_opendir && fd >= start_fd &&
Gregory P. Smith8facece2012-01-21 14:01:08 -0800378 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200379 close(fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800380 }
381 errno = 0;
382 }
383 if (errno) {
384 /* readdir error, revert behavior. Highly Unlikely. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700385 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800386 }
387 closedir(proc_fd_dir);
388 }
389}
390
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700391#define _close_open_fds _close_open_fds_maybe_unsafe
Gregory P. Smith8facece2012-01-21 14:01:08 -0800392
393#endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
394
395
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000396/*
397 * This function is code executed in the child process immediately after fork
398 * to set things up and call exec().
399 *
400 * All of the code in this function must only use async-signal-safe functions,
401 * listed at `man 7 signal` or
402 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
403 *
404 * This restriction is documented at
405 * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
406 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500407static void
408child_exec(char *const exec_array[],
409 char *const argv[],
410 char *const envp[],
411 const char *cwd,
412 int p2cread, int p2cwrite,
413 int c2pread, int c2pwrite,
414 int errread, int errwrite,
415 int errpipe_read, int errpipe_write,
416 int close_fds, int restore_signals,
417 int call_setsid,
418 PyObject *py_fds_to_keep,
419 PyObject *preexec_fn,
420 PyObject *preexec_fn_args_tuple)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000421{
Victor Stinner185fd332015-04-01 18:35:53 +0200422 int i, saved_errno, reached_preexec = 0;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000423 PyObject *result;
Gregory P. Smith14affb82010-12-22 05:22:17 +0000424 const char* err_msg = "";
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000425 /* Buffer large enough to hold a hex integer. We can't malloc. */
426 char hex_errno[sizeof(saved_errno)*2+1];
427
Victor Stinnerdaf45552013-08-28 00:53:59 +0200428 if (make_inheritable(py_fds_to_keep, errpipe_write) < 0)
429 goto error;
430
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000431 /* Close parent's pipe ends. */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200432 if (p2cwrite != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000433 POSIX_CALL(close(p2cwrite));
Victor Stinnerdaf45552013-08-28 00:53:59 +0200434 if (c2pread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000435 POSIX_CALL(close(c2pread));
Victor Stinnerdaf45552013-08-28 00:53:59 +0200436 if (errread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000437 POSIX_CALL(close(errread));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000438 POSIX_CALL(close(errpipe_read));
439
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200440 /* When duping fds, if there arises a situation where one of the fds is
441 either 0, 1 or 2, it is possible that it is overwritten (#12607). */
Gregory P. Smithce344102018-09-10 17:46:22 -0700442 if (c2pwrite == 0) {
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200443 POSIX_CALL(c2pwrite = dup(c2pwrite));
Gregory P. Smithce344102018-09-10 17:46:22 -0700444 /* issue32270 */
445 if (_Py_set_inheritable_async_safe(c2pwrite, 0, NULL) < 0) {
446 goto error;
447 }
448 }
449 while (errwrite == 0 || errwrite == 1) {
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200450 POSIX_CALL(errwrite = dup(errwrite));
Gregory P. Smithce344102018-09-10 17:46:22 -0700451 /* issue32270 */
452 if (_Py_set_inheritable_async_safe(errwrite, 0, NULL) < 0) {
453 goto error;
454 }
455 }
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200456
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000457 /* Dup fds for child.
458 dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
459 would be a no-op (issue #10806). */
460 if (p2cread == 0) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300461 if (_Py_set_inheritable_async_safe(p2cread, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200462 goto error;
463 }
464 else if (p2cread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000465 POSIX_CALL(dup2(p2cread, 0)); /* stdin */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200466
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000467 if (c2pwrite == 1) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300468 if (_Py_set_inheritable_async_safe(c2pwrite, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200469 goto error;
470 }
471 else if (c2pwrite != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000472 POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200473
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000474 if (errwrite == 2) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300475 if (_Py_set_inheritable_async_safe(errwrite, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200476 goto error;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000477 }
Victor Stinnerdaf45552013-08-28 00:53:59 +0200478 else if (errwrite != -1)
479 POSIX_CALL(dup2(errwrite, 2)); /* stderr */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000480
Gregory P. Smithce344102018-09-10 17:46:22 -0700481 /* We no longer manually close p2cread, c2pwrite, and errwrite here as
482 * _close_open_fds takes care when it is not already non-inheritable. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000483
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000484 if (cwd)
485 POSIX_CALL(chdir(cwd));
486
487 if (restore_signals)
488 _Py_RestoreSignals();
489
490#ifdef HAVE_SETSID
491 if (call_setsid)
492 POSIX_CALL(setsid());
493#endif
494
Gregory P. Smith5591b022012-10-10 03:34:47 -0700495 reached_preexec = 1;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000496 if (preexec_fn != Py_None && preexec_fn_args_tuple) {
497 /* This is where the user has asked us to deadlock their program. */
498 result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
499 if (result == NULL) {
500 /* Stringifying the exception or traceback would involve
501 * memory allocation and thus potential for deadlock.
502 * We've already faced potential deadlock by calling back
503 * into Python in the first place, so it probably doesn't
504 * matter but we avoid it to minimize the possibility. */
505 err_msg = "Exception occurred in preexec_fn.";
506 errno = 0; /* We don't want to report an OSError. */
507 goto error;
508 }
509 /* Py_DECREF(result); - We're about to exec so why bother? */
510 }
511
Charles-François Natali249cdc32013-08-25 18:24:45 +0200512 /* close FDs after executing preexec_fn, which might open FDs */
513 if (close_fds) {
Charles-François Natali249cdc32013-08-25 18:24:45 +0200514 /* TODO HP-UX could use pstat_getproc() if anyone cares about it. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700515 _close_open_fds(3, py_fds_to_keep);
Charles-François Natali249cdc32013-08-25 18:24:45 +0200516 }
517
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000518 /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
519 /* given the executable_list generated by Lib/subprocess.py. */
520 saved_errno = 0;
521 for (i = 0; exec_array[i] != NULL; ++i) {
522 const char *executable = exec_array[i];
523 if (envp) {
524 execve(executable, argv, envp);
525 } else {
526 execv(executable, argv);
527 }
528 if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
529 saved_errno = errno;
530 }
531 }
532 /* Report the first exec error, not the last. */
533 if (saved_errno)
534 errno = saved_errno;
535
536error:
537 saved_errno = errno;
538 /* Report the posix error to our parent process. */
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800539 /* We ignore all write() return values as the total size of our writes is
Victor Stinner185fd332015-04-01 18:35:53 +0200540 less than PIPEBUF and we cannot do anything about an error anyways.
541 Use _Py_write_noraise() to retry write() if it is interrupted by a
542 signal (fails with EINTR). */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000543 if (saved_errno) {
544 char *cur;
Victor Stinner185fd332015-04-01 18:35:53 +0200545 _Py_write_noraise(errpipe_write, "OSError:", 8);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000546 cur = hex_errno + sizeof(hex_errno);
Serhiy Storchaka5ae4f492016-09-27 22:03:51 +0300547 while (saved_errno != 0 && cur != hex_errno) {
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000548 *--cur = Py_hexdigits[saved_errno % 16];
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000549 saved_errno /= 16;
550 }
Victor Stinner185fd332015-04-01 18:35:53 +0200551 _Py_write_noraise(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
552 _Py_write_noraise(errpipe_write, ":", 1);
Gregory P. Smith5591b022012-10-10 03:34:47 -0700553 if (!reached_preexec) {
554 /* Indicate to the parent that the error happened before exec(). */
Victor Stinner185fd332015-04-01 18:35:53 +0200555 _Py_write_noraise(errpipe_write, "noexec", 6);
Gregory P. Smith5591b022012-10-10 03:34:47 -0700556 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000557 /* We can't call strerror(saved_errno). It is not async signal safe.
558 * The parent process will look the error message up. */
559 } else {
Victor Stinner185fd332015-04-01 18:35:53 +0200560 _Py_write_noraise(errpipe_write, "SubprocessError:0:", 18);
561 _Py_write_noraise(errpipe_write, err_msg, strlen(err_msg));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000562 }
563}
564
565
566static PyObject *
567subprocess_fork_exec(PyObject* self, PyObject *args)
568{
569 PyObject *gc_module = NULL;
Antoine Pitrou721738f2012-08-15 23:20:39 +0200570 PyObject *executable_list, *py_fds_to_keep;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000571 PyObject *env_list, *preexec_fn;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000572 PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000573 PyObject *preexec_fn_args_tuple = NULL;
574 int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
575 int errpipe_read, errpipe_write, close_fds, restore_signals;
576 int call_setsid;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000577 PyObject *cwd_obj, *cwd_obj2;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000578 const char *cwd;
579 pid_t pid;
580 int need_to_reenable_gc = 0;
581 char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800582 Py_ssize_t arg_num;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200583 int need_after_fork = 0;
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700584 int saved_errno = 0;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000585
586 if (!PyArg_ParseTuple(
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300587 args, "OOpO!OOiiiiiiiiiiO:fork_exec",
588 &process_args, &executable_list,
589 &close_fds, &PyTuple_Type, &py_fds_to_keep,
Victor Stinner0e59cc32010-04-16 23:49:32 +0000590 &cwd_obj, &env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000591 &p2cread, &p2cwrite, &c2pread, &c2pwrite,
592 &errread, &errwrite, &errpipe_read, &errpipe_write,
593 &restore_signals, &call_setsid, &preexec_fn))
594 return NULL;
595
Christian Heimes98d90f72019-08-27 23:36:56 +0200596 if ((preexec_fn != Py_None) &&
597 (_PyInterpreterState_Get() != PyInterpreterState_Main())) {
598 PyErr_SetString(PyExc_RuntimeError,
599 "preexec_fn not supported within subinterpreters");
Eric Snow59032962018-09-14 14:17:20 -0700600 return NULL;
601 }
602
Gregory P. Smith361e30c2013-12-01 00:12:24 -0800603 if (close_fds && errpipe_write < 3) { /* precondition */
604 PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
605 return NULL;
606 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800607 if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
608 PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000609 return NULL;
610 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000611
612 /* We need to call gc.disable() when we'll be calling preexec_fn */
613 if (preexec_fn != Py_None) {
614 PyObject *result;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200615
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000616 gc_module = PyImport_ImportModule("gc");
617 if (gc_module == NULL)
618 return NULL;
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100619 result = _PyObject_CallMethodNoArgs(
620 gc_module, _posixsubprocessstate_global->isenabled);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000621 if (result == NULL) {
622 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000623 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000624 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000625 need_to_reenable_gc = PyObject_IsTrue(result);
626 Py_DECREF(result);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000627 if (need_to_reenable_gc == -1) {
628 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000629 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000630 }
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100631 result = _PyObject_CallMethodNoArgs(
632 gc_module, _posixsubprocessstate_global->disable);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000633 if (result == NULL) {
634 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000635 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000636 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000637 Py_DECREF(result);
638 }
639
640 exec_array = _PySequence_BytesToCharpArray(executable_list);
Victor Stinner8f437aa2014-10-05 17:25:19 +0200641 if (!exec_array)
642 goto cleanup;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000643
644 /* Convert args and env into appropriate arguments for exec() */
645 /* These conversions are done in the parent process to avoid allocating
646 or freeing memory in the child process. */
647 if (process_args != Py_None) {
Gregory P. Smith68f52172010-03-15 06:07:42 +0000648 Py_ssize_t num_args;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000649 /* Equivalent to: */
650 /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
Gregory P. Smith68f52172010-03-15 06:07:42 +0000651 fast_args = PySequence_Fast(process_args, "argv must be a tuple");
Stefan Krahdb579d72012-08-20 14:36:47 +0200652 if (fast_args == NULL)
653 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000654 num_args = PySequence_Fast_GET_SIZE(fast_args);
655 converted_args = PyTuple_New(num_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000656 if (converted_args == NULL)
657 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000658 for (arg_num = 0; arg_num < num_args; ++arg_num) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000659 PyObject *borrowed_arg, *converted_arg;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300660 if (PySequence_Fast_GET_SIZE(fast_args) != num_args) {
661 PyErr_SetString(PyExc_RuntimeError, "args changed during iteration");
662 goto cleanup;
663 }
Gregory P. Smith68f52172010-03-15 06:07:42 +0000664 borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000665 if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
666 goto cleanup;
667 PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
668 }
669
670 argv = _PySequence_BytesToCharpArray(converted_args);
671 Py_CLEAR(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000672 Py_CLEAR(fast_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000673 if (!argv)
674 goto cleanup;
675 }
676
677 if (env_list != Py_None) {
678 envp = _PySequence_BytesToCharpArray(env_list);
679 if (!envp)
680 goto cleanup;
681 }
682
Victor Stinner0e59cc32010-04-16 23:49:32 +0000683 if (cwd_obj != Py_None) {
684 if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
685 goto cleanup;
Victor Stinnerdcb24032010-04-22 12:08:36 +0000686 cwd = PyBytes_AsString(cwd_obj2);
Victor Stinner0e59cc32010-04-16 23:49:32 +0000687 } else {
688 cwd = NULL;
689 cwd_obj2 = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000690 }
691
Gregory P. Smith163468a2017-05-29 10:03:41 -0700692 /* This must be the last thing done before fork() because we do not
693 * want to call PyOS_BeforeFork() if there is any chance of another
694 * error leading to the cleanup: code without calling fork(). */
695 if (preexec_fn != Py_None) {
696 preexec_fn_args_tuple = PyTuple_New(0);
697 if (!preexec_fn_args_tuple)
698 goto cleanup;
699 PyOS_BeforeFork();
700 need_after_fork = 1;
701 }
702
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000703 pid = fork();
704 if (pid == 0) {
705 /* Child process */
Victor Stinner0e59cc32010-04-16 23:49:32 +0000706 /*
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000707 * Code from here to _exit() must only use async-signal-safe functions,
708 * listed at `man 7 signal` or
709 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
710 */
711
712 if (preexec_fn != Py_None) {
713 /* We'll be calling back into Python later so we need to do this.
714 * This call may not be async-signal-safe but neither is calling
715 * back into Python. The user asked us to use hope as a strategy
716 * to avoid deadlock... */
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200717 PyOS_AfterFork_Child();
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000718 }
719
720 child_exec(exec_array, argv, envp, cwd,
721 p2cread, p2cwrite, c2pread, c2pwrite,
722 errread, errwrite, errpipe_read, errpipe_write,
723 close_fds, restore_signals, call_setsid,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800724 py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000725 _exit(255);
726 return NULL; /* Dead code to avoid a potential compiler warning. */
727 }
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700728 /* Parent (original) process */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000729 if (pid == -1) {
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700730 /* Capture errno for the exception. */
731 saved_errno = errno;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000732 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000733
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700734 Py_XDECREF(cwd_obj2);
735
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200736 if (need_after_fork)
737 PyOS_AfterFork_Parent();
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000738 if (envp)
739 _Py_FreeCharPArray(envp);
740 if (argv)
741 _Py_FreeCharPArray(argv);
742 _Py_FreeCharPArray(exec_array);
743
744 /* Reenable gc in the parent process (or if fork failed). */
Martin Panterafdd5132015-11-30 02:21:41 +0000745 if (_enable_gc(need_to_reenable_gc, gc_module)) {
746 pid = -1;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000747 }
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000748 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000749 Py_XDECREF(gc_module);
750
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700751 if (pid == -1) {
752 errno = saved_errno;
753 /* We can't call this above as PyOS_AfterFork_Parent() calls back
754 * into Python code which would see the unreturned error. */
755 PyErr_SetFromErrno(PyExc_OSError);
756 return NULL; /* fork() failed. */
757 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000758
759 return PyLong_FromPid(pid);
760
761cleanup:
762 if (envp)
763 _Py_FreeCharPArray(envp);
764 if (argv)
765 _Py_FreeCharPArray(argv);
Victor Stinner8f437aa2014-10-05 17:25:19 +0200766 if (exec_array)
767 _Py_FreeCharPArray(exec_array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000768 Py_XDECREF(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000769 Py_XDECREF(fast_args);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000770 Py_XDECREF(preexec_fn_args_tuple);
Martin Panterafdd5132015-11-30 02:21:41 +0000771 _enable_gc(need_to_reenable_gc, gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000772 Py_XDECREF(gc_module);
773 return NULL;
774}
775
776
777PyDoc_STRVAR(subprocess_fork_exec_doc,
778"fork_exec(args, executable_list, close_fds, cwd, env,\n\
779 p2cread, p2cwrite, c2pread, c2pwrite,\n\
780 errread, errwrite, errpipe_read, errpipe_write,\n\
781 restore_signals, call_setsid, preexec_fn)\n\
782\n\
783Forks a child process, closes parent file descriptors as appropriate in the\n\
784child and dups the few that are needed before calling exec() in the child\n\
785process.\n\
786\n\
787The preexec_fn, if supplied, will be called immediately before exec.\n\
788WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
789 It may trigger infrequent, difficult to debug deadlocks.\n\
790\n\
791If an error occurs in the child process before the exec, it is\n\
792serialized and written to the errpipe_write fd per subprocess.py.\n\
793\n\
794Returns: the child process's PID.\n\
795\n\
796Raises: Only on an error in the parent process.\n\
797");
798
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000799/* module level code ********************************************************/
800
801PyDoc_STRVAR(module_doc,
802"A POSIX helper for the subprocess module.");
803
804
805static PyMethodDef module_methods[] = {
806 {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000807 {NULL, NULL} /* sentinel */
808};
809
810
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100811static int _posixsubprocess_traverse(PyObject *m, visitproc visit, void *arg) {
812 Py_VISIT(_posixsubprocessstate(m)->disable);
813 Py_VISIT(_posixsubprocessstate(m)->enable);
814 Py_VISIT(_posixsubprocessstate(m)->isenabled);
815 return 0;
816}
817
818static int _posixsubprocess_clear(PyObject *m) {
819 Py_CLEAR(_posixsubprocessstate(m)->disable);
820 Py_CLEAR(_posixsubprocessstate(m)->enable);
821 Py_CLEAR(_posixsubprocessstate(m)->isenabled);
822 return 0;
823}
824
825static void _posixsubprocess_free(void *m) {
826 _posixsubprocess_clear((PyObject *)m);
827}
828
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000829static struct PyModuleDef _posixsubprocessmodule = {
luzpaza5293b42017-11-05 07:37:50 -0600830 PyModuleDef_HEAD_INIT,
831 "_posixsubprocess",
832 module_doc,
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100833 sizeof(_posixsubprocessstate),
luzpaza5293b42017-11-05 07:37:50 -0600834 module_methods,
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100835 NULL,
836 _posixsubprocess_traverse,
837 _posixsubprocess_clear,
838 _posixsubprocess_free,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000839};
840
841PyMODINIT_FUNC
842PyInit__posixsubprocess(void)
843{
Dino Viehland5a7d2e12019-09-10 12:01:20 +0100844 PyObject* m;
845
846 m = PyState_FindModule(&_posixsubprocessmodule);
847 if (m != NULL) {
848 Py_INCREF(m);
849 return m;
850 }
851
852 m = PyModule_Create(&_posixsubprocessmodule);
853 if (m == NULL) {
854 return NULL;
855 }
856
857 _posixsubprocessstate(m)->disable = PyUnicode_InternFromString("disable");
858 _posixsubprocessstate(m)->enable = PyUnicode_InternFromString("enable");
859 _posixsubprocessstate(m)->isenabled = PyUnicode_InternFromString("isenabled");
860
861 PyState_AddModule(m, &_posixsubprocessmodule);
862 return m;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000863}