You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

791 lines
26 KiB

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