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.

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