blob: 27112437017d97a766f393c7a353dcc71f25a4ec [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. 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;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020040 _Py_IDENTIFIER(enable);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020041
42 result = _PyObject_CallMethodId(gc_module, &PyId_enable, NULL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000043 if (result == NULL)
44 return 1;
45 Py_DECREF(result);
46 return 0;
47}
48
49
Gregory P. Smith8facece2012-01-21 14:01:08 -080050/* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
51static int _pos_int_from_ascii(char *name)
52{
53 int num = 0;
54 while (*name >= '0' && *name <= '9') {
55 num = num * 10 + (*name - '0');
56 ++name;
57 }
58 if (*name)
59 return -1; /* Non digit found, not a number. */
60 return num;
61}
62
63
64/* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
65static int _sanity_check_python_fd_sequence(PyObject *fd_sequence)
66{
67 Py_ssize_t seq_idx, seq_len = PySequence_Length(fd_sequence);
68 long prev_fd = -1;
69 for (seq_idx = 0; seq_idx < seq_len; ++seq_idx) {
70 PyObject* py_fd = PySequence_Fast_GET_ITEM(fd_sequence, seq_idx);
71 long iter_fd = PyLong_AsLong(py_fd);
72 if (iter_fd < 0 || iter_fd < prev_fd || iter_fd > INT_MAX) {
73 /* Negative, overflow, not a Long, unsorted, too big for a fd. */
74 return 1;
75 }
76 }
77 return 0;
78}
79
80
81/* Is fd found in the sorted Python Sequence? */
82static int _is_fd_in_sorted_fd_sequence(int fd, PyObject *fd_sequence)
83{
84 /* Binary search. */
85 Py_ssize_t search_min = 0;
86 Py_ssize_t search_max = PySequence_Length(fd_sequence) - 1;
87 if (search_max < 0)
88 return 0;
89 do {
90 long middle = (search_min + search_max) / 2;
91 long middle_fd = PyLong_AsLong(
92 PySequence_Fast_GET_ITEM(fd_sequence, middle));
93 if (fd == middle_fd)
94 return 1;
95 if (fd > middle_fd)
96 search_min = middle + 1;
97 else
98 search_max = middle - 1;
99 } while (search_min <= search_max);
100 return 0;
101}
102
103
104/* Close all file descriptors in the range start_fd inclusive to
105 * end_fd exclusive except for those in py_fds_to_keep. If the
106 * range defined by [start_fd, end_fd) is large this will take a
107 * long time as it calls close() on EVERY possible fd.
108 */
109static void _close_fds_by_brute_force(int start_fd, int end_fd,
110 PyObject *py_fds_to_keep)
111{
112 Py_ssize_t num_fds_to_keep = PySequence_Length(py_fds_to_keep);
113 Py_ssize_t keep_seq_idx;
114 int fd_num;
115 /* As py_fds_to_keep is sorted we can loop through the list closing
116 * fds inbetween any in the keep list falling within our range. */
117 for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
118 PyObject* py_keep_fd = PySequence_Fast_GET_ITEM(py_fds_to_keep,
119 keep_seq_idx);
120 int keep_fd = PyLong_AsLong(py_keep_fd);
121 if (keep_fd < start_fd)
122 continue;
123 for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
124 while (close(fd_num) < 0 && errno == EINTR);
125 }
126 start_fd = keep_fd + 1;
127 }
128 if (start_fd <= end_fd) {
129 for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
130 while (close(fd_num) < 0 && errno == EINTR);
131 }
132 }
133}
134
135
136#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
137/* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
138 * only to read a directory of short file descriptor number names. The kernel
139 * will return an error if we didn't give it enough space. Highly Unlikely.
140 * This structure is very old and stable: It will not change unless the kernel
141 * chooses to break compatibility with all existing binaries. Highly Unlikely.
142 */
143struct linux_dirent {
144 unsigned long d_ino; /* Inode number */
145 unsigned long d_off; /* Offset to next linux_dirent */
146 unsigned short d_reclen; /* Length of this linux_dirent */
147 char d_name[256]; /* Filename (null-terminated) */
148};
149
150/* Close all open file descriptors in the range start_fd inclusive to end_fd
151 * exclusive. Do not close any in the sorted py_fds_to_keep list.
152 *
153 * This version is async signal safe as it does not make any unsafe C library
154 * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
155 * to resort to making a kernel system call directly but this is the ONLY api
156 * available that does no harm. opendir/readdir/closedir perform memory
157 * allocation and locking so while they usually work they are not guaranteed
158 * to (especially if you have replaced your malloc implementation). A version
159 * of this function that uses those can be found in the _maybe_unsafe variant.
160 *
161 * This is Linux specific because that is all I am ready to test it on. It
162 * should be easy to add OS specific dirent or dirent64 structures and modify
163 * it with some cpp #define magic to work on other OSes as well if you want.
164 */
165static void _close_open_fd_range_safe(int start_fd, int end_fd,
166 PyObject* py_fds_to_keep)
167{
168 int fd_dir_fd;
169 if (start_fd >= end_fd)
170 return;
171 fd_dir_fd = open(LINUX_SOLARIS_FD_DIR, O_RDONLY | O_CLOEXEC, 0);
172 /* Not trying to open the BSD_OSX path as this is currently Linux only. */
173 if (fd_dir_fd == -1) {
174 /* No way to get a list of open fds. */
175 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
176 return;
177 } else {
178 char buffer[sizeof(struct linux_dirent)];
179 int bytes;
180 while ((bytes = syscall(SYS_getdents, fd_dir_fd,
181 (struct linux_dirent *)buffer,
182 sizeof(buffer))) > 0) {
183 struct linux_dirent *entry;
184 int offset;
185 for (offset = 0; offset < bytes; offset += entry->d_reclen) {
186 int fd;
187 entry = (struct linux_dirent *)(buffer + offset);
188 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
189 continue; /* Not a number. */
190 if (fd != fd_dir_fd && fd >= start_fd && fd < end_fd &&
191 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
192 while (close(fd) < 0 && errno == EINTR);
193 }
194 }
195 }
196 close(fd_dir_fd);
197 }
198}
199
200#define _close_open_fd_range _close_open_fd_range_safe
201
202#else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
203
204
205/* Close all open file descriptors in the range start_fd inclusive to end_fd
206 * exclusive. Do not close any in the sorted py_fds_to_keep list.
207 *
208 * This function violates the strict use of async signal safe functions. :(
209 * It calls opendir(), readdir64() and closedir(). Of these, the one most
210 * likely to ever cause a problem is opendir() as it performs an internal
211 * malloc(). Practically this should not be a problem. The Java VM makes the
212 * same calls between fork and exec in its own UNIXProcess_md.c implementation.
213 *
214 * readdir_r() is not used because it provides no benefit. It is typically
215 * implemented as readdir() followed by memcpy(). See also:
216 * http://womble.decadent.org.uk/readdir_r-advisory.html
217 */
218static void _close_open_fd_range_maybe_unsafe(int start_fd, int end_fd,
219 PyObject* py_fds_to_keep)
220{
221 DIR *proc_fd_dir;
222#ifndef HAVE_DIRFD
223 while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep) &&
224 (start_fd < end_fd)) {
225 ++start_fd;
226 }
227 if (start_fd >= end_fd)
228 return;
229 /* Close our lowest fd before we call opendir so that it is likely to
230 * reuse that fd otherwise we might close opendir's file descriptor in
231 * our loop. This trick assumes that fd's are allocated on a lowest
232 * available basis. */
233 while (close(start_fd) < 0 && errno == EINTR);
234 ++start_fd;
235#endif
236 if (start_fd >= end_fd)
237 return;
238
239 proc_fd_dir = opendir(BSD_OSX_FD_DIR);
240 if (!proc_fd_dir)
241 proc_fd_dir = opendir(LINUX_SOLARIS_FD_DIR);
242 if (!proc_fd_dir) {
243 /* No way to get a list of open fds. */
244 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
245 } else {
246 struct dirent64 *dir_entry;
247#ifdef HAVE_DIRFD
248 int fd_used_by_opendir = DIRFD(proc_fd_dir);
249#else
250 int fd_used_by_opendir = start_fd - 1;
251#endif
252 errno = 0;
253 /* readdir64 is used to work around Solaris 9 bug 6395699. */
254 while ((dir_entry = readdir64(proc_fd_dir))) {
255 int fd;
256 if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
257 continue; /* Not a number. */
258 if (fd != fd_used_by_opendir && fd >= start_fd && fd < end_fd &&
259 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep)) {
260 while (close(fd) < 0 && errno == EINTR);
261 }
262 errno = 0;
263 }
264 if (errno) {
265 /* readdir error, revert behavior. Highly Unlikely. */
266 _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep);
267 }
268 closedir(proc_fd_dir);
269 }
270}
271
272#define _close_open_fd_range _close_open_fd_range_maybe_unsafe
273
274#endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
275
276
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000277/*
278 * This function is code executed in the child process immediately after fork
279 * to set things up and call exec().
280 *
281 * All of the code in this function must only use async-signal-safe functions,
282 * listed at `man 7 signal` or
283 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
284 *
285 * This restriction is documented at
286 * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
287 */
288static void child_exec(char *const exec_array[],
289 char *const argv[],
290 char *const envp[],
291 const char *cwd,
292 int p2cread, int p2cwrite,
293 int c2pread, int c2pwrite,
294 int errread, int errwrite,
295 int errpipe_read, int errpipe_write,
296 int close_fds, int restore_signals,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800297 int call_setsid,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000298 PyObject *py_fds_to_keep,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000299 PyObject *preexec_fn,
300 PyObject *preexec_fn_args_tuple)
301{
Gregory P. Smith8facece2012-01-21 14:01:08 -0800302 int i, saved_errno, unused;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000303 PyObject *result;
Gregory P. Smith14affb82010-12-22 05:22:17 +0000304 const char* err_msg = "";
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000305 /* Buffer large enough to hold a hex integer. We can't malloc. */
306 char hex_errno[sizeof(saved_errno)*2+1];
307
308 /* Close parent's pipe ends. */
309 if (p2cwrite != -1) {
310 POSIX_CALL(close(p2cwrite));
311 }
312 if (c2pread != -1) {
313 POSIX_CALL(close(c2pread));
314 }
315 if (errread != -1) {
316 POSIX_CALL(close(errread));
317 }
318 POSIX_CALL(close(errpipe_read));
319
Ross Lagerwalld98646e2011-07-27 07:16:31 +0200320 /* When duping fds, if there arises a situation where one of the fds is
321 either 0, 1 or 2, it is possible that it is overwritten (#12607). */
322 if (c2pwrite == 0)
323 POSIX_CALL(c2pwrite = dup(c2pwrite));
324 if (errwrite == 0 || errwrite == 1)
325 POSIX_CALL(errwrite = dup(errwrite));
326
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000327 /* Dup fds for child.
328 dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
329 would be a no-op (issue #10806). */
330 if (p2cread == 0) {
331 int old = fcntl(p2cread, F_GETFD);
332 if (old != -1)
333 fcntl(p2cread, F_SETFD, old & ~FD_CLOEXEC);
334 } else if (p2cread != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000335 POSIX_CALL(dup2(p2cread, 0)); /* stdin */
336 }
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000337 if (c2pwrite == 1) {
338 int old = fcntl(c2pwrite, F_GETFD);
339 if (old != -1)
340 fcntl(c2pwrite, F_SETFD, old & ~FD_CLOEXEC);
341 } else if (c2pwrite != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000342 POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
343 }
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000344 if (errwrite == 2) {
345 int old = fcntl(errwrite, F_GETFD);
346 if (old != -1)
347 fcntl(errwrite, F_SETFD, old & ~FD_CLOEXEC);
348 } else if (errwrite != -1) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000349 POSIX_CALL(dup2(errwrite, 2)); /* stderr */
350 }
351
352 /* Close pipe fds. Make sure we don't close the same fd more than */
353 /* once, or standard fds. */
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000354 if (p2cread > 2) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000355 POSIX_CALL(close(p2cread));
356 }
Gregory P. Smith81218982011-03-15 14:56:39 -0400357 if (c2pwrite > 2 && c2pwrite != p2cread) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000358 POSIX_CALL(close(c2pwrite));
359 }
Gregory P. Smith81218982011-03-15 14:56:39 -0400360 if (errwrite != c2pwrite && errwrite != p2cread && errwrite > 2) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000361 POSIX_CALL(close(errwrite));
362 }
363
Gregory P. Smith8facece2012-01-21 14:01:08 -0800364 if (close_fds)
365 _close_open_fd_range(3, max_fd, py_fds_to_keep);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000366
367 if (cwd)
368 POSIX_CALL(chdir(cwd));
369
370 if (restore_signals)
371 _Py_RestoreSignals();
372
373#ifdef HAVE_SETSID
374 if (call_setsid)
375 POSIX_CALL(setsid());
376#endif
377
378 if (preexec_fn != Py_None && preexec_fn_args_tuple) {
379 /* This is where the user has asked us to deadlock their program. */
380 result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
381 if (result == NULL) {
382 /* Stringifying the exception or traceback would involve
383 * memory allocation and thus potential for deadlock.
384 * We've already faced potential deadlock by calling back
385 * into Python in the first place, so it probably doesn't
386 * matter but we avoid it to minimize the possibility. */
387 err_msg = "Exception occurred in preexec_fn.";
388 errno = 0; /* We don't want to report an OSError. */
389 goto error;
390 }
391 /* Py_DECREF(result); - We're about to exec so why bother? */
392 }
393
394 /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
395 /* given the executable_list generated by Lib/subprocess.py. */
396 saved_errno = 0;
397 for (i = 0; exec_array[i] != NULL; ++i) {
398 const char *executable = exec_array[i];
399 if (envp) {
400 execve(executable, argv, envp);
401 } else {
402 execv(executable, argv);
403 }
404 if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
405 saved_errno = errno;
406 }
407 }
408 /* Report the first exec error, not the last. */
409 if (saved_errno)
410 errno = saved_errno;
411
412error:
413 saved_errno = errno;
414 /* Report the posix error to our parent process. */
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800415 /* We ignore all write() return values as the total size of our writes is
416 * less than PIPEBUF and we cannot do anything about an error anyways. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000417 if (saved_errno) {
418 char *cur;
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800419 unused = write(errpipe_write, "OSError:", 8);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000420 cur = hex_errno + sizeof(hex_errno);
421 while (saved_errno != 0 && cur > hex_errno) {
422 *--cur = "0123456789ABCDEF"[saved_errno % 16];
423 saved_errno /= 16;
424 }
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800425 unused = write(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
426 unused = write(errpipe_write, ":", 1);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000427 /* We can't call strerror(saved_errno). It is not async signal safe.
428 * The parent process will look the error message up. */
429 } else {
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800430 unused = write(errpipe_write, "RuntimeError:0:", 15);
431 unused = write(errpipe_write, err_msg, strlen(err_msg));
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000432 }
Gregory P. Smith12fdca52012-01-21 12:31:25 -0800433 if (unused) return; /* silly? yes! avoids gcc compiler warning. */
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000434}
435
436
437static PyObject *
438subprocess_fork_exec(PyObject* self, PyObject *args)
439{
440 PyObject *gc_module = NULL;
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000441 PyObject *executable_list, *py_close_fds, *py_fds_to_keep;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000442 PyObject *env_list, *preexec_fn;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000443 PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000444 PyObject *preexec_fn_args_tuple = NULL;
445 int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
446 int errpipe_read, errpipe_write, close_fds, restore_signals;
447 int call_setsid;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000448 PyObject *cwd_obj, *cwd_obj2;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000449 const char *cwd;
450 pid_t pid;
451 int need_to_reenable_gc = 0;
452 char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
Gregory P. Smith8facece2012-01-21 14:01:08 -0800453 Py_ssize_t arg_num;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000454
455 if (!PyArg_ParseTuple(
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000456 args, "OOOOOOiiiiiiiiiiO:fork_exec",
457 &process_args, &executable_list, &py_close_fds, &py_fds_to_keep,
Victor Stinner0e59cc32010-04-16 23:49:32 +0000458 &cwd_obj, &env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000459 &p2cread, &p2cwrite, &c2pread, &c2pwrite,
460 &errread, &errwrite, &errpipe_read, &errpipe_write,
461 &restore_signals, &call_setsid, &preexec_fn))
462 return NULL;
463
464 close_fds = PyObject_IsTrue(py_close_fds);
465 if (close_fds && errpipe_write < 3) { /* precondition */
466 PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
467 return NULL;
468 }
Gregory P. Smith8facece2012-01-21 14:01:08 -0800469 if (PySequence_Length(py_fds_to_keep) < 0) {
470 PyErr_SetString(PyExc_ValueError, "cannot get length of fds_to_keep");
471 return NULL;
472 }
473 if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
474 PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000475 return NULL;
476 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000477
478 /* We need to call gc.disable() when we'll be calling preexec_fn */
479 if (preexec_fn != Py_None) {
480 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200481 _Py_IDENTIFIER(isenabled);
482 _Py_IDENTIFIER(disable);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200483
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000484 gc_module = PyImport_ImportModule("gc");
485 if (gc_module == NULL)
486 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200487 result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000488 if (result == NULL) {
489 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000490 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000491 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000492 need_to_reenable_gc = PyObject_IsTrue(result);
493 Py_DECREF(result);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000494 if (need_to_reenable_gc == -1) {
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 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200498 result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000499 if (result == NULL) {
500 Py_DECREF(gc_module);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000501 return NULL;
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000502 }
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000503 Py_DECREF(result);
504 }
505
506 exec_array = _PySequence_BytesToCharpArray(executable_list);
507 if (!exec_array)
508 return NULL;
509
510 /* Convert args and env into appropriate arguments for exec() */
511 /* These conversions are done in the parent process to avoid allocating
512 or freeing memory in the child process. */
513 if (process_args != Py_None) {
Gregory P. Smith68f52172010-03-15 06:07:42 +0000514 Py_ssize_t num_args;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000515 /* Equivalent to: */
516 /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
Gregory P. Smith68f52172010-03-15 06:07:42 +0000517 fast_args = PySequence_Fast(process_args, "argv must be a tuple");
518 num_args = PySequence_Fast_GET_SIZE(fast_args);
519 converted_args = PyTuple_New(num_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000520 if (converted_args == NULL)
521 goto cleanup;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000522 for (arg_num = 0; arg_num < num_args; ++arg_num) {
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000523 PyObject *borrowed_arg, *converted_arg;
Gregory P. Smith68f52172010-03-15 06:07:42 +0000524 borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000525 if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
526 goto cleanup;
527 PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
528 }
529
530 argv = _PySequence_BytesToCharpArray(converted_args);
531 Py_CLEAR(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000532 Py_CLEAR(fast_args);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000533 if (!argv)
534 goto cleanup;
535 }
536
537 if (env_list != Py_None) {
538 envp = _PySequence_BytesToCharpArray(env_list);
539 if (!envp)
540 goto cleanup;
541 }
542
543 if (preexec_fn != Py_None) {
544 preexec_fn_args_tuple = PyTuple_New(0);
545 if (!preexec_fn_args_tuple)
546 goto cleanup;
Victor Stinner0e59cc32010-04-16 23:49:32 +0000547 _PyImport_AcquireLock();
548 }
549
550 if (cwd_obj != Py_None) {
551 if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
552 goto cleanup;
Victor Stinnerdcb24032010-04-22 12:08:36 +0000553 cwd = PyBytes_AsString(cwd_obj2);
Victor Stinner0e59cc32010-04-16 23:49:32 +0000554 } else {
555 cwd = NULL;
556 cwd_obj2 = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000557 }
558
559 pid = fork();
560 if (pid == 0) {
561 /* Child process */
Victor Stinner0e59cc32010-04-16 23:49:32 +0000562 /*
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000563 * Code from here to _exit() must only use async-signal-safe functions,
564 * listed at `man 7 signal` or
565 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
566 */
567
568 if (preexec_fn != Py_None) {
569 /* We'll be calling back into Python later so we need to do this.
570 * This call may not be async-signal-safe but neither is calling
571 * back into Python. The user asked us to use hope as a strategy
572 * to avoid deadlock... */
573 PyOS_AfterFork();
574 }
575
576 child_exec(exec_array, argv, envp, cwd,
577 p2cread, p2cwrite, c2pread, c2pwrite,
578 errread, errwrite, errpipe_read, errpipe_write,
579 close_fds, restore_signals, call_setsid,
Gregory P. Smith8facece2012-01-21 14:01:08 -0800580 py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000581 _exit(255);
582 return NULL; /* Dead code to avoid a potential compiler warning. */
583 }
Victor Stinner0e59cc32010-04-16 23:49:32 +0000584 Py_XDECREF(cwd_obj2);
585
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000586 if (pid == -1) {
587 /* Capture the errno exception before errno can be clobbered. */
588 PyErr_SetFromErrno(PyExc_OSError);
589 }
590 if (preexec_fn != Py_None &&
591 _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) {
592 PyErr_SetString(PyExc_RuntimeError,
593 "not holding the import lock");
594 }
595
596 /* Parent process */
597 if (envp)
598 _Py_FreeCharPArray(envp);
599 if (argv)
600 _Py_FreeCharPArray(argv);
601 _Py_FreeCharPArray(exec_array);
602
603 /* Reenable gc in the parent process (or if fork failed). */
604 if (need_to_reenable_gc && _enable_gc(gc_module)) {
605 Py_XDECREF(gc_module);
606 return NULL;
607 }
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000608 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000609 Py_XDECREF(gc_module);
610
611 if (pid == -1)
612 return NULL; /* fork() failed. Exception set earlier. */
613
614 return PyLong_FromPid(pid);
615
616cleanup:
617 if (envp)
618 _Py_FreeCharPArray(envp);
619 if (argv)
620 _Py_FreeCharPArray(argv);
621 _Py_FreeCharPArray(exec_array);
622 Py_XDECREF(converted_args);
Gregory P. Smith68f52172010-03-15 06:07:42 +0000623 Py_XDECREF(fast_args);
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000624 Py_XDECREF(preexec_fn_args_tuple);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000625
626 /* Reenable gc if it was disabled. */
627 if (need_to_reenable_gc)
628 _enable_gc(gc_module);
629 Py_XDECREF(gc_module);
630 return NULL;
631}
632
633
634PyDoc_STRVAR(subprocess_fork_exec_doc,
635"fork_exec(args, executable_list, close_fds, cwd, env,\n\
636 p2cread, p2cwrite, c2pread, c2pwrite,\n\
637 errread, errwrite, errpipe_read, errpipe_write,\n\
638 restore_signals, call_setsid, preexec_fn)\n\
639\n\
640Forks a child process, closes parent file descriptors as appropriate in the\n\
641child and dups the few that are needed before calling exec() in the child\n\
642process.\n\
643\n\
644The preexec_fn, if supplied, will be called immediately before exec.\n\
645WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\
646 It may trigger infrequent, difficult to debug deadlocks.\n\
647\n\
648If an error occurs in the child process before the exec, it is\n\
649serialized and written to the errpipe_write fd per subprocess.py.\n\
650\n\
651Returns: the child process's PID.\n\
652\n\
653Raises: Only on an error in the parent process.\n\
654");
655
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000656PyDoc_STRVAR(subprocess_cloexec_pipe_doc,
657"cloexec_pipe() -> (read_end, write_end)\n\n\
658Create a pipe whose ends have the cloexec flag set.");
659
660static PyObject *
661subprocess_cloexec_pipe(PyObject *self, PyObject *noargs)
662{
663 int fds[2];
664 int res;
665#ifdef HAVE_PIPE2
666 Py_BEGIN_ALLOW_THREADS
667 res = pipe2(fds, O_CLOEXEC);
668 Py_END_ALLOW_THREADS
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000669 if (res != 0 && errno == ENOSYS)
670 {
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000671 {
672#endif
673 /* We hold the GIL which offers some protection from other code calling
674 * fork() before the CLOEXEC flags have been set but we can't guarantee
675 * anything without pipe2(). */
676 long oldflags;
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000677
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000678 res = pipe(fds);
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000679
Gregory P. Smithabcfcba2011-01-02 20:52:48 +0000680 if (res == 0) {
681 oldflags = fcntl(fds[0], F_GETFD, 0);
682 if (oldflags < 0) res = oldflags;
683 }
684 if (res == 0)
685 res = fcntl(fds[0], F_SETFD, oldflags | FD_CLOEXEC);
686
687 if (res == 0) {
688 oldflags = fcntl(fds[1], F_GETFD, 0);
689 if (oldflags < 0) res = oldflags;
690 }
691 if (res == 0)
692 res = fcntl(fds[1], F_SETFD, oldflags | FD_CLOEXEC);
693#ifdef HAVE_PIPE2
694 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000695 }
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000696#endif
697 if (res != 0)
698 return PyErr_SetFromErrno(PyExc_OSError);
699 return Py_BuildValue("(ii)", fds[0], fds[1]);
700}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000701
702/* module level code ********************************************************/
703
704PyDoc_STRVAR(module_doc,
705"A POSIX helper for the subprocess module.");
706
707
708static PyMethodDef module_methods[] = {
709 {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000710 {"cloexec_pipe", subprocess_cloexec_pipe, METH_NOARGS, subprocess_cloexec_pipe_doc},
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000711 {NULL, NULL} /* sentinel */
712};
713
714
715static struct PyModuleDef _posixsubprocessmodule = {
716 PyModuleDef_HEAD_INIT,
717 "_posixsubprocess",
718 module_doc,
719 -1, /* No memory is needed. */
720 module_methods,
721};
722
723PyMODINIT_FUNC
724PyInit__posixsubprocess(void)
725{
726#ifdef _SC_OPEN_MAX
727 max_fd = sysconf(_SC_OPEN_MAX);
728 if (max_fd == -1)
729#endif
730 max_fd = 256; /* Matches Lib/subprocess.py */
731
732 return PyModule_Create(&_posixsubprocessmodule);
733}