blob: c3f7272429dfb18fff7d0c5190d54a8d700bbbb3 [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. Smith8facece2012-01-21 14:01:08 -080018#if defined(sun) && !defined(HAVE_DIRFD)
19/* Some versions of Solaris lack dirfd(). */
20# define DIRFD(dirp) ((dirp)->dd_fd)
21# define HAVE_DIRFD
22#else
23# define DIRFD(dirp) (dirfd(dirp))
24#endif
25
26#define LINUX_SOLARIS_FD_DIR "/proc/self/fd"
27#define BSD_OSX_FD_DIR "/dev/fd"
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000028
29#define POSIX_CALL(call) if ((call) == -1) goto error
30
31
32/* Maximum file descriptor, initialized on module load. */
33static long max_fd;
34
35
36/* Given the gc module call gc.enable() and return 0 on success. */
37static int _enable_gc(PyObject *gc_module)
38{
39 PyObject *result;
40 result = PyObject_CallMethod(gc_module, "enable", NULL);
41 if (result == NULL)
42 return 1;
43 Py_DECREF(result);
44 return 0;
45}
46
47
Gregory P. Smith8facece2012-01-21 14:01:08 -080048/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
49static int _pos_int_from_ascii(char *name)
50{
51 int num = 0;
52 while (*name >= '0' && *name <= '9') {
53 num = num * 10 + (*name - '0');
54 ++name;
55 }
56 if (*name)
57 return -1; /* Non digit found, not a number. */
58 return num;
59}
60
61
62/* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
63static int _sanity_check_python_fd_sequence(PyObject *fd_sequence)
64{
65 Py_ssize_t seq_idx, seq_len = PySequence_Length(fd_sequence);
66 long prev_fd = -1;
67 for (seq_idx = 0; seq_idx < seq_len; ++seq_idx) {
68 PyObject* py_fd = PySequence_Fast_GET_ITEM(fd_sequence, seq_idx);
69 long iter_fd = PyLong_AsLong(py_fd);
70 if (iter_fd < 0 || iter_fd < prev_fd || iter_fd > INT_MAX) {
71 /* Negative, overflow, not a Long, unsorted, too big for a fd. */
72 return 1;
73 }
74 }
75 return 0;
76}
77
78
79/* Is fd found in the sorted Python Sequence? */
80static int _is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
81{
82 /* Binary search. */
83 Py_ssize_t search_min = 0;
84 Py_ssize_t search_max = PySequence_Length(fd_sequence) - 1;
85 if (search_max < 0)
86 return 0;
87 do {
88 long middle = (search_min + search_max) / 2;
89 long middle_fd = PyLong_AsLong(
90 PySequence_Fast_GET_ITEM(fd_sequence, middle));
91 if (fd == middle_fd)
92 return 1;
93 if (fd > middle_fd)
94 search_min = middle + 1;
95 else
96 search_max = middle - 1;
97 } while (search_min <= search_max);
98 return 0;
99}
100
101
102/* Close all file descriptors in the range start_fd inclusive to
103 * end_fd exclusive except for those in py_fds_to_keep. If the
104 * range defined by [start_fd, end_fd) is large this will take a
105 * long time as it calls close() on EVERY possible fd.
106 */
107static void _close_fds_by_brute_force(int start_fd, int end_fd,
108 PyObject *py_fds_to_keep)
109{
110 Py_ssize_t num_fds_to_keep = PySequence_Length(py_fds_to_keep);
111 Py_ssize_t keep_seq_idx;
112 int fd_num;
113 /* As py_fds_to_keep is sorted we can loop through the list closing
114 * fds inbetween any in the keep list falling within our range. */
115 for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
116 PyObject* py_keep_fd = PySequence_Fast_GET_ITEM(py_fds_to_keep,
117 keep_seq_idx);
118 int keep_fd = PyLong_AsLong(py_keep_fd);
119 if (keep_fd < start_fd)
120 continue;
121 for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
122 while (close(fd_num) < 0 && errno == EINTR);
123 }
124 start_fd = keep_fd + 1;
125 }
126 if (start_fd <= end_fd) {
127 for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
128 while (close(fd_num) < 0 && errno == EINTR);
129 }
130 }
131}
132
133
134#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
135/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
136 * only to read a directory of short file descriptor number names. The kernel
137 * will return an error if we didn't give it enough space. Highly Unlikely.
138 * This structure is very old and stable: It will not change unless the kernel
139 * chooses to break compatibility with all existing binaries. Highly Unlikely.
140 */
141struct linux_dirent {
142 unsigned long d_ino; /* Inode number */
143 unsigned long d_off; /* Offset to next linux_dirent */
144 unsigned short d_reclen; /* Length of this linux_dirent */
145 char d_name[256]; /* Filename (null-terminated) */
146};
147
148/* Close all open file descriptors in the range start_fd inclusive to end_fd
149 * exclusive. Do not close any in the sorted py_fds_to_keep list.
150 *
151 * This version is async signal safe as it does not make any unsafe C library
152 * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
153 * to resort to making a kernel system call directly but this is the ONLY api
154 * available that does no harm. opendir/readdir/closedir perform memory
155 * allocation and locking so while they usually work they are not guaranteed
156 * to (especially if you have replaced your malloc implementation). A version
157 * of this function that uses those can be found in the _maybe_unsafe variant.
158 *
159 * This is Linux specific because that is all I am ready to test it on. It
160 * should be easy to add OS specific dirent or dirent64 structures and modify
161 * it with some cpp #define magic to work on other OSes as well if you want.
162 */
163static void _close_open_fd_range_safe(int start_fd, int end_fd,
164 PyObject* py_fds_to_keep)
165{
166 int fd_dir_fd;
167 if (start_fd >= end_fd)
168 return;
169 fd_dir_fd = open(LINUX_SOLARIS_FD_DIR, O_RDONLY | O_CLOEXEC, 0);
170 /* Not trying to open the BSD_OSX path as this is currently Linux only. */
171 if (fd_dir_fd == -1) {
172 /* No way to get a list of open fds. */
173 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
174 return;
175 } else {
176 char buffer[sizeof(struct linux_dirent)];
177 int bytes;
178 while ((bytes = syscall(SYS_getdents, fd_dir_fd,
179 (struct linux_dirent *)buffer,
180 sizeof(buffer))) > 0) {
181 struct linux_dirent *entry;
182 int offset;
183 for (offset = 0; offset < bytes; offset += entry->d_reclen) {
184 int fd;
185 entry = (struct linux_dirent *)(buffer + offset);
186 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
187 continue; /* Not a number. */
188 if (fd != fd_dir_fd && fd >= start_fd && fd < end_fd &&
189 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
190 while (close(fd) < 0 && errno == EINTR);
191 }
192 }
193 }
194 close(fd_dir_fd);
195 }
196}
197
198#define _close_open_fd_range _close_open_fd_range_safe
199
200#else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
201
202
203/* Close all open file descriptors in the range start_fd inclusive to end_fd
204 * exclusive. Do not close any in the sorted py_fds_to_keep list.
205 *
206 * This function violates the strict use of async signal safe functions. :(
207 * It calls opendir(), readdir64() and closedir(). Of these, the one most
208 * likely to ever cause a problem is opendir() as it performs an internal
209 * malloc(). Practically this should not be a problem. The Java VM makes the
210 * same calls between fork and exec in its own UNIXProcess_md.c implementation.
211 *
212 * readdir_r() is not used because it provides no benefit. It is typically
213 * implemented as readdir() followed by memcpy(). See also:
214 * http://womble.decadent.org.uk/readdir_r-advisory.html
215 */
216static void _close_open_fd_range_maybe_unsafe(int start_fd, int end_fd,
217 PyObject* py_fds_to_keep)
218{
219 DIR *proc_fd_dir;
220#ifndef HAVE_DIRFD
221 while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep) &&
222 (start_fd < end_fd)) {
223 ++start_fd;
224 }
225 if (start_fd >= end_fd)
226 return;
227 /* Close our lowest fd before we call opendir so that it is likely to
228 * reuse that fd otherwise we might close opendir's file descriptor in
229 * our loop. This trick assumes that fd's are allocated on a lowest
230 * available basis. */
231 while (close(start_fd) < 0 && errno == EINTR);
232 ++start_fd;
233#endif
234 if (start_fd >= end_fd)
235 return;
236
237 proc_fd_dir = opendir(BSD_OSX_FD_DIR);
238 if (!proc_fd_dir)
239 proc_fd_dir = opendir(LINUX_SOLARIS_FD_DIR);
240 if (!proc_fd_dir) {
241 /* No way to get a list of open fds. */
242 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
243 } else {
244 struct dirent64 *dir_entry;
245#ifdef HAVE_DIRFD
246 int fd_used_by_opendir = DIRFD(proc_fd_dir);
247#else
248 int fd_used_by_opendir = start_fd - 1;
249#endif
250 errno = 0;
251 /* readdir64 is used to work around Solaris 9 bug 6395699. */
252 while ((dir_entry = readdir64(proc_fd_dir))) {
253 int fd;
254 if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
255 continue; /* Not a number. */
256 if (fd != fd_used_by_opendir && fd >= start_fd && fd < end_fd &&
257 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
258 while (close(fd) < 0 && errno == EINTR);
259 }
260 errno = 0;
261 }
262 if (errno) {
263 /* readdir error, revert behavior. Highly Unlikely. */
264 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
265 }
266 closedir(proc_fd_dir);
267 }
268}
269
270#define _close_open_fd_range _close_open_fd_range_maybe_unsafe
271
272#endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
273
274
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000275/*
276 * This function is code executed in the child process immediately after fork
277 * to set things up and call exec().
278 *
279 * All of the code in this function must only use async-signal-safe functions,
280 * listed at `man 7 signal` or
281 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
282 *
283 * This restriction is documented at
284 * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
285 */
286static void child_exec(char *const exec_array[],
287 char *const argv[],
288 char *const envp[],
289 const char *cwd,
290 int p2cread, int p2cwrite,
291 int c2pread, int c2pwrite,
292 int errread, int errwrite,
293 int errpipe_read, int errpipe_write,
294 int close_fds, int restore_signals,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800295 int call_setsid,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000296 PyObject *py_fds_to_keep,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000297 PyObject *preexec_fn,
298 PyObject *preexec_fn_args_tuple)
299{
Gregory P. Smith8facece2012-01-21 14:01:08 -0800300 int i, saved_errno, unused;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000301 PyObject *result;
Gregory P. Smith14affb82010-12-22 05:22:17 +0000302 const char* err_msg = "";
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000303 /* Buffer large enough to hold a hex integer. We can't malloc. */
304 char hex_errno[sizeof(saved_errno)*2+1];
305
306 /* Close parent's pipe ends. */
307 if (p2cwrite != -1) {
308 POSIX_CALL(close(p2cwrite));
309 }
310 if (c2pread != -1) {
311 POSIX_CALL(close(c2pread));
312 }
313 if (errread != -1) {
314 POSIX_CALL(close(errread));
315 }
316 POSIX_CALL(close(errpipe_read));
317
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200318 /* When duping fds, if there arises a situation where one of the fds is
319 either 0, 1 or 2, it is possible that it is overwritten (#12607). */
320 if (c2pwrite == 0)
321 POSIX_CALL(c2pwrite = dup(c2pwrite));
322 if (errwrite == 0 || errwrite == 1)
323 POSIX_CALL(errwrite = dup(errwrite));
324
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000325 /* Dup fds for child.
326 dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
327 would be a no-op (issue #10806). */
328 if (p2cread == 0) {
329 int old = fcntl(p2cread, F_GETFD);
330 if (old != -1)
331 fcntl(p2cread, F_SETFD, old & ~FD_CLOEXEC);
332 } else if (p2cread != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000333 POSIX_CALL(dup2(p2cread, 0)); /* stdin */
334 }
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000335 if (c2pwrite == 1) {
336 int old = fcntl(c2pwrite, F_GETFD);
337 if (old != -1)
338 fcntl(c2pwrite, F_SETFD, old & ~FD_CLOEXEC);
339 } else if (c2pwrite != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000340 POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
341 }
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000342 if (errwrite == 2) {
343 int old = fcntl(errwrite, F_GETFD);
344 if (old != -1)
345 fcntl(errwrite, F_SETFD, old & ~FD_CLOEXEC);
346 } else if (errwrite != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000347 POSIX_CALL(dup2(errwrite, 2)); /* stderr */
348 }
349
350 /* Close pipe fds. Make sure we don't close the same fd more than */
351 /* once, or standard fds. */
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000352 if (p2cread > 2) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000353 POSIX_CALL(close(p2cread));
354 }
Gregory P. Smith9c4f44f2011-03-15 14:56:39 -0400355 if (c2pwrite > 2 && c2pwrite != p2cread) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000356 POSIX_CALL(close(c2pwrite));
357 }
Gregory P. Smith9c4f44f2011-03-15 14:56:39 -0400358 if (errwrite != c2pwrite && errwrite != p2cread && errwrite > 2) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000359 POSIX_CALL(close(errwrite));
360 }
361
Gregory P. Smith8facece2012-01-21 14:01:08 -0800362 if (close_fds)
363 _close_open_fd_range(3, max_fd, py_fds_to_keep);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000364
365 if (cwd)
366 POSIX_CALL(chdir(cwd));
367
368 if (restore_signals)
369 _Py_RestoreSignals();
370
371#ifdef HAVE_SETSID
372 if (call_setsid)
373 POSIX_CALL(setsid());
374#endif
375
376 if (preexec_fn != Py_None && preexec_fn_args_tuple) {
377 /* This is where the user has asked us to deadlock their program. */
378 result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
379 if (result == NULL) {
380 /* Stringifying the exception or traceback would involve
381 * memory allocation and thus potential for deadlock.
382 * We've already faced potential deadlock by calling back
383 * into Python in the first place, so it probably doesn't
384 * matter but we avoid it to minimize the possibility. */
385 err_msg = "Exception occurred in preexec_fn.";
386 errno = 0; /* We don't want to report an OSError. */
387 goto error;
388 }
389 /* Py_DECREF(result); - We're about to exec so why bother? */
390 }
391
392 /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
393 /* given the executable_list generated by Lib/subprocess.py. */
394 saved_errno = 0;
395 for (i = 0; exec_array[i] != NULL; ++i) {
396 const char *executable = exec_array[i];
397 if (envp) {
398 execve(executable, argv, envp);
399 } else {
400 execv(executable, argv);
401 }
402 if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
403 saved_errno = errno;
404 }
405 }
406 /* Report the first exec error, not the last. */
407 if (saved_errno)
408 errno = saved_errno;
409
410error:
411 saved_errno = errno;
412 /* Report the posix error to our parent process. */
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800413 /* We ignore all write() return values as the total size of our writes is
414 * less than PIPEBUF and we cannot do anything about an error anyways. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000415 if (saved_errno) {
416 char *cur;
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800417 unused = write(errpipe_write, "OSError:", 8);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000418 cur = hex_errno + sizeof(hex_errno);
419 while (saved_errno != 0 && cur > hex_errno) {
420 *--cur = "0123456789ABCDEF"[saved_errno % 16];
421 saved_errno /= 16;
422 }
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800423 unused = write(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
424 unused = write(errpipe_write, ":", 1);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000425 /* We can't call strerror(saved_errno). It is not async signal safe.
426 * The parent process will look the error message up. */
427 } else {
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800428 unused = write(errpipe_write, "RuntimeError:0:", 15);
429 unused = write(errpipe_write, err_msg, strlen(err_msg));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000430 }
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800431 if (unused) return; /* silly? yes! avoids gcc compiler warning. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000432}
433
434
435static PyObject *
436subprocess_fork_exec(PyObject* self, PyObject *args)
437{
438 PyObject *gc_module = NULL;
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000439 PyObject *executable_list, *py_close_fds, *py_fds_to_keep;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000440 PyObject *env_list, *preexec_fn;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000441 PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000442 PyObject *preexec_fn_args_tuple = NULL;
443 int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
444 int errpipe_read, errpipe_write, close_fds, restore_signals;
445 int call_setsid;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000446 PyObject *cwd_obj, *cwd_obj2;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000447 const char *cwd;
448 pid_t pid;
449 int need_to_reenable_gc = 0;
450 char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800451 Py_ssize_t arg_num;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000452
453 if (!PyArg_ParseTuple(
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000454 args, "OOOOOOiiiiiiiiiiO:fork_exec",
455 &process_args, &executable_list, &py_close_fds, &py_fds_to_keep,
Victor Stinner0e59cc32010-04-16 23:49:32 +0000456 &cwd_obj, &env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000457 &p2cread, &p2cwrite, &c2pread, &c2pwrite,
458 &errread, &errwrite, &errpipe_read, &errpipe_write,
459 &restore_signals, &call_setsid, &preexec_fn))
460 return NULL;
461
462 close_fds = PyObject_IsTrue(py_close_fds);
463 if (close_fds && errpipe_write < 3) { /* precondition */
464 PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
465 return NULL;
466 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800467 if (PySequence_Length(py_fds_to_keep) < 0) {
468 PyErr_SetString(PyExc_ValueError, "cannot get length of fds_to_keep");
469 return NULL;
470 }
471 if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
472 PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000473 return NULL;
474 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000475
476 /* We need to call gc.disable() when we'll be calling preexec_fn */
477 if (preexec_fn != Py_None) {
478 PyObject *result;
479 gc_module = PyImport_ImportModule("gc");
480 if (gc_module == NULL)
481 return NULL;
482 result = PyObject_CallMethod(gc_module, "isenabled", NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000483 if (result == NULL) {
484 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000485 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000486 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000487 need_to_reenable_gc = PyObject_IsTrue(result);
488 Py_DECREF(result);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000489 if (need_to_reenable_gc == -1) {
490 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000491 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000492 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000493 result = PyObject_CallMethod(gc_module, "disable", NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000494 if (result == NULL) {
495 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000496 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000497 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000498 Py_DECREF(result);
499 }
500
501 exec_array = _PySequence_BytesToCharpArray(executable_list);
502 if (!exec_array)
503 return NULL;
504
505 /* Convert args and env into appropriate arguments for exec() */
506 /* These conversions are done in the parent process to avoid allocating
507 or freeing memory in the child process. */
508 if (process_args != Py_None) {
Gregory P. Smith68f52172010-03-15 06:07:42 +0000509 Py_ssize_t num_args;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000510 /* Equivalent to: */
511 /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
Gregory P. Smith68f52172010-03-15 06:07:42 +0000512 fast_args = PySequence_Fast(process_args, "argv must be a tuple");
513 num_args = PySequence_Fast_GET_SIZE(fast_args);
514 converted_args = PyTuple_New(num_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000515 if (converted_args == NULL)
516 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000517 for (arg_num = 0; arg_num < num_args; ++arg_num) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000518 PyObject *borrowed_arg, *converted_arg;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000519 borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000520 if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
521 goto cleanup;
522 PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
523 }
524
525 argv = _PySequence_BytesToCharpArray(converted_args);
526 Py_CLEAR(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000527 Py_CLEAR(fast_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000528 if (!argv)
529 goto cleanup;
530 }
531
532 if (env_list != Py_None) {
533 envp = _PySequence_BytesToCharpArray(env_list);
534 if (!envp)
535 goto cleanup;
536 }
537
538 if (preexec_fn != Py_None) {
539 preexec_fn_args_tuple = PyTuple_New(0);
540 if (!preexec_fn_args_tuple)
541 goto cleanup;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000542 _PyImport_AcquireLock();
543 }
544
545 if (cwd_obj != Py_None) {
546 if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
547 goto cleanup;
Victor Stinnerdcb24032010-04-22 12:08:36 +0000548 cwd = PyBytes_AsString(cwd_obj2);
Victor Stinner0e59cc32010-04-16 23:49:32 +0000549 } else {
550 cwd = NULL;
551 cwd_obj2 = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000552 }
553
554 pid = fork();
555 if (pid == 0) {
556 /* Child process */
Victor Stinner0e59cc32010-04-16 23:49:32 +0000557 /*
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000558 * Code from here to _exit() must only use async-signal-safe functions,
559 * listed at `man 7 signal` or
560 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
561 */
562
563 if (preexec_fn != Py_None) {
564 /* We'll be calling back into Python later so we need to do this.
565 * This call may not be async-signal-safe but neither is calling
566 * back into Python. The user asked us to use hope as a strategy
567 * to avoid deadlock... */
568 PyOS_AfterFork();
569 }
570
571 child_exec(exec_array, argv, envp, cwd,
572 p2cread, p2cwrite, c2pread, c2pwrite,
573 errread, errwrite, errpipe_read, errpipe_write,
574 close_fds, restore_signals, call_setsid,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800575 py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000576 _exit(255);
577 return NULL; /* Dead code to avoid a potential compiler warning. */
578 }
Victor Stinner0e59cc32010-04-16 23:49:32 +0000579 Py_XDECREF(cwd_obj2);
580
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000581 if (pid == -1) {
582 /* Capture the errno exception before errno can be clobbered. */
583 PyErr_SetFromErrno(PyExc_OSError);
584 }
585 if (preexec_fn != Py_None &&
586 _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) {
587 PyErr_SetString(PyExc_RuntimeError,
588 "not holding the import lock");
589 }
590
591 /* Parent process */
592 if (envp)
593 _Py_FreeCharPArray(envp);
594 if (argv)
595 _Py_FreeCharPArray(argv);
596 _Py_FreeCharPArray(exec_array);
597
598 /* Reenable gc in the parent process (or if fork failed). */
599 if (need_to_reenable_gc && _enable_gc(gc_module)) {
600 Py_XDECREF(gc_module);
601 return NULL;
602 }
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000603 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000604 Py_XDECREF(gc_module);
605
606 if (pid == -1)
607 return NULL; /* fork() failed. Exception set earlier. */
608
609 return PyLong_FromPid(pid);
610
611cleanup:
612 if (envp)
613 _Py_FreeCharPArray(envp);
614 if (argv)
615 _Py_FreeCharPArray(argv);
616 _Py_FreeCharPArray(exec_array);
617 Py_XDECREF(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000618 Py_XDECREF(fast_args);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000619 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000620
621 /* Reenable gc if it was disabled. */
622 if (need_to_reenable_gc)
623 _enable_gc(gc_module);
624 Py_XDECREF(gc_module);
625 return NULL;
626}
627
628
629PyDoc_STRVAR(subprocess_fork_exec_doc,
630"fork_exec(args, executable_list, close_fds, cwd, env,\n\
631 p2cread, p2cwrite, c2pread, c2pwrite,\n\
632 errread, errwrite, errpipe_read, errpipe_write,\n\
633 restore_signals, call_setsid, preexec_fn)\n\
634\n\
635Forks a child process, closes parent file descriptors as appropriate in the\n\
636child and dups the few that are needed before calling exec() in the child\n\
637process.\n\
638\n\
639The preexec_fn, if supplied, will be called immediately before exec.\n\
640WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
641 It may trigger infrequent, difficult to debug deadlocks.\n\
642\n\
643If an error occurs in the child process before the exec, it is\n\
644serialized and written to the errpipe_write fd per subprocess.py.\n\
645\n\
646Returns: the child process's PID.\n\
647\n\
648Raises: Only on an error in the parent process.\n\
649");
650
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000651PyDoc_STRVAR(subprocess_cloexec_pipe_doc,
652"cloexec_pipe() -> (read_end, write_end)\n\n\
653Create a pipe whose ends have the cloexec flag set.");
654
655static PyObject *
656subprocess_cloexec_pipe(PyObject *self, PyObject *noargs)
657{
658 int fds[2];
659 int res;
660#ifdef HAVE_PIPE2
661 Py_BEGIN_ALLOW_THREADS
662 res = pipe2(fds, O_CLOEXEC);
663 Py_END_ALLOW_THREADS
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000664 if (res != 0 && errno == ENOSYS)
665 {
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000666 {
667#endif
668 /* We hold the GIL which offers some protection from other code calling
669 * fork() before the CLOEXEC flags have been set but we can't guarantee
670 * anything without pipe2(). */
671 long oldflags;
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000672
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000673 res = pipe(fds);
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000674
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000675 if (res == 0) {
676 oldflags = fcntl(fds[0], F_GETFD, 0);
677 if (oldflags < 0) res = oldflags;
678 }
679 if (res == 0)
680 res = fcntl(fds[0], F_SETFD, oldflags | FD_CLOEXEC);
681
682 if (res == 0) {
683 oldflags = fcntl(fds[1], F_GETFD, 0);
684 if (oldflags < 0) res = oldflags;
685 }
686 if (res == 0)
687 res = fcntl(fds[1], F_SETFD, oldflags | FD_CLOEXEC);
688#ifdef HAVE_PIPE2
689 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000690 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000691#endif
692 if (res != 0)
693 return PyErr_SetFromErrno(PyExc_OSError);
694 return Py_BuildValue("(ii)", fds[0], fds[1]);
695}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000696
697/* module level code ********************************************************/
698
699PyDoc_STRVAR(module_doc,
700"A POSIX helper for the subprocess module.");
701
702
703static PyMethodDef module_methods[] = {
704 {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000705 {"cloexec_pipe", subprocess_cloexec_pipe, METH_NOARGS, subprocess_cloexec_pipe_doc},
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000706 {NULL, NULL} /* sentinel */
707};
708
709
710static struct PyModuleDef _posixsubprocessmodule = {
711 PyModuleDef_HEAD_INIT,
712 "_posixsubprocess",
713 module_doc,
714 -1, /* No memory is needed. */
715 module_methods,
716};
717
718PyMODINIT_FUNC
719PyInit__posixsubprocess(void)
720{
721#ifdef _SC_OPEN_MAX
722 max_fd = sysconf(_SC_OPEN_MAX);
723 if (max_fd == -1)
724#endif
725 max_fd = 256; /* Matches Lib/subprocess.py */
726
727 return PyModule_Create(&_posixsubprocessmodule);
728}