blob: 81a23c6d330037859b19dc2080a279a073fb0897 [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
52
Martin Panterafdd5132015-11-30 02:21:41 +000053/* If gc was disabled, call gc.enable(). Return 0 on success. */
Benjamin Peterson91eef982012-01-22 20:04:46 -050054static int
Martin Panterafdd5132015-11-30 02:21:41 +000055_enable_gc(int need_to_reenable_gc, PyObject *gc_module)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000056{
57 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020058 _Py_IDENTIFIER(enable);
Martin Panterafdd5132015-11-30 02:21:41 +000059 PyObject *exctype, *val, *tb;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020060
Martin Panterafdd5132015-11-30 02:21:41 +000061 if (need_to_reenable_gc) {
62 PyErr_Fetch(&exctype, &val, &tb);
63 result = _PyObject_CallMethodId(gc_module, &PyId_enable, NULL);
64 if (exctype != NULL) {
65 PyErr_Restore(exctype, val, tb);
66 }
67 if (result == NULL) {
68 return 1;
69 }
70 Py_DECREF(result);
71 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000072 return 0;
73}
74
75
Gregory P. Smith8facece2012-01-21 14:01:08 -080076/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
Benjamin Peterson91eef982012-01-22 20:04:46 -050077static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020078_pos_int_from_ascii(const char *name)
Gregory P. Smith8facece2012-01-21 14:01:08 -080079{
80 int num = 0;
81 while (*name >= '0' && *name <= '9') {
82 num = num * 10 + (*name - '0');
83 ++name;
84 }
85 if (*name)
86 return -1; /* Non digit found, not a number. */
87 return num;
88}
89
90
Gregory P. Smith4842efc2012-01-21 21:01:24 -080091#if defined(__FreeBSD__)
92/* When /dev/fd isn't mounted it is often a static directory populated
93 * with 0 1 2 or entries for 0 .. 63 on FreeBSD, NetBSD and OpenBSD.
94 * NetBSD and OpenBSD have a /proc fs available (though not necessarily
95 * mounted) and do not have fdescfs for /dev/fd. MacOS X has a devfs
96 * that properly supports /dev/fd.
97 */
Benjamin Peterson91eef982012-01-22 20:04:46 -050098static int
Ross Lagerwall7f4fdb22012-03-07 20:06:33 +020099_is_fdescfs_mounted_on_dev_fd(void)
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800100{
101 struct stat dev_stat;
102 struct stat dev_fd_stat;
103 if (stat("/dev", &dev_stat) != 0)
104 return 0;
105 if (stat(FD_DIR, &dev_fd_stat) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200106 return 0;
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800107 if (dev_stat.st_dev == dev_fd_stat.st_dev)
108 return 0; /* / == /dev == /dev/fd means it is static. #fail */
109 return 1;
110}
111#endif
112
113
Gregory P. Smith8facece2012-01-21 14:01:08 -0800114/* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500115static int
116_sanity_check_python_fd_sequence(PyObject *fd_sequence)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800117{
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300118 Py_ssize_t seq_idx;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800119 long prev_fd = -1;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300120 for (seq_idx = 0; seq_idx < PyTuple_GET_SIZE(fd_sequence); ++seq_idx) {
121 PyObject* py_fd = PyTuple_GET_ITEM(fd_sequence, seq_idx);
122 long iter_fd;
123 if (!PyLong_Check(py_fd)) {
124 return 1;
125 }
126 iter_fd = PyLong_AsLong(py_fd);
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -0800127 if (iter_fd < 0 || iter_fd <= prev_fd || iter_fd > INT_MAX) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300128 /* Negative, overflow, unsorted, too big for a fd. */
Gregory P. Smith8facece2012-01-21 14:01:08 -0800129 return 1;
130 }
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -0800131 prev_fd = iter_fd;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800132 }
133 return 0;
134}
135
136
137/* Is fd found in the sorted Python Sequence? */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500138static int
139_is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800140{
141 /* Binary search. */
142 Py_ssize_t search_min = 0;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300143 Py_ssize_t search_max = PyTuple_GET_SIZE(fd_sequence) - 1;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800144 if (search_max < 0)
145 return 0;
146 do {
147 long middle = (search_min + search_max) / 2;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300148 long middle_fd = PyLong_AsLong(PyTuple_GET_ITEM(fd_sequence, middle));
Gregory P. Smith8facece2012-01-21 14:01:08 -0800149 if (fd == middle_fd)
150 return 1;
151 if (fd > middle_fd)
152 search_min = middle + 1;
153 else
154 search_max = middle - 1;
155 } while (search_min <= search_max);
156 return 0;
157}
158
Victor Stinnerdaf45552013-08-28 00:53:59 +0200159static int
160make_inheritable(PyObject *py_fds_to_keep, int errpipe_write)
161{
162 Py_ssize_t i, len;
163
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300164 len = PyTuple_GET_SIZE(py_fds_to_keep);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200165 for (i = 0; i < len; ++i) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300166 PyObject* fdobj = PyTuple_GET_ITEM(py_fds_to_keep, i);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200167 long fd = PyLong_AsLong(fdobj);
168 assert(!PyErr_Occurred());
169 assert(0 <= fd && fd <= INT_MAX);
170 if (fd == errpipe_write) {
171 /* errpipe_write is part of py_fds_to_keep. It must be closed at
172 exec(), but kept open in the child process until exec() is
173 called. */
174 continue;
175 }
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300176 if (_Py_set_inheritable_async_safe((int)fd, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200177 return -1;
178 }
179 return 0;
180}
181
Gregory P. Smith8facece2012-01-21 14:01:08 -0800182
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700183/* Get the maximum file descriptor that could be opened by this process.
184 * This function is async signal safe for use between fork() and exec().
185 */
186static long
187safe_get_max_fd(void)
188{
189 long local_max_fd;
190#if defined(__NetBSD__)
191 local_max_fd = fcntl(0, F_MAXFD);
192 if (local_max_fd >= 0)
193 return local_max_fd;
194#endif
Gregory P. Smithf9681772015-04-25 23:43:34 -0700195#if defined(HAVE_SYS_RESOURCE_H) && defined(__OpenBSD__)
196 struct rlimit rl;
197 /* Not on the POSIX async signal safe functions list but likely
198 * safe. TODO - Someone should audit OpenBSD to make sure. */
199 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
200 return (long) rl.rlim_max;
201#endif
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700202#ifdef _SC_OPEN_MAX
203 local_max_fd = sysconf(_SC_OPEN_MAX);
204 if (local_max_fd == -1)
205#endif
206 local_max_fd = 256; /* Matches legacy Lib/subprocess.py behavior. */
207 return local_max_fd;
208}
209
210
211/* Close all file descriptors in the range from start_fd and higher
212 * except for those in py_fds_to_keep. If the range defined by
213 * [start_fd, safe_get_max_fd()) is large this will take a long
214 * time as it calls close() on EVERY possible fd.
215 *
216 * It isn't possible to know for sure what the max fd to go up to
217 * is for processes with the capability of raising their maximum.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800218 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500219static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700220_close_fds_by_brute_force(long start_fd, PyObject *py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800221{
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700222 long end_fd = safe_get_max_fd();
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300223 Py_ssize_t num_fds_to_keep = PyTuple_GET_SIZE(py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800224 Py_ssize_t keep_seq_idx;
225 int fd_num;
226 /* As py_fds_to_keep is sorted we can loop through the list closing
luzpaza5293b42017-11-05 07:37:50 -0600227 * fds in between any in the keep list falling within our range. */
Gregory P. Smith8facece2012-01-21 14:01:08 -0800228 for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300229 PyObject* py_keep_fd = PyTuple_GET_ITEM(py_fds_to_keep, keep_seq_idx);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800230 int keep_fd = PyLong_AsLong(py_keep_fd);
231 if (keep_fd < start_fd)
232 continue;
233 for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200234 close(fd_num);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800235 }
236 start_fd = keep_fd + 1;
237 }
238 if (start_fd <= end_fd) {
239 for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200240 close(fd_num);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800241 }
242 }
243}
244
245
246#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
247/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
248 * only to read a directory of short file descriptor number names. The kernel
249 * will return an error if we didn't give it enough space. Highly Unlikely.
250 * This structure is very old and stable: It will not change unless the kernel
251 * chooses to break compatibility with all existing binaries. Highly Unlikely.
252 */
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800253struct linux_dirent64 {
Gregory P. Smith58f07a92012-06-05 13:26:39 -0700254 unsigned long long d_ino;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800255 long long d_off;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800256 unsigned short d_reclen; /* Length of this linux_dirent */
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800257 unsigned char d_type;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800258 char d_name[256]; /* Filename (null-terminated) */
259};
260
Gregory P. Smitha26987a2014-06-01 13:46:36 -0700261/* Close all open file descriptors in the range from start_fd and higher
262 * Do not close any in the sorted py_fds_to_keep list.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800263 *
264 * This version is async signal safe as it does not make any unsafe C library
265 * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
266 * to resort to making a kernel system call directly but this is the ONLY api
267 * available that does no harm. opendir/readdir/closedir perform memory
268 * allocation and locking so while they usually work they are not guaranteed
269 * to (especially if you have replaced your malloc implementation). A version
270 * of this function that uses those can be found in the _maybe_unsafe variant.
271 *
272 * This is Linux specific because that is all I am ready to test it on. It
273 * should be easy to add OS specific dirent or dirent64 structures and modify
274 * it with some cpp #define magic to work on other OSes as well if you want.
275 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500276static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700277_close_open_fds_safe(int start_fd, PyObject* py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800278{
279 int fd_dir_fd;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200280
Victor Stinner160e8192015-03-30 02:18:31 +0200281 fd_dir_fd = _Py_open_noraise(FD_DIR, O_RDONLY);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800282 if (fd_dir_fd == -1) {
283 /* No way to get a list of open fds. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700284 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800285 return;
286 } else {
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800287 char buffer[sizeof(struct linux_dirent64)];
Gregory P. Smith8facece2012-01-21 14:01:08 -0800288 int bytes;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800289 while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
290 (struct linux_dirent64 *)buffer,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800291 sizeof(buffer))) > 0) {
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800292 struct linux_dirent64 *entry;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800293 int offset;
Gregory P. Smith3015fb82018-11-12 22:01:22 -0800294#ifdef _Py_MEMORY_SANITIZER
Gregory P. Smith1584a002018-11-12 12:07:14 -0800295 __msan_unpoison(buffer, bytes);
296#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -0800297 for (offset = 0; offset < bytes; offset += entry->d_reclen) {
298 int fd;
Gregory P. Smith255bf5b2013-03-03 10:45:05 -0800299 entry = (struct linux_dirent64 *)(buffer + offset);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800300 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
301 continue; /* Not a number. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700302 if (fd != fd_dir_fd && fd >= start_fd &&
Gregory P. Smith8facece2012-01-21 14:01:08 -0800303 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200304 close(fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800305 }
306 }
307 }
Victor Stinnere7c74922015-04-02 16:24:46 +0200308 close(fd_dir_fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800309 }
310}
311
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700312#define _close_open_fds _close_open_fds_safe
Gregory P. Smith8facece2012-01-21 14:01:08 -0800313
314#else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
315
316
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700317/* Close all open file descriptors from start_fd and higher.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300318 * Do not close any in the sorted py_fds_to_keep tuple.
Gregory P. Smith8facece2012-01-21 14:01:08 -0800319 *
320 * This function violates the strict use of async signal safe functions. :(
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800321 * It calls opendir(), readdir() and closedir(). Of these, the one most
Gregory P. Smith8facece2012-01-21 14:01:08 -0800322 * likely to ever cause a problem is opendir() as it performs an internal
323 * malloc(). Practically this should not be a problem. The Java VM makes the
324 * same calls between fork and exec in its own UNIXProcess_md.c implementation.
325 *
326 * readdir_r() is not used because it provides no benefit. It is typically
327 * implemented as readdir() followed by memcpy(). See also:
328 * http://womble.decadent.org.uk/readdir_r-advisory.html
329 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500330static void
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700331_close_open_fds_maybe_unsafe(long start_fd, PyObject* py_fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -0800332{
333 DIR *proc_fd_dir;
334#ifndef HAVE_DIRFD
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700335 while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep)) {
Gregory P. Smith8facece2012-01-21 14:01:08 -0800336 ++start_fd;
337 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800338 /* Close our lowest fd before we call opendir so that it is likely to
339 * reuse that fd otherwise we might close opendir's file descriptor in
340 * our loop. This trick assumes that fd's are allocated on a lowest
341 * available basis. */
Victor Stinnere7c74922015-04-02 16:24:46 +0200342 close(start_fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800343 ++start_fd;
344#endif
Gregory P. Smith8facece2012-01-21 14:01:08 -0800345
Gregory P. Smith4842efc2012-01-21 21:01:24 -0800346#if defined(__FreeBSD__)
347 if (!_is_fdescfs_mounted_on_dev_fd())
348 proc_fd_dir = NULL;
349 else
350#endif
351 proc_fd_dir = opendir(FD_DIR);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800352 if (!proc_fd_dir) {
353 /* No way to get a list of open fds. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700354 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800355 } else {
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800356 struct dirent *dir_entry;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800357#ifdef HAVE_DIRFD
Gregory P. Smithe9b7cab2012-01-21 15:19:11 -0800358 int fd_used_by_opendir = dirfd(proc_fd_dir);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800359#else
360 int fd_used_by_opendir = start_fd - 1;
361#endif
362 errno = 0;
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800363 while ((dir_entry = readdir(proc_fd_dir))) {
Gregory P. Smith8facece2012-01-21 14:01:08 -0800364 int fd;
365 if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
366 continue; /* Not a number. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700367 if (fd != fd_used_by_opendir && fd >= start_fd &&
Gregory P. Smith8facece2012-01-21 14:01:08 -0800368 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
Victor Stinnere7c74922015-04-02 16:24:46 +0200369 close(fd);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800370 }
371 errno = 0;
372 }
373 if (errno) {
374 /* readdir error, revert behavior. Highly Unlikely. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700375 _close_fds_by_brute_force(start_fd, py_fds_to_keep);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800376 }
377 closedir(proc_fd_dir);
378 }
379}
380
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700381#define _close_open_fds _close_open_fds_maybe_unsafe
Gregory P. Smith8facece2012-01-21 14:01:08 -0800382
383#endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
384
385
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000386/*
387 * This function is code executed in the child process immediately after fork
388 * to set things up and call exec().
389 *
390 * All of the code in this function must only use async-signal-safe functions,
391 * listed at `man 7 signal` or
392 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
393 *
394 * This restriction is documented at
395 * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
396 */
Benjamin Peterson91eef982012-01-22 20:04:46 -0500397static void
398child_exec(char *const exec_array[],
399 char *const argv[],
400 char *const envp[],
401 const char *cwd,
402 int p2cread, int p2cwrite,
403 int c2pread, int c2pwrite,
404 int errread, int errwrite,
405 int errpipe_read, int errpipe_write,
406 int close_fds, int restore_signals,
407 int call_setsid,
408 PyObject *py_fds_to_keep,
409 PyObject *preexec_fn,
410 PyObject *preexec_fn_args_tuple)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000411{
Victor Stinner185fd332015-04-01 18:35:53 +0200412 int i, saved_errno, reached_preexec = 0;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000413 PyObject *result;
Gregory P. Smith14affb82010-12-22 05:22:17 +0000414 const char* err_msg = "";
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000415 /* Buffer large enough to hold a hex integer. We can't malloc. */
416 char hex_errno[sizeof(saved_errno)*2+1];
417
Victor Stinnerdaf45552013-08-28 00:53:59 +0200418 if (make_inheritable(py_fds_to_keep, errpipe_write) < 0)
419 goto error;
420
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000421 /* Close parent's pipe ends. */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200422 if (p2cwrite != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000423 POSIX_CALL(close(p2cwrite));
Victor Stinnerdaf45552013-08-28 00:53:59 +0200424 if (c2pread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000425 POSIX_CALL(close(c2pread));
Victor Stinnerdaf45552013-08-28 00:53:59 +0200426 if (errread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000427 POSIX_CALL(close(errread));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000428 POSIX_CALL(close(errpipe_read));
429
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200430 /* When duping fds, if there arises a situation where one of the fds is
431 either 0, 1 or 2, it is possible that it is overwritten (#12607). */
Gregory P. Smithce344102018-09-10 17:46:22 -0700432 if (c2pwrite == 0) {
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200433 POSIX_CALL(c2pwrite = dup(c2pwrite));
Gregory P. Smithce344102018-09-10 17:46:22 -0700434 /* issue32270 */
435 if (_Py_set_inheritable_async_safe(c2pwrite, 0, NULL) < 0) {
436 goto error;
437 }
438 }
439 while (errwrite == 0 || errwrite == 1) {
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200440 POSIX_CALL(errwrite = dup(errwrite));
Gregory P. Smithce344102018-09-10 17:46:22 -0700441 /* issue32270 */
442 if (_Py_set_inheritable_async_safe(errwrite, 0, NULL) < 0) {
443 goto error;
444 }
445 }
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200446
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000447 /* Dup fds for child.
448 dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
449 would be a no-op (issue #10806). */
450 if (p2cread == 0) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300451 if (_Py_set_inheritable_async_safe(p2cread, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200452 goto error;
453 }
454 else if (p2cread != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000455 POSIX_CALL(dup2(p2cread, 0)); /* stdin */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200456
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000457 if (c2pwrite == 1) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300458 if (_Py_set_inheritable_async_safe(c2pwrite, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200459 goto error;
460 }
461 else if (c2pwrite != -1)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000462 POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200463
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000464 if (errwrite == 2) {
Alexey Izbyshevc1e46e92018-02-06 09:09:34 +0300465 if (_Py_set_inheritable_async_safe(errwrite, 1, NULL) < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200466 goto error;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000467 }
Victor Stinnerdaf45552013-08-28 00:53:59 +0200468 else if (errwrite != -1)
469 POSIX_CALL(dup2(errwrite, 2)); /* stderr */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000470
Gregory P. Smithce344102018-09-10 17:46:22 -0700471 /* We no longer manually close p2cread, c2pwrite, and errwrite here as
472 * _close_open_fds takes care when it is not already non-inheritable. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000473
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000474 if (cwd)
475 POSIX_CALL(chdir(cwd));
476
477 if (restore_signals)
478 _Py_RestoreSignals();
479
480#ifdef HAVE_SETSID
481 if (call_setsid)
482 POSIX_CALL(setsid());
483#endif
484
Gregory P. Smith5591b022012-10-10 03:34:47 -0700485 reached_preexec = 1;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000486 if (preexec_fn != Py_None && preexec_fn_args_tuple) {
487 /* This is where the user has asked us to deadlock their program. */
488 result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
489 if (result == NULL) {
490 /* Stringifying the exception or traceback would involve
491 * memory allocation and thus potential for deadlock.
492 * We've already faced potential deadlock by calling back
493 * into Python in the first place, so it probably doesn't
494 * matter but we avoid it to minimize the possibility. */
495 err_msg = "Exception occurred in preexec_fn.";
496 errno = 0; /* We don't want to report an OSError. */
497 goto error;
498 }
499 /* Py_DECREF(result); - We're about to exec so why bother? */
500 }
501
Charles-François Natali249cdc32013-08-25 18:24:45 +0200502 /* close FDs after executing preexec_fn, which might open FDs */
503 if (close_fds) {
Charles-François Natali249cdc32013-08-25 18:24:45 +0200504 /* TODO HP-UX could use pstat_getproc() if anyone cares about it. */
Gregory P. Smithd4dcb702014-06-01 13:18:28 -0700505 _close_open_fds(3, py_fds_to_keep);
Charles-François Natali249cdc32013-08-25 18:24:45 +0200506 }
507
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000508 /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
509 /* given the executable_list generated by Lib/subprocess.py. */
510 saved_errno = 0;
511 for (i = 0; exec_array[i] != NULL; ++i) {
512 const char *executable = exec_array[i];
513 if (envp) {
514 execve(executable, argv, envp);
515 } else {
516 execv(executable, argv);
517 }
518 if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
519 saved_errno = errno;
520 }
521 }
522 /* Report the first exec error, not the last. */
523 if (saved_errno)
524 errno = saved_errno;
525
526error:
527 saved_errno = errno;
528 /* Report the posix error to our parent process. */
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800529 /* We ignore all write() return values as the total size of our writes is
Victor Stinner185fd332015-04-01 18:35:53 +0200530 less than PIPEBUF and we cannot do anything about an error anyways.
531 Use _Py_write_noraise() to retry write() if it is interrupted by a
532 signal (fails with EINTR). */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000533 if (saved_errno) {
534 char *cur;
Victor Stinner185fd332015-04-01 18:35:53 +0200535 _Py_write_noraise(errpipe_write, "OSError:", 8);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000536 cur = hex_errno + sizeof(hex_errno);
Serhiy Storchaka5ae4f492016-09-27 22:03:51 +0300537 while (saved_errno != 0 && cur != hex_errno) {
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000538 *--cur = Py_hexdigits[saved_errno % 16];
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000539 saved_errno /= 16;
540 }
Victor Stinner185fd332015-04-01 18:35:53 +0200541 _Py_write_noraise(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
542 _Py_write_noraise(errpipe_write, ":", 1);
Gregory P. Smith5591b022012-10-10 03:34:47 -0700543 if (!reached_preexec) {
544 /* Indicate to the parent that the error happened before exec(). */
Victor Stinner185fd332015-04-01 18:35:53 +0200545 _Py_write_noraise(errpipe_write, "noexec", 6);
Gregory P. Smith5591b022012-10-10 03:34:47 -0700546 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000547 /* We can't call strerror(saved_errno). It is not async signal safe.
548 * The parent process will look the error message up. */
549 } else {
Victor Stinner185fd332015-04-01 18:35:53 +0200550 _Py_write_noraise(errpipe_write, "SubprocessError:0:", 18);
551 _Py_write_noraise(errpipe_write, err_msg, strlen(err_msg));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000552 }
553}
554
555
556static PyObject *
557subprocess_fork_exec(PyObject* self, PyObject *args)
558{
559 PyObject *gc_module = NULL;
Antoine Pitrou721738f2012-08-15 23:20:39 +0200560 PyObject *executable_list, *py_fds_to_keep;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000561 PyObject *env_list, *preexec_fn;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000562 PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000563 PyObject *preexec_fn_args_tuple = NULL;
564 int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
565 int errpipe_read, errpipe_write, close_fds, restore_signals;
566 int call_setsid;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000567 PyObject *cwd_obj, *cwd_obj2;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000568 const char *cwd;
569 pid_t pid;
570 int need_to_reenable_gc = 0;
571 char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800572 Py_ssize_t arg_num;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200573 int need_after_fork = 0;
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700574 int saved_errno = 0;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000575
576 if (!PyArg_ParseTuple(
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300577 args, "OOpO!OOiiiiiiiiiiO:fork_exec",
578 &process_args, &executable_list,
579 &close_fds, &PyTuple_Type, &py_fds_to_keep,
Victor Stinner0e59cc32010-04-16 23:49:32 +0000580 &cwd_obj, &env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000581 &p2cread, &p2cwrite, &c2pread, &c2pwrite,
582 &errread, &errwrite, &errpipe_read, &errpipe_write,
583 &restore_signals, &call_setsid, &preexec_fn))
584 return NULL;
585
Eric Snow59032962018-09-14 14:17:20 -0700586 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
587 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
588 return NULL;
589 }
590
Gregory P. Smith361e30c2013-12-01 00:12:24 -0800591 if (close_fds && errpipe_write < 3) { /* precondition */
592 PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
593 return NULL;
594 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800595 if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
596 PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000597 return NULL;
598 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000599
600 /* We need to call gc.disable() when we'll be calling preexec_fn */
601 if (preexec_fn != Py_None) {
602 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200603 _Py_IDENTIFIER(isenabled);
604 _Py_IDENTIFIER(disable);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200605
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000606 gc_module = PyImport_ImportModule("gc");
607 if (gc_module == NULL)
608 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200609 result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000610 if (result == NULL) {
611 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000612 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000613 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000614 need_to_reenable_gc = PyObject_IsTrue(result);
615 Py_DECREF(result);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000616 if (need_to_reenable_gc == -1) {
617 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000618 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000619 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200620 result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL);
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 Py_DECREF(result);
626 }
627
628 exec_array = _PySequence_BytesToCharpArray(executable_list);
Victor Stinner8f437aa2014-10-05 17:25:19 +0200629 if (!exec_array)
630 goto cleanup;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000631
632 /* Convert args and env into appropriate arguments for exec() */
633 /* These conversions are done in the parent process to avoid allocating
634 or freeing memory in the child process. */
635 if (process_args != Py_None) {
Gregory P. Smith68f52172010-03-15 06:07:42 +0000636 Py_ssize_t num_args;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000637 /* Equivalent to: */
638 /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
Gregory P. Smith68f52172010-03-15 06:07:42 +0000639 fast_args = PySequence_Fast(process_args, "argv must be a tuple");
Stefan Krahdb579d72012-08-20 14:36:47 +0200640 if (fast_args == NULL)
641 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000642 num_args = PySequence_Fast_GET_SIZE(fast_args);
643 converted_args = PyTuple_New(num_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000644 if (converted_args == NULL)
645 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000646 for (arg_num = 0; arg_num < num_args; ++arg_num) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000647 PyObject *borrowed_arg, *converted_arg;
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300648 if (PySequence_Fast_GET_SIZE(fast_args) != num_args) {
649 PyErr_SetString(PyExc_RuntimeError, "args changed during iteration");
650 goto cleanup;
651 }
Gregory P. Smith68f52172010-03-15 06:07:42 +0000652 borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000653 if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
654 goto cleanup;
655 PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
656 }
657
658 argv = _PySequence_BytesToCharpArray(converted_args);
659 Py_CLEAR(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000660 Py_CLEAR(fast_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000661 if (!argv)
662 goto cleanup;
663 }
664
665 if (env_list != Py_None) {
666 envp = _PySequence_BytesToCharpArray(env_list);
667 if (!envp)
668 goto cleanup;
669 }
670
Victor Stinner0e59cc32010-04-16 23:49:32 +0000671 if (cwd_obj != Py_None) {
672 if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
673 goto cleanup;
Victor Stinnerdcb24032010-04-22 12:08:36 +0000674 cwd = PyBytes_AsString(cwd_obj2);
Victor Stinner0e59cc32010-04-16 23:49:32 +0000675 } else {
676 cwd = NULL;
677 cwd_obj2 = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000678 }
679
Gregory P. Smith163468a2017-05-29 10:03:41 -0700680 /* This must be the last thing done before fork() because we do not
681 * want to call PyOS_BeforeFork() if there is any chance of another
682 * error leading to the cleanup: code without calling fork(). */
683 if (preexec_fn != Py_None) {
684 preexec_fn_args_tuple = PyTuple_New(0);
685 if (!preexec_fn_args_tuple)
686 goto cleanup;
687 PyOS_BeforeFork();
688 need_after_fork = 1;
689 }
690
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000691 pid = fork();
692 if (pid == 0) {
693 /* Child process */
Victor Stinner0e59cc32010-04-16 23:49:32 +0000694 /*
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000695 * Code from here to _exit() must only use async-signal-safe functions,
696 * listed at `man 7 signal` or
697 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
698 */
699
700 if (preexec_fn != Py_None) {
701 /* We'll be calling back into Python later so we need to do this.
702 * This call may not be async-signal-safe but neither is calling
703 * back into Python. The user asked us to use hope as a strategy
704 * to avoid deadlock... */
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200705 PyOS_AfterFork_Child();
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000706 }
707
708 child_exec(exec_array, argv, envp, cwd,
709 p2cread, p2cwrite, c2pread, c2pwrite,
710 errread, errwrite, errpipe_read, errpipe_write,
711 close_fds, restore_signals, call_setsid,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800712 py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000713 _exit(255);
714 return NULL; /* Dead code to avoid a potential compiler warning. */
715 }
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700716 /* Parent (original) process */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000717 if (pid == -1) {
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700718 /* Capture errno for the exception. */
719 saved_errno = errno;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000720 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000721
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700722 Py_XDECREF(cwd_obj2);
723
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200724 if (need_after_fork)
725 PyOS_AfterFork_Parent();
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000726 if (envp)
727 _Py_FreeCharPArray(envp);
728 if (argv)
729 _Py_FreeCharPArray(argv);
730 _Py_FreeCharPArray(exec_array);
731
732 /* Reenable gc in the parent process (or if fork failed). */
Martin Panterafdd5132015-11-30 02:21:41 +0000733 if (_enable_gc(need_to_reenable_gc, gc_module)) {
734 pid = -1;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000735 }
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000736 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000737 Py_XDECREF(gc_module);
738
Gregory P. Smitha20b6ad2018-09-13 04:30:10 -0700739 if (pid == -1) {
740 errno = saved_errno;
741 /* We can't call this above as PyOS_AfterFork_Parent() calls back
742 * into Python code which would see the unreturned error. */
743 PyErr_SetFromErrno(PyExc_OSError);
744 return NULL; /* fork() failed. */
745 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000746
747 return PyLong_FromPid(pid);
748
749cleanup:
750 if (envp)
751 _Py_FreeCharPArray(envp);
752 if (argv)
753 _Py_FreeCharPArray(argv);
Victor Stinner8f437aa2014-10-05 17:25:19 +0200754 if (exec_array)
755 _Py_FreeCharPArray(exec_array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000756 Py_XDECREF(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000757 Py_XDECREF(fast_args);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000758 Py_XDECREF(preexec_fn_args_tuple);
Martin Panterafdd5132015-11-30 02:21:41 +0000759 _enable_gc(need_to_reenable_gc, gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000760 Py_XDECREF(gc_module);
761 return NULL;
762}
763
764
765PyDoc_STRVAR(subprocess_fork_exec_doc,
766"fork_exec(args, executable_list, close_fds, cwd, env,\n\
767 p2cread, p2cwrite, c2pread, c2pwrite,\n\
768 errread, errwrite, errpipe_read, errpipe_write,\n\
769 restore_signals, call_setsid, preexec_fn)\n\
770\n\
771Forks a child process, closes parent file descriptors as appropriate in the\n\
772child and dups the few that are needed before calling exec() in the child\n\
773process.\n\
774\n\
775The preexec_fn, if supplied, will be called immediately before exec.\n\
776WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
777 It may trigger infrequent, difficult to debug deadlocks.\n\
778\n\
779If an error occurs in the child process before the exec, it is\n\
780serialized and written to the errpipe_write fd per subprocess.py.\n\
781\n\
782Returns: the child process's PID.\n\
783\n\
784Raises: Only on an error in the parent process.\n\
785");
786
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000787/* module level code ********************************************************/
788
789PyDoc_STRVAR(module_doc,
790"A POSIX helper for the subprocess module.");
791
792
793static PyMethodDef module_methods[] = {
794 {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000795 {NULL, NULL} /* sentinel */
796};
797
798
799static struct PyModuleDef _posixsubprocessmodule = {
luzpaza5293b42017-11-05 07:37:50 -0600800 PyModuleDef_HEAD_INIT,
801 "_posixsubprocess",
802 module_doc,
803 -1, /* No memory is needed. */
804 module_methods,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000805};
806
807PyMODINIT_FUNC
808PyInit__posixsubprocess(void)
809{
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000810 return PyModule_Create(&_posixsubprocessmodule);
811}