blob: dbb92ff2f4016c6c67043dcf1910b1e30695af76 [file] [log] [blame]
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001/* Authors: Gregory P. Smith & Jeffrey Yasskin */
2#include "Python.h"
Ross Lagerwall667d75d2011-12-22 09:45:53 +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. Smithe3f78482012-01-21 15:16:17 -080024# define DIRFD(dirp) ((dirp)->dd_fd)
25# define HAVE_DIRFD
26# else
27# define DIRFD(dirp) (dirfd(dirp))
28# endif
Gregory P. Smith8facece2012-01-21 14:01:08 -080029#endif
30
31#define LINUX_SOLARIS_FD_DIR "/proc/self/fd"
32#define BSD_OSX_FD_DIR "/dev/fd"
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000033
34#define POSIX_CALL(call) if ((call) == -1) goto error
35
36
37/* Maximum file descriptor, initialized on module load. */
38static long max_fd;
39
40
41/* Given the gc module call gc.enable() and return 0 on success. */
42static int _enable_gc(PyObject *gc_module)
43{
44 PyObject *result;
45 result = PyObject_CallMethod(gc_module, "enable", NULL);
46 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
251 int fd_used_by_opendir = DIRFD(proc_fd_dir);
252#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. Smith9c4f44f2011-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. Smith9c4f44f2011-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;
483 gc_module = PyImport_ImportModule("gc");
484 if (gc_module == NULL)
485 return NULL;
486 result = PyObject_CallMethod(gc_module, "isenabled", NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000487 if (result == NULL) {
488 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000489 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000490 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000491 need_to_reenable_gc = PyObject_IsTrue(result);
492 Py_DECREF(result);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000493 if (need_to_reenable_gc == -1) {
494 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000495 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000496 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000497 result = PyObject_CallMethod(gc_module, "disable", NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000498 if (result == NULL) {
499 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000500 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000501 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000502 Py_DECREF(result);
503 }
504
505 exec_array = _PySequence_BytesToCharpArray(executable_list);
506 if (!exec_array)
507 return NULL;
508
509 /* Convert args and env into appropriate arguments for exec() */
510 /* These conversions are done in the parent process to avoid allocating
511 or freeing memory in the child process. */
512 if (process_args != Py_None) {
Gregory P. Smith68f52172010-03-15 06:07:42 +0000513 Py_ssize_t num_args;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000514 /* Equivalent to: */
515 /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
Gregory P. Smith68f52172010-03-15 06:07:42 +0000516 fast_args = PySequence_Fast(process_args, "argv must be a tuple");
517 num_args = PySequence_Fast_GET_SIZE(fast_args);
518 converted_args = PyTuple_New(num_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000519 if (converted_args == NULL)
520 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000521 for (arg_num = 0; arg_num < num_args; ++arg_num) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000522 PyObject *borrowed_arg, *converted_arg;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000523 borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000524 if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
525 goto cleanup;
526 PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
527 }
528
529 argv = _PySequence_BytesToCharpArray(converted_args);
530 Py_CLEAR(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000531 Py_CLEAR(fast_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000532 if (!argv)
533 goto cleanup;
534 }
535
536 if (env_list != Py_None) {
537 envp = _PySequence_BytesToCharpArray(env_list);
538 if (!envp)
539 goto cleanup;
540 }
541
542 if (preexec_fn != Py_None) {
543 preexec_fn_args_tuple = PyTuple_New(0);
544 if (!preexec_fn_args_tuple)
545 goto cleanup;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000546 _PyImport_AcquireLock();
547 }
548
549 if (cwd_obj != Py_None) {
550 if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
551 goto cleanup;
Victor Stinnerdcb24032010-04-22 12:08:36 +0000552 cwd = PyBytes_AsString(cwd_obj2);
Victor Stinner0e59cc32010-04-16 23:49:32 +0000553 } else {
554 cwd = NULL;
555 cwd_obj2 = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000556 }
557
558 pid = fork();
559 if (pid == 0) {
560 /* Child process */
Victor Stinner0e59cc32010-04-16 23:49:32 +0000561 /*
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000562 * Code from here to _exit() must only use async-signal-safe functions,
563 * listed at `man 7 signal` or
564 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
565 */
566
567 if (preexec_fn != Py_None) {
568 /* We'll be calling back into Python later so we need to do this.
569 * This call may not be async-signal-safe but neither is calling
570 * back into Python. The user asked us to use hope as a strategy
571 * to avoid deadlock... */
572 PyOS_AfterFork();
573 }
574
575 child_exec(exec_array, argv, envp, cwd,
576 p2cread, p2cwrite, c2pread, c2pwrite,
577 errread, errwrite, errpipe_read, errpipe_write,
578 close_fds, restore_signals, call_setsid,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800579 py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000580 _exit(255);
581 return NULL; /* Dead code to avoid a potential compiler warning. */
582 }
Victor Stinner0e59cc32010-04-16 23:49:32 +0000583 Py_XDECREF(cwd_obj2);
584
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000585 if (pid == -1) {
586 /* Capture the errno exception before errno can be clobbered. */
587 PyErr_SetFromErrno(PyExc_OSError);
588 }
589 if (preexec_fn != Py_None &&
590 _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) {
591 PyErr_SetString(PyExc_RuntimeError,
592 "not holding the import lock");
593 }
594
595 /* Parent process */
596 if (envp)
597 _Py_FreeCharPArray(envp);
598 if (argv)
599 _Py_FreeCharPArray(argv);
600 _Py_FreeCharPArray(exec_array);
601
602 /* Reenable gc in the parent process (or if fork failed). */
603 if (need_to_reenable_gc && _enable_gc(gc_module)) {
604 Py_XDECREF(gc_module);
605 return NULL;
606 }
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000607 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000608 Py_XDECREF(gc_module);
609
610 if (pid == -1)
611 return NULL; /* fork() failed. Exception set earlier. */
612
613 return PyLong_FromPid(pid);
614
615cleanup:
616 if (envp)
617 _Py_FreeCharPArray(envp);
618 if (argv)
619 _Py_FreeCharPArray(argv);
620 _Py_FreeCharPArray(exec_array);
621 Py_XDECREF(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000622 Py_XDECREF(fast_args);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000623 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000624
625 /* Reenable gc if it was disabled. */
626 if (need_to_reenable_gc)
627 _enable_gc(gc_module);
628 Py_XDECREF(gc_module);
629 return NULL;
630}
631
632
633PyDoc_STRVAR(subprocess_fork_exec_doc,
634"fork_exec(args, executable_list, close_fds, cwd, env,\n\
635 p2cread, p2cwrite, c2pread, c2pwrite,\n\
636 errread, errwrite, errpipe_read, errpipe_write,\n\
637 restore_signals, call_setsid, preexec_fn)\n\
638\n\
639Forks a child process, closes parent file descriptors as appropriate in the\n\
640child and dups the few that are needed before calling exec() in the child\n\
641process.\n\
642\n\
643The preexec_fn, if supplied, will be called immediately before exec.\n\
644WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
645 It may trigger infrequent, difficult to debug deadlocks.\n\
646\n\
647If an error occurs in the child process before the exec, it is\n\
648serialized and written to the errpipe_write fd per subprocess.py.\n\
649\n\
650Returns: the child process's PID.\n\
651\n\
652Raises: Only on an error in the parent process.\n\
653");
654
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000655PyDoc_STRVAR(subprocess_cloexec_pipe_doc,
656"cloexec_pipe() -> (read_end, write_end)\n\n\
657Create a pipe whose ends have the cloexec flag set.");
658
659static PyObject *
660subprocess_cloexec_pipe(PyObject *self, PyObject *noargs)
661{
662 int fds[2];
663 int res;
664#ifdef HAVE_PIPE2
665 Py_BEGIN_ALLOW_THREADS
666 res = pipe2(fds, O_CLOEXEC);
667 Py_END_ALLOW_THREADS
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000668 if (res != 0 && errno == ENOSYS)
669 {
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000670 {
671#endif
672 /* We hold the GIL which offers some protection from other code calling
673 * fork() before the CLOEXEC flags have been set but we can't guarantee
674 * anything without pipe2(). */
675 long oldflags;
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000676
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000677 res = pipe(fds);
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000678
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000679 if (res == 0) {
680 oldflags = fcntl(fds[0], F_GETFD, 0);
681 if (oldflags < 0) res = oldflags;
682 }
683 if (res == 0)
684 res = fcntl(fds[0], F_SETFD, oldflags | FD_CLOEXEC);
685
686 if (res == 0) {
687 oldflags = fcntl(fds[1], F_GETFD, 0);
688 if (oldflags < 0) res = oldflags;
689 }
690 if (res == 0)
691 res = fcntl(fds[1], F_SETFD, oldflags | FD_CLOEXEC);
692#ifdef HAVE_PIPE2
693 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000694 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000695#endif
696 if (res != 0)
697 return PyErr_SetFromErrno(PyExc_OSError);
698 return Py_BuildValue("(ii)", fds[0], fds[1]);
699}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000700
701/* module level code ********************************************************/
702
703PyDoc_STRVAR(module_doc,
704"A POSIX helper for the subprocess module.");
705
706
707static PyMethodDef module_methods[] = {
708 {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000709 {"cloexec_pipe", subprocess_cloexec_pipe, METH_NOARGS, subprocess_cloexec_pipe_doc},
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000710 {NULL, NULL} /* sentinel */
711};
712
713
714static struct PyModuleDef _posixsubprocessmodule = {
715 PyModuleDef_HEAD_INIT,
716 "_posixsubprocess",
717 module_doc,
718 -1, /* No memory is needed. */
719 module_methods,
720};
721
722PyMODINIT_FUNC
723PyInit__posixsubprocess(void)
724{
725#ifdef _SC_OPEN_MAX
726 max_fd = sysconf(_SC_OPEN_MAX);
727 if (max_fd == -1)
728#endif
729 max_fd = 256; /* Matches Lib/subprocess.py */
730
731 return PyModule_Create(&_posixsubprocessmodule);
732}