Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1 | /* Authors: Gregory P. Smith & Jeffrey Yasskin */ |
| 2 | #include "Python.h" |
Victor Stinner | 5572ba7 | 2011-05-26 14:10:08 +0200 | [diff] [blame] | 3 | #if defined(HAVE_PIPE2) && !defined(_GNU_SOURCE) |
| 4 | # define _GNU_SOURCE |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 5 | #endif |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 6 | #include <unistd.h> |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 7 | #include <fcntl.h> |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 8 | #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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 17 | |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 18 | #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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 28 | |
| 29 | #define POSIX_CALL(call) if ((call) == -1) goto error |
| 30 | |
| 31 | |
| 32 | /* Maximum file descriptor, initialized on module load. */ |
| 33 | static long max_fd; |
| 34 | |
| 35 | |
| 36 | /* Given the gc module call gc.enable() and return 0 on success. */ |
| 37 | static int _enable_gc(PyObject *gc_module) |
| 38 | { |
| 39 | PyObject *result; |
Martin v. Löwis | bd928fe | 2011-10-14 10:20:37 +0200 | [diff] [blame] | 40 | _Py_IDENTIFIER(enable); |
Martin v. Löwis | afe55bb | 2011-10-09 10:38:36 +0200 | [diff] [blame] | 41 | |
| 42 | result = _PyObject_CallMethodId(gc_module, &PyId_enable, NULL); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 43 | if (result == NULL) |
| 44 | return 1; |
| 45 | Py_DECREF(result); |
| 46 | return 0; |
| 47 | } |
| 48 | |
| 49 | |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 50 | /* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */ |
| 51 | static 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. */ |
| 65 | static 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? */ |
| 82 | static 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 | */ |
| 109 | static 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 | */ |
| 143 | struct 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 | */ |
| 165 | static 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 | */ |
| 218 | static 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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 277 | /* |
| 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 | */ |
| 288 | static 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. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 297 | int call_setsid, |
Gregory P. Smith | d4cc7bf | 2010-12-04 11:22:11 +0000 | [diff] [blame] | 298 | PyObject *py_fds_to_keep, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 299 | PyObject *preexec_fn, |
| 300 | PyObject *preexec_fn_args_tuple) |
| 301 | { |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 302 | int i, saved_errno, unused; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 303 | PyObject *result; |
Gregory P. Smith | 14affb8 | 2010-12-22 05:22:17 +0000 | [diff] [blame] | 304 | const char* err_msg = ""; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 305 | /* 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 Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 320 | /* 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 Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 327 | /* 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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 335 | POSIX_CALL(dup2(p2cread, 0)); /* stdin */ |
| 336 | } |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 337 | 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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 342 | POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */ |
| 343 | } |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 344 | 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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 349 | 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 Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 354 | if (p2cread > 2) { |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 355 | POSIX_CALL(close(p2cread)); |
| 356 | } |
Gregory P. Smith | 8121898 | 2011-03-15 14:56:39 -0400 | [diff] [blame] | 357 | if (c2pwrite > 2 && c2pwrite != p2cread) { |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 358 | POSIX_CALL(close(c2pwrite)); |
| 359 | } |
Gregory P. Smith | 8121898 | 2011-03-15 14:56:39 -0400 | [diff] [blame] | 360 | if (errwrite != c2pwrite && errwrite != p2cread && errwrite > 2) { |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 361 | POSIX_CALL(close(errwrite)); |
| 362 | } |
| 363 | |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 364 | if (close_fds) |
| 365 | _close_open_fd_range(3, max_fd, py_fds_to_keep); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 366 | |
| 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 | |
| 412 | error: |
| 413 | saved_errno = errno; |
| 414 | /* Report the posix error to our parent process. */ |
Gregory P. Smith | 12fdca5 | 2012-01-21 12:31:25 -0800 | [diff] [blame] | 415 | /* 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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 417 | if (saved_errno) { |
| 418 | char *cur; |
Gregory P. Smith | 12fdca5 | 2012-01-21 12:31:25 -0800 | [diff] [blame] | 419 | unused = write(errpipe_write, "OSError:", 8); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 420 | 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. Smith | 12fdca5 | 2012-01-21 12:31:25 -0800 | [diff] [blame] | 425 | unused = write(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur); |
| 426 | unused = write(errpipe_write, ":", 1); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 427 | /* 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. Smith | 12fdca5 | 2012-01-21 12:31:25 -0800 | [diff] [blame] | 430 | unused = write(errpipe_write, "RuntimeError:0:", 15); |
| 431 | unused = write(errpipe_write, err_msg, strlen(err_msg)); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 432 | } |
Gregory P. Smith | 12fdca5 | 2012-01-21 12:31:25 -0800 | [diff] [blame] | 433 | if (unused) return; /* silly? yes! avoids gcc compiler warning. */ |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 434 | } |
| 435 | |
| 436 | |
| 437 | static PyObject * |
| 438 | subprocess_fork_exec(PyObject* self, PyObject *args) |
| 439 | { |
| 440 | PyObject *gc_module = NULL; |
Gregory P. Smith | d4cc7bf | 2010-12-04 11:22:11 +0000 | [diff] [blame] | 441 | PyObject *executable_list, *py_close_fds, *py_fds_to_keep; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 442 | PyObject *env_list, *preexec_fn; |
Gregory P. Smith | 68f5217 | 2010-03-15 06:07:42 +0000 | [diff] [blame] | 443 | PyObject *process_args, *converted_args = NULL, *fast_args = NULL; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 444 | 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 Stinner | 0e59cc3 | 2010-04-16 23:49:32 +0000 | [diff] [blame] | 448 | PyObject *cwd_obj, *cwd_obj2; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 449 | 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. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 453 | Py_ssize_t arg_num; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 454 | |
| 455 | if (!PyArg_ParseTuple( |
Gregory P. Smith | d4cc7bf | 2010-12-04 11:22:11 +0000 | [diff] [blame] | 456 | args, "OOOOOOiiiiiiiiiiO:fork_exec", |
| 457 | &process_args, &executable_list, &py_close_fds, &py_fds_to_keep, |
Victor Stinner | 0e59cc3 | 2010-04-16 23:49:32 +0000 | [diff] [blame] | 458 | &cwd_obj, &env_list, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 459 | &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. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 469 | 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. Smith | d4cc7bf | 2010-12-04 11:22:11 +0000 | [diff] [blame] | 475 | return NULL; |
| 476 | } |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 477 | |
| 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öwis | bd928fe | 2011-10-14 10:20:37 +0200 | [diff] [blame] | 481 | _Py_IDENTIFIER(isenabled); |
| 482 | _Py_IDENTIFIER(disable); |
Martin v. Löwis | afe55bb | 2011-10-09 10:38:36 +0200 | [diff] [blame] | 483 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 484 | gc_module = PyImport_ImportModule("gc"); |
| 485 | if (gc_module == NULL) |
| 486 | return NULL; |
Martin v. Löwis | afe55bb | 2011-10-09 10:38:36 +0200 | [diff] [blame] | 487 | result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL); |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 488 | if (result == NULL) { |
| 489 | Py_DECREF(gc_module); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 490 | return NULL; |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 491 | } |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 492 | need_to_reenable_gc = PyObject_IsTrue(result); |
| 493 | Py_DECREF(result); |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 494 | if (need_to_reenable_gc == -1) { |
| 495 | Py_DECREF(gc_module); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 496 | return NULL; |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 497 | } |
Martin v. Löwis | afe55bb | 2011-10-09 10:38:36 +0200 | [diff] [blame] | 498 | result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL); |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 499 | if (result == NULL) { |
| 500 | Py_DECREF(gc_module); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 501 | return NULL; |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 502 | } |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 503 | 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. Smith | 68f5217 | 2010-03-15 06:07:42 +0000 | [diff] [blame] | 514 | Py_ssize_t num_args; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 515 | /* Equivalent to: */ |
| 516 | /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */ |
Gregory P. Smith | 68f5217 | 2010-03-15 06:07:42 +0000 | [diff] [blame] | 517 | 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. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 520 | if (converted_args == NULL) |
| 521 | goto cleanup; |
Gregory P. Smith | 68f5217 | 2010-03-15 06:07:42 +0000 | [diff] [blame] | 522 | for (arg_num = 0; arg_num < num_args; ++arg_num) { |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 523 | PyObject *borrowed_arg, *converted_arg; |
Gregory P. Smith | 68f5217 | 2010-03-15 06:07:42 +0000 | [diff] [blame] | 524 | borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 525 | 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. Smith | 68f5217 | 2010-03-15 06:07:42 +0000 | [diff] [blame] | 532 | Py_CLEAR(fast_args); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 533 | 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 Stinner | 0e59cc3 | 2010-04-16 23:49:32 +0000 | [diff] [blame] | 547 | _PyImport_AcquireLock(); |
| 548 | } |
| 549 | |
| 550 | if (cwd_obj != Py_None) { |
| 551 | if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0) |
| 552 | goto cleanup; |
Victor Stinner | dcb2403 | 2010-04-22 12:08:36 +0000 | [diff] [blame] | 553 | cwd = PyBytes_AsString(cwd_obj2); |
Victor Stinner | 0e59cc3 | 2010-04-16 23:49:32 +0000 | [diff] [blame] | 554 | } else { |
| 555 | cwd = NULL; |
| 556 | cwd_obj2 = NULL; |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 557 | } |
| 558 | |
| 559 | pid = fork(); |
| 560 | if (pid == 0) { |
| 561 | /* Child process */ |
Victor Stinner | 0e59cc3 | 2010-04-16 23:49:32 +0000 | [diff] [blame] | 562 | /* |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 563 | * 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. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 580 | py_fds_to_keep, preexec_fn, preexec_fn_args_tuple); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 581 | _exit(255); |
| 582 | return NULL; /* Dead code to avoid a potential compiler warning. */ |
| 583 | } |
Victor Stinner | 0e59cc3 | 2010-04-16 23:49:32 +0000 | [diff] [blame] | 584 | Py_XDECREF(cwd_obj2); |
| 585 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 586 | 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. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 608 | Py_XDECREF(preexec_fn_args_tuple); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 609 | Py_XDECREF(gc_module); |
| 610 | |
| 611 | if (pid == -1) |
| 612 | return NULL; /* fork() failed. Exception set earlier. */ |
| 613 | |
| 614 | return PyLong_FromPid(pid); |
| 615 | |
| 616 | cleanup: |
| 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. Smith | 68f5217 | 2010-03-15 06:07:42 +0000 | [diff] [blame] | 623 | Py_XDECREF(fast_args); |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 624 | Py_XDECREF(preexec_fn_args_tuple); |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 625 | |
| 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 | |
| 634 | PyDoc_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\ |
| 640 | Forks a child process, closes parent file descriptors as appropriate in the\n\ |
| 641 | child and dups the few that are needed before calling exec() in the child\n\ |
| 642 | process.\n\ |
| 643 | \n\ |
| 644 | The preexec_fn, if supplied, will be called immediately before exec.\n\ |
| 645 | WARNING: preexec_fn is NOT SAFE if your application uses threads.\n\ |
| 646 | It may trigger infrequent, difficult to debug deadlocks.\n\ |
| 647 | \n\ |
| 648 | If an error occurs in the child process before the exec, it is\n\ |
| 649 | serialized and written to the errpipe_write fd per subprocess.py.\n\ |
| 650 | \n\ |
| 651 | Returns: the child process's PID.\n\ |
| 652 | \n\ |
| 653 | Raises: Only on an error in the parent process.\n\ |
| 654 | "); |
| 655 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 656 | PyDoc_STRVAR(subprocess_cloexec_pipe_doc, |
| 657 | "cloexec_pipe() -> (read_end, write_end)\n\n\ |
| 658 | Create a pipe whose ends have the cloexec flag set."); |
| 659 | |
| 660 | static PyObject * |
| 661 | subprocess_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. Smith | abcfcba | 2011-01-02 20:52:48 +0000 | [diff] [blame] | 669 | if (res != 0 && errno == ENOSYS) |
| 670 | { |
Gregory P. Smith | abcfcba | 2011-01-02 20:52:48 +0000 | [diff] [blame] | 671 | { |
| 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. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 677 | |
Gregory P. Smith | abcfcba | 2011-01-02 20:52:48 +0000 | [diff] [blame] | 678 | res = pipe(fds); |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 679 | |
Gregory P. Smith | abcfcba | 2011-01-02 20:52:48 +0000 | [diff] [blame] | 680 | 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. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 695 | } |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 696 | #endif |
| 697 | if (res != 0) |
| 698 | return PyErr_SetFromErrno(PyExc_OSError); |
| 699 | return Py_BuildValue("(ii)", fds[0], fds[1]); |
| 700 | } |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 701 | |
| 702 | /* module level code ********************************************************/ |
| 703 | |
| 704 | PyDoc_STRVAR(module_doc, |
| 705 | "A POSIX helper for the subprocess module."); |
| 706 | |
| 707 | |
| 708 | static PyMethodDef module_methods[] = { |
| 709 | {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc}, |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 710 | {"cloexec_pipe", subprocess_cloexec_pipe, METH_NOARGS, subprocess_cloexec_pipe_doc}, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 711 | {NULL, NULL} /* sentinel */ |
| 712 | }; |
| 713 | |
| 714 | |
| 715 | static struct PyModuleDef _posixsubprocessmodule = { |
| 716 | PyModuleDef_HEAD_INIT, |
| 717 | "_posixsubprocess", |
| 718 | module_doc, |
| 719 | -1, /* No memory is needed. */ |
| 720 | module_methods, |
| 721 | }; |
| 722 | |
| 723 | PyMODINIT_FUNC |
| 724 | PyInit__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 | } |