_posixsubprocess.c 31 KB

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