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.

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