blob: 7407a11bc8d1f4fe7f6df0a603eec293d2dc7ec4 [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
11#ifdef HAVE_SYS_SYSCALL_H
12#include <sys/syscall.h>
13#endif
14#ifdef HAVE_DIRENT_H
15#include <dirent.h>
16#endif
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000017
Gregory P. Smithe3f78482012-01-21 15:16:17 -080018#if defined(sun)
19/* readdir64 is used to work around Solaris 9 bug 6395699. */
20# define readdir readdir64
21# define dirent dirent64
22# if !defined(HAVE_DIRFD)
Gregory P. Smith8facece2012-01-21 14:01:08 -080023/* Some versions of Solaris lack dirfd(). */
Gregory P. Smithe9b7cab2012-01-21 15:19:11 -080024# define dirfd(dirp) ((dirp)->dd_fd)
Gregory P. Smithe3f78482012-01-21 15:16:17 -080025# define HAVE_DIRFD
Gregory P. Smithe3f78482012-01-21 15:16:17 -080026# endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080027#endif
28
29#define LINUX_SOLARIS_FD_DIR "/proc/self/fd"
30#define BSD_OSX_FD_DIR "/dev/fd"
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000031
32#define POSIX_CALL(call) if ((call) == -1) goto error
33
34
35/* Maximum file descriptor, initialized on module load. */
36static long max_fd;
37
38
39/* Given the gc module call gc.enable() and return 0 on success. */
40static int _enable_gc(PyObject *gc_module)
41{
42 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020043 _Py_IDENTIFIER(enable);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020044
45 result = _PyObject_CallMethodId(gc_module, &PyId_enable, NULL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000046 if (result == NULL)
47 return 1;
48 Py_DECREF(result);
49 return 0;
50}
51
52
Gregory P. Smith8facece2012-01-21 14:01:08 -080053/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
54static int _pos_int_from_ascii(char *name)
55{
56 int num = 0;
57 while (*name >= '0' && *name <= '9') {
58 num = num * 10 + (*name - '0');
59 ++name;
60 }
61 if (*name)
62 return -1; /* Non digit found, not a number. */
63 return num;
64}
65
66
67/* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
68static int _sanity_check_python_fd_sequence(PyObject *fd_sequence)
69{
70 Py_ssize_t seq_idx, seq_len = PySequence_Length(fd_sequence);
71 long prev_fd = -1;
72 for (seq_idx = 0; seq_idx < seq_len; ++seq_idx) {
73 PyObject* py_fd = PySequence_Fast_GET_ITEM(fd_sequence, seq_idx);
74 long iter_fd = PyLong_AsLong(py_fd);
75 if (iter_fd < 0 || iter_fd < prev_fd || iter_fd > INT_MAX) {
76 /* Negative, overflow, not a Long, unsorted, too big for a fd. */
77 return 1;
78 }
79 }
80 return 0;
81}
82
83
84/* Is fd found in the sorted Python Sequence? */
85static int _is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
86{
87 /* Binary search. */
88 Py_ssize_t search_min = 0;
89 Py_ssize_t search_max = PySequence_Length(fd_sequence) - 1;
90 if (search_max < 0)
91 return 0;
92 do {
93 long middle = (search_min + search_max) / 2;
94 long middle_fd = PyLong_AsLong(
95 PySequence_Fast_GET_ITEM(fd_sequence, middle));
96 if (fd == middle_fd)
97 return 1;
98 if (fd > middle_fd)
99 search_min = middle + 1;
100 else
101 search_max = middle - 1;
102 } while (search_min <= search_max);
103 return 0;
104}
105
106
107/* Close all file descriptors in the range start_fd inclusive to
108 * end_fd exclusive except for those in py_fds_to_keep. If the
109 * range defined by [start_fd, end_fd) is large this will take a
110 * long time as it calls close() on EVERY possible fd.
111 */
112static void _close_fds_by_brute_force(int start_fd, int end_fd,
113 PyObject *py_fds_to_keep)
114{
115 Py_ssize_t num_fds_to_keep = PySequence_Length(py_fds_to_keep);
116 Py_ssize_t keep_seq_idx;
117 int fd_num;
118 /* As py_fds_to_keep is sorted we can loop through the list closing
119 * fds inbetween any in the keep list falling within our range. */
120 for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
121 PyObject* py_keep_fd = PySequence_Fast_GET_ITEM(py_fds_to_keep,
122 keep_seq_idx);
123 int keep_fd = PyLong_AsLong(py_keep_fd);
124 if (keep_fd < start_fd)
125 continue;
126 for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
127 while (close(fd_num) < 0 && errno == EINTR);
128 }
129 start_fd = keep_fd + 1;
130 }
131 if (start_fd <= end_fd) {
132 for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
133 while (close(fd_num) < 0 && errno == EINTR);
134 }
135 }
136}
137
138
139#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
140/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
141 * only to read a directory of short file descriptor number names. The kernel
142 * will return an error if we didn't give it enough space. Highly Unlikely.
143 * This structure is very old and stable: It will not change unless the kernel
144 * chooses to break compatibility with all existing binaries. Highly Unlikely.
145 */
146struct linux_dirent {
147 unsigned long d_ino; /* Inode number */
148 unsigned long d_off; /* Offset to next linux_dirent */
149 unsigned short d_reclen; /* Length of this linux_dirent */
150 char d_name[256]; /* Filename (null-terminated) */
151};
152
153/* Close all open file descriptors in the range start_fd inclusive to end_fd
154 * exclusive. Do not close any in the sorted py_fds_to_keep list.
155 *
156 * This version is async signal safe as it does not make any unsafe C library
157 * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
158 * to resort to making a kernel system call directly but this is the ONLY api
159 * available that does no harm. opendir/readdir/closedir perform memory
160 * allocation and locking so while they usually work they are not guaranteed
161 * to (especially if you have replaced your malloc implementation). A version
162 * of this function that uses those can be found in the _maybe_unsafe variant.
163 *
164 * This is Linux specific because that is all I am ready to test it on. It
165 * should be easy to add OS specific dirent or dirent64 structures and modify
166 * it with some cpp #define magic to work on other OSes as well if you want.
167 */
168static void _close_open_fd_range_safe(int start_fd, int end_fd,
169 PyObject* py_fds_to_keep)
170{
171 int fd_dir_fd;
172 if (start_fd >= end_fd)
173 return;
174 fd_dir_fd = open(LINUX_SOLARIS_FD_DIR, O_RDONLY | O_CLOEXEC, 0);
175 /* Not trying to open the BSD_OSX path as this is currently Linux only. */
176 if (fd_dir_fd == -1) {
177 /* No way to get a list of open fds. */
178 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
179 return;
180 } else {
181 char buffer[sizeof(struct linux_dirent)];
182 int bytes;
183 while ((bytes = syscall(SYS_getdents, fd_dir_fd,
184 (struct linux_dirent *)buffer,
185 sizeof(buffer))) > 0) {
186 struct linux_dirent *entry;
187 int offset;
188 for (offset = 0; offset < bytes; offset += entry->d_reclen) {
189 int fd;
190 entry = (struct linux_dirent *)(buffer + offset);
191 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
192 continue; /* Not a number. */
193 if (fd != fd_dir_fd && fd >= start_fd && fd < end_fd &&
194 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
195 while (close(fd) < 0 && errno == EINTR);
196 }
197 }
198 }
199 close(fd_dir_fd);
200 }
201}
202
203#define _close_open_fd_range _close_open_fd_range_safe
204
205#else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
206
207
208/* Close all open file descriptors in the range start_fd inclusive to end_fd
209 * exclusive. Do not close any in the sorted py_fds_to_keep list.
210 *
211 * This function violates the strict use of async signal safe functions. :(
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800212 * It calls opendir(), readdir() and closedir(). Of these, the one most
Gregory P. Smith8facece2012-01-21 14:01:08 -0800213 * likely to ever cause a problem is opendir() as it performs an internal
214 * malloc(). Practically this should not be a problem. The Java VM makes the
215 * same calls between fork and exec in its own UNIXProcess_md.c implementation.
216 *
217 * readdir_r() is not used because it provides no benefit. It is typically
218 * implemented as readdir() followed by memcpy(). See also:
219 * http://womble.decadent.org.uk/readdir_r-advisory.html
220 */
221static void _close_open_fd_range_maybe_unsafe(int start_fd, int end_fd,
222 PyObject* py_fds_to_keep)
223{
224 DIR *proc_fd_dir;
225#ifndef HAVE_DIRFD
226 while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep) &&
227 (start_fd < end_fd)) {
228 ++start_fd;
229 }
230 if (start_fd >= end_fd)
231 return;
232 /* Close our lowest fd before we call opendir so that it is likely to
233 * reuse that fd otherwise we might close opendir's file descriptor in
234 * our loop. This trick assumes that fd's are allocated on a lowest
235 * available basis. */
236 while (close(start_fd) < 0 && errno == EINTR);
237 ++start_fd;
238#endif
239 if (start_fd >= end_fd)
240 return;
241
242 proc_fd_dir = opendir(BSD_OSX_FD_DIR);
243 if (!proc_fd_dir)
244 proc_fd_dir = opendir(LINUX_SOLARIS_FD_DIR);
245 if (!proc_fd_dir) {
246 /* No way to get a list of open fds. */
247 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
248 } else {
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800249 struct dirent *dir_entry;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800250#ifdef HAVE_DIRFD
Gregory P. Smithe9b7cab2012-01-21 15:19:11 -0800251 int fd_used_by_opendir = dirfd(proc_fd_dir);
Gregory P. Smith8facece2012-01-21 14:01:08 -0800252#else
253 int fd_used_by_opendir = start_fd - 1;
254#endif
255 errno = 0;
Gregory P. Smithe3f78482012-01-21 15:16:17 -0800256 while ((dir_entry = readdir(proc_fd_dir))) {
Gregory P. Smith8facece2012-01-21 14:01:08 -0800257 int fd;
258 if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
259 continue; /* Not a number. */
260 if (fd != fd_used_by_opendir && fd >= start_fd && fd < end_fd &&
261 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
262 while (close(fd) < 0 && errno == EINTR);
263 }
264 errno = 0;
265 }
266 if (errno) {
267 /* readdir error, revert behavior. Highly Unlikely. */
268 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
269 }
270 closedir(proc_fd_dir);
271 }
272}
273
274#define _close_open_fd_range _close_open_fd_range_maybe_unsafe
275
276#endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
277
278
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000279/*
280 * This function is code executed in the child process immediately after fork
281 * to set things up and call exec().
282 *
283 * All of the code in this function must only use async-signal-safe functions,
284 * listed at `man 7 signal` or
285 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
286 *
287 * This restriction is documented at
288 * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
289 */
290static void child_exec(char *const exec_array[],
291 char *const argv[],
292 char *const envp[],
293 const char *cwd,
294 int p2cread, int p2cwrite,
295 int c2pread, int c2pwrite,
296 int errread, int errwrite,
297 int errpipe_read, int errpipe_write,
298 int close_fds, int restore_signals,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800299 int call_setsid,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000300 PyObject *py_fds_to_keep,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000301 PyObject *preexec_fn,
302 PyObject *preexec_fn_args_tuple)
303{
Gregory P. Smith8facece2012-01-21 14:01:08 -0800304 int i, saved_errno, unused;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000305 PyObject *result;
Gregory P. Smith14affb82010-12-22 05:22:17 +0000306 const char* err_msg = "";
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000307 /* Buffer large enough to hold a hex integer. We can't malloc. */
308 char hex_errno[sizeof(saved_errno)*2+1];
309
310 /* Close parent's pipe ends. */
311 if (p2cwrite != -1) {
312 POSIX_CALL(close(p2cwrite));
313 }
314 if (c2pread != -1) {
315 POSIX_CALL(close(c2pread));
316 }
317 if (errread != -1) {
318 POSIX_CALL(close(errread));
319 }
320 POSIX_CALL(close(errpipe_read));
321
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200322 /* When duping fds, if there arises a situation where one of the fds is
323 either 0, 1 or 2, it is possible that it is overwritten (#12607). */
324 if (c2pwrite == 0)
325 POSIX_CALL(c2pwrite = dup(c2pwrite));
326 if (errwrite == 0 || errwrite == 1)
327 POSIX_CALL(errwrite = dup(errwrite));
328
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000329 /* Dup fds for child.
330 dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
331 would be a no-op (issue #10806). */
332 if (p2cread == 0) {
333 int old = fcntl(p2cread, F_GETFD);
334 if (old != -1)
335 fcntl(p2cread, F_SETFD, old & ~FD_CLOEXEC);
336 } else if (p2cread != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000337 POSIX_CALL(dup2(p2cread, 0)); /* stdin */
338 }
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000339 if (c2pwrite == 1) {
340 int old = fcntl(c2pwrite, F_GETFD);
341 if (old != -1)
342 fcntl(c2pwrite, F_SETFD, old & ~FD_CLOEXEC);
343 } else if (c2pwrite != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000344 POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
345 }
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000346 if (errwrite == 2) {
347 int old = fcntl(errwrite, F_GETFD);
348 if (old != -1)
349 fcntl(errwrite, F_SETFD, old & ~FD_CLOEXEC);
350 } else if (errwrite != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000351 POSIX_CALL(dup2(errwrite, 2)); /* stderr */
352 }
353
354 /* Close pipe fds. Make sure we don't close the same fd more than */
355 /* once, or standard fds. */
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000356 if (p2cread > 2) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000357 POSIX_CALL(close(p2cread));
358 }
Gregory P. Smith81218982011-03-15 14:56:39 -0400359 if (c2pwrite > 2 && c2pwrite != p2cread) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000360 POSIX_CALL(close(c2pwrite));
361 }
Gregory P. Smith81218982011-03-15 14:56:39 -0400362 if (errwrite != c2pwrite && errwrite != p2cread && errwrite > 2) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000363 POSIX_CALL(close(errwrite));
364 }
365
Gregory P. Smith8facece2012-01-21 14:01:08 -0800366 if (close_fds)
367 _close_open_fd_range(3, max_fd, py_fds_to_keep);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000368
369 if (cwd)
370 POSIX_CALL(chdir(cwd));
371
372 if (restore_signals)
373 _Py_RestoreSignals();
374
375#ifdef HAVE_SETSID
376 if (call_setsid)
377 POSIX_CALL(setsid());
378#endif
379
380 if (preexec_fn != Py_None && preexec_fn_args_tuple) {
381 /* This is where the user has asked us to deadlock their program. */
382 result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
383 if (result == NULL) {
384 /* Stringifying the exception or traceback would involve
385 * memory allocation and thus potential for deadlock.
386 * We've already faced potential deadlock by calling back
387 * into Python in the first place, so it probably doesn't
388 * matter but we avoid it to minimize the possibility. */
389 err_msg = "Exception occurred in preexec_fn.";
390 errno = 0; /* We don't want to report an OSError. */
391 goto error;
392 }
393 /* Py_DECREF(result); - We're about to exec so why bother? */
394 }
395
396 /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
397 /* given the executable_list generated by Lib/subprocess.py. */
398 saved_errno = 0;
399 for (i = 0; exec_array[i] != NULL; ++i) {
400 const char *executable = exec_array[i];
401 if (envp) {
402 execve(executable, argv, envp);
403 } else {
404 execv(executable, argv);
405 }
406 if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
407 saved_errno = errno;
408 }
409 }
410 /* Report the first exec error, not the last. */
411 if (saved_errno)
412 errno = saved_errno;
413
414error:
415 saved_errno = errno;
416 /* Report the posix error to our parent process. */
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800417 /* We ignore all write() return values as the total size of our writes is
418 * less than PIPEBUF and we cannot do anything about an error anyways. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000419 if (saved_errno) {
420 char *cur;
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800421 unused = write(errpipe_write, "OSError:", 8);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000422 cur = hex_errno + sizeof(hex_errno);
423 while (saved_errno != 0 && cur > hex_errno) {
424 *--cur = "0123456789ABCDEF"[saved_errno % 16];
425 saved_errno /= 16;
426 }
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800427 unused = write(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
428 unused = write(errpipe_write, ":", 1);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000429 /* We can't call strerror(saved_errno). It is not async signal safe.
430 * The parent process will look the error message up. */
431 } else {
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800432 unused = write(errpipe_write, "RuntimeError:0:", 15);
433 unused = write(errpipe_write, err_msg, strlen(err_msg));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000434 }
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800435 if (unused) return; /* silly? yes! avoids gcc compiler warning. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000436}
437
438
439static PyObject *
440subprocess_fork_exec(PyObject* self, PyObject *args)
441{
442 PyObject *gc_module = NULL;
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000443 PyObject *executable_list, *py_close_fds, *py_fds_to_keep;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000444 PyObject *env_list, *preexec_fn;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000445 PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000446 PyObject *preexec_fn_args_tuple = NULL;
447 int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
448 int errpipe_read, errpipe_write, close_fds, restore_signals;
449 int call_setsid;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000450 PyObject *cwd_obj, *cwd_obj2;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000451 const char *cwd;
452 pid_t pid;
453 int need_to_reenable_gc = 0;
454 char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800455 Py_ssize_t arg_num;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000456
457 if (!PyArg_ParseTuple(
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000458 args, "OOOOOOiiiiiiiiiiO:fork_exec",
459 &process_args, &executable_list, &py_close_fds, &py_fds_to_keep,
Victor Stinner0e59cc32010-04-16 23:49:32 +0000460 &cwd_obj, &env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000461 &p2cread, &p2cwrite, &c2pread, &c2pwrite,
462 &errread, &errwrite, &errpipe_read, &errpipe_write,
463 &restore_signals, &call_setsid, &preexec_fn))
464 return NULL;
465
466 close_fds = PyObject_IsTrue(py_close_fds);
467 if (close_fds && errpipe_write < 3) { /* precondition */
468 PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
469 return NULL;
470 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800471 if (PySequence_Length(py_fds_to_keep) < 0) {
472 PyErr_SetString(PyExc_ValueError, "cannot get length of fds_to_keep");
473 return NULL;
474 }
475 if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
476 PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000477 return NULL;
478 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000479
480 /* We need to call gc.disable() when we'll be calling preexec_fn */
481 if (preexec_fn != Py_None) {
482 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200483 _Py_IDENTIFIER(isenabled);
484 _Py_IDENTIFIER(disable);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200485
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000486 gc_module = PyImport_ImportModule("gc");
487 if (gc_module == NULL)
488 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200489 result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000490 if (result == NULL) {
491 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000492 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000493 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000494 need_to_reenable_gc = PyObject_IsTrue(result);
495 Py_DECREF(result);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000496 if (need_to_reenable_gc == -1) {
497 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000498 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000499 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200500 result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000501 if (result == NULL) {
502 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000503 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000504 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000505 Py_DECREF(result);
506 }
507
508 exec_array = _PySequence_BytesToCharpArray(executable_list);
509 if (!exec_array)
510 return NULL;
511
512 /* Convert args and env into appropriate arguments for exec() */
513 /* These conversions are done in the parent process to avoid allocating
514 or freeing memory in the child process. */
515 if (process_args != Py_None) {
Gregory P. Smith68f52172010-03-15 06:07:42 +0000516 Py_ssize_t num_args;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000517 /* Equivalent to: */
518 /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
Gregory P. Smith68f52172010-03-15 06:07:42 +0000519 fast_args = PySequence_Fast(process_args, "argv must be a tuple");
520 num_args = PySequence_Fast_GET_SIZE(fast_args);
521 converted_args = PyTuple_New(num_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000522 if (converted_args == NULL)
523 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000524 for (arg_num = 0; arg_num < num_args; ++arg_num) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000525 PyObject *borrowed_arg, *converted_arg;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000526 borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000527 if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
528 goto cleanup;
529 PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
530 }
531
532 argv = _PySequence_BytesToCharpArray(converted_args);
533 Py_CLEAR(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000534 Py_CLEAR(fast_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000535 if (!argv)
536 goto cleanup;
537 }
538
539 if (env_list != Py_None) {
540 envp = _PySequence_BytesToCharpArray(env_list);
541 if (!envp)
542 goto cleanup;
543 }
544
545 if (preexec_fn != Py_None) {
546 preexec_fn_args_tuple = PyTuple_New(0);
547 if (!preexec_fn_args_tuple)
548 goto cleanup;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000549 _PyImport_AcquireLock();
550 }
551
552 if (cwd_obj != Py_None) {
553 if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
554 goto cleanup;
Victor Stinnerdcb24032010-04-22 12:08:36 +0000555 cwd = PyBytes_AsString(cwd_obj2);
Victor Stinner0e59cc32010-04-16 23:49:32 +0000556 } else {
557 cwd = NULL;
558 cwd_obj2 = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000559 }
560
561 pid = fork();
562 if (pid == 0) {
563 /* Child process */
Victor Stinner0e59cc32010-04-16 23:49:32 +0000564 /*
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000565 * Code from here to _exit() must only use async-signal-safe functions,
566 * listed at `man 7 signal` or
567 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
568 */
569
570 if (preexec_fn != Py_None) {
571 /* We'll be calling back into Python later so we need to do this.
572 * This call may not be async-signal-safe but neither is calling
573 * back into Python. The user asked us to use hope as a strategy
574 * to avoid deadlock... */
575 PyOS_AfterFork();
576 }
577
578 child_exec(exec_array, argv, envp, cwd,
579 p2cread, p2cwrite, c2pread, c2pwrite,
580 errread, errwrite, errpipe_read, errpipe_write,
581 close_fds, restore_signals, call_setsid,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800582 py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000583 _exit(255);
584 return NULL; /* Dead code to avoid a potential compiler warning. */
585 }
Victor Stinner0e59cc32010-04-16 23:49:32 +0000586 Py_XDECREF(cwd_obj2);
587
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000588 if (pid == -1) {
589 /* Capture the errno exception before errno can be clobbered. */
590 PyErr_SetFromErrno(PyExc_OSError);
591 }
592 if (preexec_fn != Py_None &&
593 _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) {
594 PyErr_SetString(PyExc_RuntimeError,
595 "not holding the import lock");
596 }
597
598 /* Parent process */
599 if (envp)
600 _Py_FreeCharPArray(envp);
601 if (argv)
602 _Py_FreeCharPArray(argv);
603 _Py_FreeCharPArray(exec_array);
604
605 /* Reenable gc in the parent process (or if fork failed). */
606 if (need_to_reenable_gc && _enable_gc(gc_module)) {
607 Py_XDECREF(gc_module);
608 return NULL;
609 }
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000610 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000611 Py_XDECREF(gc_module);
612
613 if (pid == -1)
614 return NULL; /* fork() failed. Exception set earlier. */
615
616 return PyLong_FromPid(pid);
617
618cleanup:
619 if (envp)
620 _Py_FreeCharPArray(envp);
621 if (argv)
622 _Py_FreeCharPArray(argv);
623 _Py_FreeCharPArray(exec_array);
624 Py_XDECREF(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000625 Py_XDECREF(fast_args);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000626 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000627
628 /* Reenable gc if it was disabled. */
629 if (need_to_reenable_gc)
630 _enable_gc(gc_module);
631 Py_XDECREF(gc_module);
632 return NULL;
633}
634
635
636PyDoc_STRVAR(subprocess_fork_exec_doc,
637"fork_exec(args, executable_list, close_fds, cwd, env,\n\
638 p2cread, p2cwrite, c2pread, c2pwrite,\n\
639 errread, errwrite, errpipe_read, errpipe_write,\n\
640 restore_signals, call_setsid, preexec_fn)\n\
641\n\
642Forks a child process, closes parent file descriptors as appropriate in the\n\
643child and dups the few that are needed before calling exec() in the child\n\
644process.\n\
645\n\
646The preexec_fn, if supplied, will be called immediately before exec.\n\
647WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
648 It may trigger infrequent, difficult to debug deadlocks.\n\
649\n\
650If an error occurs in the child process before the exec, it is\n\
651serialized and written to the errpipe_write fd per subprocess.py.\n\
652\n\
653Returns: the child process's PID.\n\
654\n\
655Raises: Only on an error in the parent process.\n\
656");
657
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000658PyDoc_STRVAR(subprocess_cloexec_pipe_doc,
659"cloexec_pipe() -> (read_end, write_end)\n\n\
660Create a pipe whose ends have the cloexec flag set.");
661
662static PyObject *
663subprocess_cloexec_pipe(PyObject *self, PyObject *noargs)
664{
665 int fds[2];
666 int res;
667#ifdef HAVE_PIPE2
668 Py_BEGIN_ALLOW_THREADS
669 res = pipe2(fds, O_CLOEXEC);
670 Py_END_ALLOW_THREADS
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000671 if (res != 0 && errno == ENOSYS)
672 {
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000673 {
674#endif
675 /* We hold the GIL which offers some protection from other code calling
676 * fork() before the CLOEXEC flags have been set but we can't guarantee
677 * anything without pipe2(). */
678 long oldflags;
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000679
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000680 res = pipe(fds);
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000681
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000682 if (res == 0) {
683 oldflags = fcntl(fds[0], F_GETFD, 0);
684 if (oldflags < 0) res = oldflags;
685 }
686 if (res == 0)
687 res = fcntl(fds[0], F_SETFD, oldflags | FD_CLOEXEC);
688
689 if (res == 0) {
690 oldflags = fcntl(fds[1], F_GETFD, 0);
691 if (oldflags < 0) res = oldflags;
692 }
693 if (res == 0)
694 res = fcntl(fds[1], F_SETFD, oldflags | FD_CLOEXEC);
695#ifdef HAVE_PIPE2
696 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000697 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000698#endif
699 if (res != 0)
700 return PyErr_SetFromErrno(PyExc_OSError);
701 return Py_BuildValue("(ii)", fds[0], fds[1]);
702}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000703
704/* module level code ********************************************************/
705
706PyDoc_STRVAR(module_doc,
707"A POSIX helper for the subprocess module.");
708
709
710static PyMethodDef module_methods[] = {
711 {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000712 {"cloexec_pipe", subprocess_cloexec_pipe, METH_NOARGS, subprocess_cloexec_pipe_doc},
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000713 {NULL, NULL} /* sentinel */
714};
715
716
717static struct PyModuleDef _posixsubprocessmodule = {
718 PyModuleDef_HEAD_INIT,
719 "_posixsubprocess",
720 module_doc,
721 -1, /* No memory is needed. */
722 module_methods,
723};
724
725PyMODINIT_FUNC
726PyInit__posixsubprocess(void)
727{
728#ifdef _SC_OPEN_MAX
729 max_fd = sysconf(_SC_OPEN_MAX);
730 if (max_fd == -1)
731#endif
732 max_fd = 256; /* Matches Lib/subprocess.py */
733
734 return PyModule_Create(&_posixsubprocessmodule);
735}