_posixsubprocess.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. /* Authors: Gregory P. Smith & Jeffrey Yasskin */
  2. #ifndef Py_BUILD_CORE_BUILTIN
  3. # define Py_BUILD_CORE_MODULE 1
  4. #endif
  5. #include "Python.h"
  6. #include "pycore_fileutils.h"
  7. #include "pycore_pystate.h"
  8. #if defined(HAVE_PIPE2) && !defined(_GNU_SOURCE)
  9. # define _GNU_SOURCE
  10. #endif
  11. #include <unistd.h>
  12. #include <fcntl.h>
  13. #ifdef HAVE_SYS_TYPES_H
  14. #include <sys/types.h>
  15. #endif
  16. #if defined(HAVE_SYS_STAT_H)
  17. #include <sys/stat.h>
  18. #endif
  19. #ifdef HAVE_SYS_SYSCALL_H
  20. #include <sys/syscall.h>
  21. #endif
  22. #if defined(HAVE_SYS_RESOURCE_H)
  23. #include <sys/resource.h>
  24. #endif
  25. #ifdef HAVE_DIRENT_H
  26. #include <dirent.h>
  27. #endif
  28. #ifdef HAVE_GRP_H
  29. #include <grp.h>
  30. #endif /* HAVE_GRP_H */
  31. #include "posixmodule.h"
  32. #ifdef _Py_MEMORY_SANITIZER
  33. # include <sanitizer/msan_interface.h>
  34. #endif
  35. #if defined(__ANDROID__) && __ANDROID_API__ < 21 && !defined(SYS_getdents64)
  36. # include <sys/linux-syscalls.h>
  37. # define SYS_getdents64 __NR_getdents64
  38. #endif
  39. #if defined(__linux__) && defined(HAVE_VFORK) && defined(HAVE_SIGNAL_H) && \
  40. defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
  41. /* If this is ever expanded to non-Linux platforms, verify what calls are
  42. * allowed after vfork(). Ex: setsid() may be disallowed on macOS? */
  43. # include <signal.h>
  44. # define VFORK_USABLE 1
  45. #endif
  46. #if defined(__sun) && defined(__SVR4)
  47. /* readdir64 is used to work around Solaris 9 bug 6395699. */
  48. # define readdir readdir64
  49. # define dirent dirent64
  50. # if !defined(HAVE_DIRFD)
  51. /* Some versions of Solaris lack dirfd(). */
  52. # define dirfd(dirp) ((dirp)->dd_fd)
  53. # define HAVE_DIRFD
  54. # endif
  55. #endif
  56. #if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__DragonFly__)
  57. # define FD_DIR "/dev/fd"
  58. #else
  59. # define FD_DIR "/proc/self/fd"
  60. #endif
  61. #ifdef NGROUPS_MAX
  62. #define MAX_GROUPS NGROUPS_MAX
  63. #else
  64. #define MAX_GROUPS 64
  65. #endif
  66. #define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0)
  67. static struct PyModuleDef _posixsubprocessmodule;
  68. /*[clinic input]
  69. module _posixsubprocess
  70. [clinic start generated code]*/
  71. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=c62211df27cf7334]*/
  72. /*[python input]
  73. class pid_t_converter(CConverter):
  74. type = 'pid_t'
  75. format_unit = '" _Py_PARSE_PID "'
  76. def parse_arg(self, argname, displayname):
  77. return """
  78. {paramname} = PyLong_AsPid({argname});
  79. if ({paramname} == -1 && PyErr_Occurred()) {{{{
  80. goto exit;
  81. }}}}
  82. """.format(argname=argname, paramname=self.parser_name)
  83. [python start generated code]*/
  84. /*[python end generated code: output=da39a3ee5e6b4b0d input=5af1c116d56cbb5a]*/
  85. #include "clinic/_posixsubprocess.c.h"
  86. /* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
  87. static int
  88. _pos_int_from_ascii(const char *name)
  89. {
  90. int num = 0;
  91. while (*name >= '0' && *name <= '9') {
  92. num = num * 10 + (*name - '0');
  93. ++name;
  94. }
  95. if (*name)
  96. return -1; /* Non digit found, not a number. */
  97. return num;
  98. }
  99. #if defined(__FreeBSD__) || defined(__DragonFly__)
  100. /* When /dev/fd isn't mounted it is often a static directory populated
  101. * with 0 1 2 or entries for 0 .. 63 on FreeBSD, NetBSD, OpenBSD and DragonFlyBSD.
  102. * NetBSD and OpenBSD have a /proc fs available (though not necessarily
  103. * mounted) and do not have fdescfs for /dev/fd. MacOS X has a devfs
  104. * that properly supports /dev/fd.
  105. */
  106. static int
  107. _is_fdescfs_mounted_on_dev_fd(void)
  108. {
  109. struct stat dev_stat;
  110. struct stat dev_fd_stat;
  111. if (stat("/dev", &dev_stat) != 0)
  112. return 0;
  113. if (stat(FD_DIR, &dev_fd_stat) != 0)
  114. return 0;
  115. if (dev_stat.st_dev == dev_fd_stat.st_dev)
  116. return 0; /* / == /dev == /dev/fd means it is static. #fail */
  117. return 1;
  118. }
  119. #endif
  120. /* Returns 1 if there is a problem with fd_sequence, 0 otherwise. */
  121. static int
  122. _sanity_check_python_fd_sequence(PyObject *fd_sequence)
  123. {
  124. Py_ssize_t seq_idx;
  125. long prev_fd = -1;
  126. for (seq_idx = 0; seq_idx < PyTuple_GET_SIZE(fd_sequence); ++seq_idx) {
  127. PyObject* py_fd = PyTuple_GET_ITEM(fd_sequence, seq_idx);
  128. long iter_fd;
  129. if (!PyLong_Check(py_fd)) {
  130. return 1;
  131. }
  132. iter_fd = PyLong_AsLong(py_fd);
  133. if (iter_fd < 0 || iter_fd <= prev_fd || iter_fd > INT_MAX) {
  134. /* Negative, overflow, unsorted, too big for a fd. */
  135. return 1;
  136. }
  137. prev_fd = iter_fd;
  138. }
  139. return 0;
  140. }
  141. /* Is fd found in the sorted Python Sequence? */
  142. static int
  143. _is_fd_in_sorted_fd_sequence(int fd, int *fd_sequence,
  144. Py_ssize_t fd_sequence_len)
  145. {
  146. /* Binary search. */
  147. Py_ssize_t search_min = 0;
  148. Py_ssize_t search_max = fd_sequence_len - 1;
  149. if (search_max < 0)
  150. return 0;
  151. do {
  152. long middle = (search_min + search_max) / 2;
  153. long middle_fd = fd_sequence[middle];
  154. if (fd == middle_fd)
  155. return 1;
  156. if (fd > middle_fd)
  157. search_min = middle + 1;
  158. else
  159. search_max = middle - 1;
  160. } while (search_min <= search_max);
  161. return 0;
  162. }
  163. /*
  164. * Do all the Python C API calls in the parent process to turn the pass_fds
  165. * "py_fds_to_keep" tuple into a C array. The caller owns allocation and
  166. * freeing of the array.
  167. *
  168. * On error an unknown number of array elements may have been filled in.
  169. * A Python exception has been set when an error is returned.
  170. *
  171. * Returns: -1 on error, 0 on success.
  172. */
  173. static int
  174. convert_fds_to_keep_to_c(PyObject *py_fds_to_keep, int *c_fds_to_keep)
  175. {
  176. Py_ssize_t i, len;
  177. len = PyTuple_GET_SIZE(py_fds_to_keep);
  178. for (i = 0; i < len; ++i) {
  179. PyObject* fdobj = PyTuple_GET_ITEM(py_fds_to_keep, i);
  180. long fd = PyLong_AsLong(fdobj);
  181. if (fd == -1 && PyErr_Occurred()) {
  182. return -1;
  183. }
  184. if (fd < 0 || fd > INT_MAX) {
  185. PyErr_SetString(PyExc_ValueError,
  186. "fd out of range in fds_to_keep.");
  187. return -1;
  188. }
  189. c_fds_to_keep[i] = (int)fd;
  190. }
  191. return 0;
  192. }
  193. /* This function must be async-signal-safe as it is called from child_exec()
  194. * after fork() or vfork().
  195. */
  196. static int
  197. make_inheritable(int *c_fds_to_keep, Py_ssize_t len, int errpipe_write)
  198. {
  199. Py_ssize_t i;
  200. for (i = 0; i < len; ++i) {
  201. int fd = c_fds_to_keep[i];
  202. if (fd == errpipe_write) {
  203. /* errpipe_write is part of fds_to_keep. It must be closed at
  204. exec(), but kept open in the child process until exec() is
  205. called. */
  206. continue;
  207. }
  208. if (_Py_set_inheritable_async_safe(fd, 1, NULL) < 0)
  209. return -1;
  210. }
  211. return 0;
  212. }
  213. /* Get the maximum file descriptor that could be opened by this process.
  214. * This function is async signal safe for use between fork() and exec().
  215. */
  216. static long
  217. safe_get_max_fd(void)
  218. {
  219. long local_max_fd;
  220. #if defined(__NetBSD__)
  221. local_max_fd = fcntl(0, F_MAXFD);
  222. if (local_max_fd >= 0)
  223. return local_max_fd;
  224. #endif
  225. #if defined(HAVE_SYS_RESOURCE_H) && defined(__OpenBSD__)
  226. struct rlimit rl;
  227. /* Not on the POSIX async signal safe functions list but likely
  228. * safe. TODO - Someone should audit OpenBSD to make sure. */
  229. if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
  230. return (long) rl.rlim_max;
  231. #endif
  232. #ifdef _SC_OPEN_MAX
  233. local_max_fd = sysconf(_SC_OPEN_MAX);
  234. if (local_max_fd == -1)
  235. #endif
  236. local_max_fd = 256; /* Matches legacy Lib/subprocess.py behavior. */
  237. return local_max_fd;
  238. }
  239. /* Close all file descriptors in the given range except for those in
  240. * fds_to_keep by invoking closer on each subrange.
  241. *
  242. * If end_fd == -1, it's guessed via safe_get_max_fd(), but it isn't
  243. * possible to know for sure what the max fd to go up to is for
  244. * processes with the capability of raising their maximum, or in case
  245. * a process opened a high fd and then lowered its maximum.
  246. */
  247. static int
  248. _close_range_except(int start_fd,
  249. int end_fd,
  250. int *fds_to_keep,
  251. Py_ssize_t fds_to_keep_len,
  252. int (*closer)(int, int))
  253. {
  254. if (end_fd == -1) {
  255. end_fd = Py_MIN(safe_get_max_fd(), INT_MAX);
  256. }
  257. Py_ssize_t keep_seq_idx;
  258. /* As fds_to_keep is sorted we can loop through the list closing
  259. * fds in between any in the keep list falling within our range. */
  260. for (keep_seq_idx = 0; keep_seq_idx < fds_to_keep_len; ++keep_seq_idx) {
  261. int keep_fd = fds_to_keep[keep_seq_idx];
  262. if (keep_fd < start_fd)
  263. continue;
  264. if (closer(start_fd, keep_fd - 1) != 0)
  265. return -1;
  266. start_fd = keep_fd + 1;
  267. }
  268. if (start_fd <= end_fd) {
  269. if (closer(start_fd, end_fd) != 0)
  270. return -1;
  271. }
  272. return 0;
  273. }
  274. #if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
  275. /* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
  276. * only to read a directory of short file descriptor number names. The kernel
  277. * will return an error if we didn't give it enough space. Highly Unlikely.
  278. * This structure is very old and stable: It will not change unless the kernel
  279. * chooses to break compatibility with all existing binaries. Highly Unlikely.
  280. */
  281. struct linux_dirent64 {
  282. unsigned long long d_ino;
  283. long long d_off;
  284. unsigned short d_reclen; /* Length of this linux_dirent */
  285. unsigned char d_type;
  286. char d_name[256]; /* Filename (null-terminated) */
  287. };
  288. static int
  289. _brute_force_closer(int first, int last)
  290. {
  291. for (int i = first; i <= last; i++) {
  292. /* Ignore errors */
  293. (void)close(i);
  294. }
  295. return 0;
  296. }
  297. /* Close all open file descriptors in the range from start_fd and higher
  298. * Do not close any in the sorted fds_to_keep list.
  299. *
  300. * This version is async signal safe as it does not make any unsafe C library
  301. * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
  302. * to resort to making a kernel system call directly but this is the ONLY api
  303. * available that does no harm. opendir/readdir/closedir perform memory
  304. * allocation and locking so while they usually work they are not guaranteed
  305. * to (especially if you have replaced your malloc implementation). A version
  306. * of this function that uses those can be found in the _maybe_unsafe variant.
  307. *
  308. * This is Linux specific because that is all I am ready to test it on. It
  309. * should be easy to add OS specific dirent or dirent64 structures and modify
  310. * it with some cpp #define magic to work on other OSes as well if you want.
  311. */
  312. static void
  313. _close_open_fds_safe(int start_fd, int *fds_to_keep, Py_ssize_t fds_to_keep_len)
  314. {
  315. int fd_dir_fd;
  316. fd_dir_fd = _Py_open_noraise(FD_DIR, O_RDONLY);
  317. if (fd_dir_fd == -1) {
  318. /* No way to get a list of open fds. */
  319. _close_range_except(start_fd, -1,
  320. fds_to_keep, fds_to_keep_len,
  321. _brute_force_closer);
  322. return;
  323. } else {
  324. char buffer[sizeof(struct linux_dirent64)];
  325. int bytes;
  326. while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
  327. (struct linux_dirent64 *)buffer,
  328. sizeof(buffer))) > 0) {
  329. struct linux_dirent64 *entry;
  330. int offset;
  331. #ifdef _Py_MEMORY_SANITIZER
  332. __msan_unpoison(buffer, bytes);
  333. #endif
  334. for (offset = 0; offset < bytes; offset += entry->d_reclen) {
  335. int fd;
  336. entry = (struct linux_dirent64 *)(buffer + offset);
  337. if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
  338. continue; /* Not a number. */
  339. if (fd != fd_dir_fd && fd >= start_fd &&
  340. !_is_fd_in_sorted_fd_sequence(fd, fds_to_keep,
  341. fds_to_keep_len)) {
  342. close(fd);
  343. }
  344. }
  345. }
  346. close(fd_dir_fd);
  347. }
  348. }
  349. #define _close_open_fds_fallback _close_open_fds_safe
  350. #else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
  351. static int
  352. _unsafe_closer(int first, int last)
  353. {
  354. _Py_closerange(first, last);
  355. return 0;
  356. }
  357. /* Close all open file descriptors from start_fd and higher.
  358. * Do not close any in the sorted fds_to_keep tuple.
  359. *
  360. * This function violates the strict use of async signal safe functions. :(
  361. * It calls opendir(), readdir() and closedir(). Of these, the one most
  362. * likely to ever cause a problem is opendir() as it performs an internal
  363. * malloc(). Practically this should not be a problem. The Java VM makes the
  364. * same calls between fork and exec in its own UNIXProcess_md.c implementation.
  365. *
  366. * readdir_r() is not used because it provides no benefit. It is typically
  367. * implemented as readdir() followed by memcpy(). See also:
  368. * http://womble.decadent.org.uk/readdir_r-advisory.html
  369. */
  370. static void
  371. _close_open_fds_maybe_unsafe(int start_fd, int *fds_to_keep,
  372. Py_ssize_t fds_to_keep_len)
  373. {
  374. DIR *proc_fd_dir;
  375. #ifndef HAVE_DIRFD
  376. while (_is_fd_in_sorted_fd_sequence(start_fd, fds_to_keep,
  377. fds_to_keep_len)) {
  378. ++start_fd;
  379. }
  380. /* Close our lowest fd before we call opendir so that it is likely to
  381. * reuse that fd otherwise we might close opendir's file descriptor in
  382. * our loop. This trick assumes that fd's are allocated on a lowest
  383. * available basis. */
  384. close(start_fd);
  385. ++start_fd;
  386. #endif
  387. #if defined(__FreeBSD__) || defined(__DragonFly__)
  388. if (!_is_fdescfs_mounted_on_dev_fd())
  389. proc_fd_dir = NULL;
  390. else
  391. #endif
  392. proc_fd_dir = opendir(FD_DIR);
  393. if (!proc_fd_dir) {
  394. /* No way to get a list of open fds. */
  395. _close_range_except(start_fd, -1, fds_to_keep, fds_to_keep_len,
  396. _unsafe_closer);
  397. } else {
  398. struct dirent *dir_entry;
  399. #ifdef HAVE_DIRFD
  400. int fd_used_by_opendir = dirfd(proc_fd_dir);
  401. #else
  402. int fd_used_by_opendir = start_fd - 1;
  403. #endif
  404. errno = 0;
  405. while ((dir_entry = readdir(proc_fd_dir))) {
  406. int fd;
  407. if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
  408. continue; /* Not a number. */
  409. if (fd != fd_used_by_opendir && fd >= start_fd &&
  410. !_is_fd_in_sorted_fd_sequence(fd, fds_to_keep,
  411. fds_to_keep_len)) {
  412. close(fd);
  413. }
  414. errno = 0;
  415. }
  416. if (errno) {
  417. /* readdir error, revert behavior. Highly Unlikely. */
  418. _close_range_except(start_fd, -1, fds_to_keep, fds_to_keep_len,
  419. _unsafe_closer);
  420. }
  421. closedir(proc_fd_dir);
  422. }
  423. }
  424. #define _close_open_fds_fallback _close_open_fds_maybe_unsafe
  425. #endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
  426. /* We can use close_range() library function only if it's known to be
  427. * async-signal-safe.
  428. *
  429. * On Linux, glibc explicitly documents it to be a thin wrapper over
  430. * the system call, and other C libraries are likely to follow glibc.
  431. */
  432. #if defined(HAVE_CLOSE_RANGE) && \
  433. (defined(__linux__) || defined(__FreeBSD__))
  434. #define HAVE_ASYNC_SAFE_CLOSE_RANGE
  435. static int
  436. _close_range_closer(int first, int last)
  437. {
  438. return close_range(first, last, 0);
  439. }
  440. #endif
  441. static void
  442. _close_open_fds(int start_fd, int *fds_to_keep, Py_ssize_t fds_to_keep_len)
  443. {
  444. #ifdef HAVE_ASYNC_SAFE_CLOSE_RANGE
  445. if (_close_range_except(
  446. start_fd, INT_MAX, fds_to_keep, fds_to_keep_len,
  447. _close_range_closer) == 0) {
  448. return;
  449. }
  450. #endif
  451. _close_open_fds_fallback(start_fd, fds_to_keep, fds_to_keep_len);
  452. }
  453. #ifdef VFORK_USABLE
  454. /* Reset dispositions for all signals to SIG_DFL except for ignored
  455. * signals. This way we ensure that no signal handlers can run
  456. * after we unblock signals in a child created by vfork().
  457. */
  458. static void
  459. reset_signal_handlers(const sigset_t *child_sigmask)
  460. {
  461. struct sigaction sa_dfl = {.sa_handler = SIG_DFL};
  462. for (int sig = 1; sig < _NSIG; sig++) {
  463. /* Dispositions for SIGKILL and SIGSTOP can't be changed. */
  464. if (sig == SIGKILL || sig == SIGSTOP) {
  465. continue;
  466. }
  467. /* There is no need to reset the disposition of signals that will
  468. * remain blocked across execve() since the kernel will do it. */
  469. if (sigismember(child_sigmask, sig) == 1) {
  470. continue;
  471. }
  472. struct sigaction sa;
  473. /* C libraries usually return EINVAL for signals used
  474. * internally (e.g. for thread cancellation), so simply
  475. * skip errors here. */
  476. if (sigaction(sig, NULL, &sa) == -1) {
  477. continue;
  478. }
  479. /* void *h works as these fields are both pointer types already. */
  480. void *h = (sa.sa_flags & SA_SIGINFO ? (void *)sa.sa_sigaction :
  481. (void *)sa.sa_handler);
  482. if (h == SIG_IGN || h == SIG_DFL) {
  483. continue;
  484. }
  485. /* This call can't reasonably fail, but if it does, terminating
  486. * the child seems to be too harsh, so ignore errors. */
  487. (void) sigaction(sig, &sa_dfl, NULL);
  488. }
  489. }
  490. #endif /* VFORK_USABLE */
  491. /*
  492. * This function is code executed in the child process immediately after
  493. * (v)fork to set things up and call exec().
  494. *
  495. * All of the code in this function must only use async-signal-safe functions,
  496. * listed at `man 7 signal` or
  497. * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
  498. *
  499. * This restriction is documented at
  500. * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
  501. *
  502. * If this function is called after vfork(), even more care must be taken.
  503. * The lack of preparations that C libraries normally take on fork(),
  504. * as well as sharing the address space with the parent, might make even
  505. * async-signal-safe functions vfork-unsafe. In particular, on Linux,
  506. * set*id() and setgroups() library functions must not be called, since
  507. * they have to interact with the library-level thread list and send
  508. * library-internal signals to implement per-process credentials semantics
  509. * required by POSIX but not supported natively on Linux. Another reason to
  510. * avoid this family of functions is that sharing an address space between
  511. * processes running with different privileges is inherently insecure.
  512. * See https://bugs.python.org/issue35823 for discussion and references.
  513. *
  514. * In some C libraries, setrlimit() has the same thread list/signalling
  515. * behavior since resource limits were per-thread attributes before
  516. * Linux 2.6.10. Musl, as of 1.2.1, is known to have this issue
  517. * (https://www.openwall.com/lists/musl/2020/10/15/6).
  518. *
  519. * If vfork-unsafe functionality is desired after vfork(), consider using
  520. * syscall() to obtain it.
  521. */
  522. Py_NO_INLINE static void
  523. child_exec(char *const exec_array[],
  524. char *const argv[],
  525. char *const envp[],
  526. const char *cwd,
  527. int p2cread, int p2cwrite,
  528. int c2pread, int c2pwrite,
  529. int errread, int errwrite,
  530. int errpipe_read, int errpipe_write,
  531. int close_fds, int restore_signals,
  532. int call_setsid, pid_t pgid_to_set,
  533. gid_t gid,
  534. Py_ssize_t extra_group_size, const gid_t *extra_groups,
  535. uid_t uid, int child_umask,
  536. const void *child_sigmask,
  537. int *fds_to_keep, Py_ssize_t fds_to_keep_len,
  538. PyObject *preexec_fn,
  539. PyObject *preexec_fn_args_tuple)
  540. {
  541. int i, saved_errno;
  542. PyObject *result;
  543. /* Indicate to the parent that the error happened before exec(). */
  544. const char *err_msg = "noexec";
  545. /* Buffer large enough to hold a hex integer. We can't malloc. */
  546. char hex_errno[sizeof(saved_errno)*2+1];
  547. if (make_inheritable(fds_to_keep, fds_to_keep_len, errpipe_write) < 0)
  548. goto error;
  549. /* Close parent's pipe ends. */
  550. if (p2cwrite != -1)
  551. POSIX_CALL(close(p2cwrite));
  552. if (c2pread != -1)
  553. POSIX_CALL(close(c2pread));
  554. if (errread != -1)
  555. POSIX_CALL(close(errread));
  556. POSIX_CALL(close(errpipe_read));
  557. /* When duping fds, if there arises a situation where one of the fds is
  558. either 0, 1 or 2, it is possible that it is overwritten (#12607). */
  559. if (c2pwrite == 0) {
  560. POSIX_CALL(c2pwrite = dup(c2pwrite));
  561. /* issue32270 */
  562. if (_Py_set_inheritable_async_safe(c2pwrite, 0, NULL) < 0) {
  563. goto error;
  564. }
  565. }
  566. while (errwrite == 0 || errwrite == 1) {
  567. POSIX_CALL(errwrite = dup(errwrite));
  568. /* issue32270 */
  569. if (_Py_set_inheritable_async_safe(errwrite, 0, NULL) < 0) {
  570. goto error;
  571. }
  572. }
  573. /* Dup fds for child.
  574. dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
  575. would be a no-op (issue #10806). */
  576. if (p2cread == 0) {
  577. if (_Py_set_inheritable_async_safe(p2cread, 1, NULL) < 0)
  578. goto error;
  579. }
  580. else if (p2cread != -1)
  581. POSIX_CALL(dup2(p2cread, 0)); /* stdin */
  582. if (c2pwrite == 1) {
  583. if (_Py_set_inheritable_async_safe(c2pwrite, 1, NULL) < 0)
  584. goto error;
  585. }
  586. else if (c2pwrite != -1)
  587. POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
  588. if (errwrite == 2) {
  589. if (_Py_set_inheritable_async_safe(errwrite, 1, NULL) < 0)
  590. goto error;
  591. }
  592. else if (errwrite != -1)
  593. POSIX_CALL(dup2(errwrite, 2)); /* stderr */
  594. /* We no longer manually close p2cread, c2pwrite, and errwrite here as
  595. * _close_open_fds takes care when it is not already non-inheritable. */
  596. if (cwd) {
  597. if (chdir(cwd) == -1) {
  598. err_msg = "noexec:chdir";
  599. goto error;
  600. }
  601. }
  602. if (child_umask >= 0)
  603. umask(child_umask); /* umask() always succeeds. */
  604. if (restore_signals)
  605. _Py_RestoreSignals();
  606. #ifdef VFORK_USABLE
  607. if (child_sigmask) {
  608. reset_signal_handlers(child_sigmask);
  609. if ((errno = pthread_sigmask(SIG_SETMASK, child_sigmask, NULL))) {
  610. goto error;
  611. }
  612. }
  613. #endif
  614. #ifdef HAVE_SETSID
  615. if (call_setsid)
  616. POSIX_CALL(setsid());
  617. #endif
  618. #ifdef HAVE_SETPGID
  619. static_assert(_Py_IS_TYPE_SIGNED(pid_t), "pid_t is unsigned");
  620. if (pgid_to_set >= 0) {
  621. POSIX_CALL(setpgid(0, pgid_to_set));
  622. }
  623. #endif
  624. #ifdef HAVE_SETGROUPS
  625. if (extra_group_size >= 0) {
  626. assert((extra_group_size == 0) == (extra_groups == NULL));
  627. POSIX_CALL(setgroups(extra_group_size, extra_groups));
  628. }
  629. #endif /* HAVE_SETGROUPS */
  630. #ifdef HAVE_SETREGID
  631. if (gid != (gid_t)-1)
  632. POSIX_CALL(setregid(gid, gid));
  633. #endif /* HAVE_SETREGID */
  634. #ifdef HAVE_SETREUID
  635. if (uid != (uid_t)-1)
  636. POSIX_CALL(setreuid(uid, uid));
  637. #endif /* HAVE_SETREUID */
  638. err_msg = "";
  639. if (preexec_fn != Py_None && preexec_fn_args_tuple) {
  640. /* This is where the user has asked us to deadlock their program. */
  641. result = PyObject_Call(preexec_fn, preexec_fn_args_tuple, NULL);
  642. if (result == NULL) {
  643. /* Stringifying the exception or traceback would involve
  644. * memory allocation and thus potential for deadlock.
  645. * We've already faced potential deadlock by calling back
  646. * into Python in the first place, so it probably doesn't
  647. * matter but we avoid it to minimize the possibility. */
  648. err_msg = "Exception occurred in preexec_fn.";
  649. errno = 0; /* We don't want to report an OSError. */
  650. goto error;
  651. }
  652. /* Py_DECREF(result); - We're about to exec so why bother? */
  653. }
  654. /* close FDs after executing preexec_fn, which might open FDs */
  655. if (close_fds) {
  656. /* TODO HP-UX could use pstat_getproc() if anyone cares about it. */
  657. _close_open_fds(3, fds_to_keep, fds_to_keep_len);
  658. }
  659. /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
  660. /* given the executable_list generated by Lib/subprocess.py. */
  661. saved_errno = 0;
  662. for (i = 0; exec_array[i] != NULL; ++i) {
  663. const char *executable = exec_array[i];
  664. if (envp) {
  665. execve(executable, argv, envp);
  666. } else {
  667. execv(executable, argv);
  668. }
  669. if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
  670. saved_errno = errno;
  671. }
  672. }
  673. /* Report the first exec error, not the last. */
  674. if (saved_errno)
  675. errno = saved_errno;
  676. error:
  677. saved_errno = errno;
  678. /* Report the posix error to our parent process. */
  679. /* We ignore all write() return values as the total size of our writes is
  680. less than PIPEBUF and we cannot do anything about an error anyways.
  681. Use _Py_write_noraise() to retry write() if it is interrupted by a
  682. signal (fails with EINTR). */
  683. if (saved_errno) {
  684. char *cur;
  685. _Py_write_noraise(errpipe_write, "OSError:", 8);
  686. cur = hex_errno + sizeof(hex_errno);
  687. while (saved_errno != 0 && cur != hex_errno) {
  688. *--cur = Py_hexdigits[saved_errno % 16];
  689. saved_errno /= 16;
  690. }
  691. _Py_write_noraise(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
  692. _Py_write_noraise(errpipe_write, ":", 1);
  693. /* We can't call strerror(saved_errno). It is not async signal safe.
  694. * The parent process will look the error message up. */
  695. } else {
  696. _Py_write_noraise(errpipe_write, "SubprocessError:0:", 18);
  697. }
  698. _Py_write_noraise(errpipe_write, err_msg, strlen(err_msg));
  699. }
  700. /* The main purpose of this wrapper function is to isolate vfork() from both
  701. * subprocess_fork_exec() and child_exec(). A child process created via
  702. * vfork() executes on the same stack as the parent process while the latter is
  703. * suspended, so this function should not be inlined to avoid compiler bugs
  704. * that might clobber data needed by the parent later. Additionally,
  705. * child_exec() should not be inlined to avoid spurious -Wclobber warnings from
  706. * GCC (see bpo-35823).
  707. */
  708. Py_NO_INLINE static pid_t
  709. do_fork_exec(char *const exec_array[],
  710. char *const argv[],
  711. char *const envp[],
  712. const char *cwd,
  713. int p2cread, int p2cwrite,
  714. int c2pread, int c2pwrite,
  715. int errread, int errwrite,
  716. int errpipe_read, int errpipe_write,
  717. int close_fds, int restore_signals,
  718. int call_setsid, pid_t pgid_to_set,
  719. gid_t gid,
  720. Py_ssize_t extra_group_size, const gid_t *extra_groups,
  721. uid_t uid, int child_umask,
  722. const void *child_sigmask,
  723. int *fds_to_keep, Py_ssize_t fds_to_keep_len,
  724. PyObject *preexec_fn,
  725. PyObject *preexec_fn_args_tuple)
  726. {
  727. pid_t pid;
  728. #ifdef VFORK_USABLE
  729. PyThreadState *vfork_tstate_save;
  730. if (child_sigmask) {
  731. /* These are checked by our caller; verify them in debug builds. */
  732. assert(uid == (uid_t)-1);
  733. assert(gid == (gid_t)-1);
  734. assert(extra_group_size < 0);
  735. assert(preexec_fn == Py_None);
  736. /* Drop the GIL so that other threads can continue execution while this
  737. * thread in the parent remains blocked per vfork-semantics on the
  738. * child's exec syscall outcome. Exec does filesystem access which
  739. * can take an arbitrarily long time. This addresses GH-104372.
  740. *
  741. * The vfork'ed child still runs in our address space. Per POSIX it
  742. * must be limited to nothing but exec, but the Linux implementation
  743. * is a little more usable. See the child_exec() comment - The child
  744. * MUST NOT re-acquire the GIL.
  745. */
  746. vfork_tstate_save = PyEval_SaveThread();
  747. pid = vfork();
  748. if (pid != 0) {
  749. // Not in the child process, reacquire the GIL.
  750. PyEval_RestoreThread(vfork_tstate_save);
  751. }
  752. if (pid == (pid_t)-1) {
  753. /* If vfork() fails, fall back to using fork(). When it isn't
  754. * allowed in a process by the kernel, vfork can return -1
  755. * with errno EINVAL. https://bugs.python.org/issue47151. */
  756. pid = fork();
  757. }
  758. } else
  759. #endif
  760. {
  761. pid = fork();
  762. }
  763. if (pid != 0) {
  764. // Parent process.
  765. return pid;
  766. }
  767. /* Child process.
  768. * See the comment above child_exec() for restrictions imposed on
  769. * the code below.
  770. */
  771. if (preexec_fn != Py_None) {
  772. /* We'll be calling back into Python later so we need to do this.
  773. * This call may not be async-signal-safe but neither is calling
  774. * back into Python. The user asked us to use hope as a strategy
  775. * to avoid deadlock... */
  776. PyOS_AfterFork_Child();
  777. }
  778. child_exec(exec_array, argv, envp, cwd,
  779. p2cread, p2cwrite, c2pread, c2pwrite,
  780. errread, errwrite, errpipe_read, errpipe_write,
  781. close_fds, restore_signals, call_setsid, pgid_to_set,
  782. gid, extra_group_size, extra_groups,
  783. uid, child_umask, child_sigmask,
  784. fds_to_keep, fds_to_keep_len,
  785. preexec_fn, preexec_fn_args_tuple);
  786. _exit(255);
  787. return 0; /* Dead code to avoid a potential compiler warning. */
  788. }
  789. /*[clinic input]
  790. _posixsubprocess.fork_exec as subprocess_fork_exec
  791. args as process_args: object
  792. executable_list: object
  793. close_fds: bool
  794. pass_fds as py_fds_to_keep: object(subclass_of='&PyTuple_Type')
  795. cwd as cwd_obj: object
  796. env as env_list: object
  797. p2cread: int
  798. p2cwrite: int
  799. c2pread: int
  800. c2pwrite: int
  801. errread: int
  802. errwrite: int
  803. errpipe_read: int
  804. errpipe_write: int
  805. restore_signals: bool
  806. call_setsid: bool
  807. pgid_to_set: pid_t
  808. gid as gid_object: object
  809. extra_groups as extra_groups_packed: object
  810. uid as uid_object: object
  811. child_umask: int
  812. preexec_fn: object
  813. allow_vfork: bool
  814. /
  815. Spawn a fresh new child process.
  816. Fork a child process, close parent file descriptors as appropriate in the
  817. child and duplicate the few that are needed before calling exec() in the
  818. child process.
  819. If close_fds is True, close file descriptors 3 and higher, except those listed
  820. in the sorted tuple pass_fds.
  821. The preexec_fn, if supplied, will be called immediately before closing file
  822. descriptors and exec.
  823. WARNING: preexec_fn is NOT SAFE if your application uses threads.
  824. It may trigger infrequent, difficult to debug deadlocks.
  825. If an error occurs in the child process before the exec, it is
  826. serialized and written to the errpipe_write fd per subprocess.py.
  827. Returns: the child process's PID.
  828. Raises: Only on an error in the parent process.
  829. [clinic start generated code]*/
  830. static PyObject *
  831. subprocess_fork_exec_impl(PyObject *module, PyObject *process_args,
  832. PyObject *executable_list, int close_fds,
  833. PyObject *py_fds_to_keep, PyObject *cwd_obj,
  834. PyObject *env_list, int p2cread, int p2cwrite,
  835. int c2pread, int c2pwrite, int errread,
  836. int errwrite, int errpipe_read, int errpipe_write,
  837. int restore_signals, int call_setsid,
  838. pid_t pgid_to_set, PyObject *gid_object,
  839. PyObject *extra_groups_packed,
  840. PyObject *uid_object, int child_umask,
  841. PyObject *preexec_fn, int allow_vfork)
  842. /*[clinic end generated code: output=7ee4f6ee5cf22b5b input=51757287ef266ffa]*/
  843. {
  844. PyObject *converted_args = NULL, *fast_args = NULL;
  845. PyObject *preexec_fn_args_tuple = NULL;
  846. gid_t *extra_groups = NULL;
  847. PyObject *cwd_obj2 = NULL;
  848. const char *cwd = NULL;
  849. pid_t pid = -1;
  850. int need_to_reenable_gc = 0;
  851. char *const *argv = NULL, *const *envp = NULL;
  852. int need_after_fork = 0;
  853. int saved_errno = 0;
  854. int *c_fds_to_keep = NULL;
  855. Py_ssize_t fds_to_keep_len = PyTuple_GET_SIZE(py_fds_to_keep);
  856. PyInterpreterState *interp = PyInterpreterState_Get();
  857. if ((preexec_fn != Py_None) &&
  858. _PyInterpreterState_GetFinalizing(interp) != NULL)
  859. {
  860. PyErr_SetString(PyExc_RuntimeError,
  861. "preexec_fn not supported at interpreter shutdown");
  862. return NULL;
  863. }
  864. if ((preexec_fn != Py_None) && (interp != PyInterpreterState_Main())) {
  865. PyErr_SetString(PyExc_RuntimeError,
  866. "preexec_fn not supported within subinterpreters");
  867. return NULL;
  868. }
  869. if (close_fds && errpipe_write < 3) { /* precondition */
  870. PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
  871. return NULL;
  872. }
  873. if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
  874. PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
  875. return NULL;
  876. }
  877. /* We need to call gc.disable() when we'll be calling preexec_fn */
  878. if (preexec_fn != Py_None) {
  879. need_to_reenable_gc = PyGC_Disable();
  880. }
  881. char *const *exec_array = _PySequence_BytesToCharpArray(executable_list);
  882. if (!exec_array)
  883. goto cleanup;
  884. /* Convert args and env into appropriate arguments for exec() */
  885. /* These conversions are done in the parent process to avoid allocating
  886. or freeing memory in the child process. */
  887. if (process_args != Py_None) {
  888. Py_ssize_t num_args;
  889. /* Equivalent to: */
  890. /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
  891. fast_args = PySequence_Fast(process_args, "argv must be a tuple");
  892. if (fast_args == NULL)
  893. goto cleanup;
  894. num_args = PySequence_Fast_GET_SIZE(fast_args);
  895. converted_args = PyTuple_New(num_args);
  896. if (converted_args == NULL)
  897. goto cleanup;
  898. for (Py_ssize_t arg_num = 0; arg_num < num_args; ++arg_num) {
  899. PyObject *borrowed_arg, *converted_arg;
  900. if (PySequence_Fast_GET_SIZE(fast_args) != num_args) {
  901. PyErr_SetString(PyExc_RuntimeError, "args changed during iteration");
  902. goto cleanup;
  903. }
  904. borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
  905. if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
  906. goto cleanup;
  907. PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
  908. }
  909. argv = _PySequence_BytesToCharpArray(converted_args);
  910. Py_CLEAR(converted_args);
  911. Py_CLEAR(fast_args);
  912. if (!argv)
  913. goto cleanup;
  914. }
  915. if (env_list != Py_None) {
  916. envp = _PySequence_BytesToCharpArray(env_list);
  917. if (!envp)
  918. goto cleanup;
  919. }
  920. if (cwd_obj != Py_None) {
  921. if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
  922. goto cleanup;
  923. cwd = PyBytes_AsString(cwd_obj2);
  924. }
  925. // Special initial value meaning that subprocess API was called with
  926. // extra_groups=None leading to _posixsubprocess.fork_exec(gids=None).
  927. // We use this to differentiate between code desiring a setgroups(0, NULL)
  928. // call vs no call at all. The fast vfork() code path could be used when
  929. // there is no setgroups call.
  930. Py_ssize_t extra_group_size = -2;
  931. if (extra_groups_packed != Py_None) {
  932. #ifdef HAVE_SETGROUPS
  933. if (!PyList_Check(extra_groups_packed)) {
  934. PyErr_SetString(PyExc_TypeError,
  935. "setgroups argument must be a list");
  936. goto cleanup;
  937. }
  938. extra_group_size = PySequence_Size(extra_groups_packed);
  939. if (extra_group_size < 0)
  940. goto cleanup;
  941. if (extra_group_size > MAX_GROUPS) {
  942. PyErr_SetString(PyExc_ValueError, "too many extra_groups");
  943. goto cleanup;
  944. }
  945. /* Deliberately keep extra_groups == NULL for extra_group_size == 0 */
  946. if (extra_group_size > 0) {
  947. extra_groups = PyMem_RawMalloc(extra_group_size * sizeof(gid_t));
  948. if (extra_groups == NULL) {
  949. PyErr_SetString(PyExc_MemoryError,
  950. "failed to allocate memory for group list");
  951. goto cleanup;
  952. }
  953. }
  954. for (Py_ssize_t i = 0; i < extra_group_size; i++) {
  955. PyObject *elem;
  956. elem = PySequence_GetItem(extra_groups_packed, i);
  957. if (!elem)
  958. goto cleanup;
  959. if (!PyLong_Check(elem)) {
  960. PyErr_SetString(PyExc_TypeError,
  961. "extra_groups must be integers");
  962. Py_DECREF(elem);
  963. goto cleanup;
  964. } else {
  965. gid_t gid;
  966. if (!_Py_Gid_Converter(elem, &gid)) {
  967. Py_DECREF(elem);
  968. PyErr_SetString(PyExc_ValueError, "invalid group id");
  969. goto cleanup;
  970. }
  971. extra_groups[i] = gid;
  972. }
  973. Py_DECREF(elem);
  974. }
  975. #else /* HAVE_SETGROUPS */
  976. PyErr_BadInternalCall();
  977. goto cleanup;
  978. #endif /* HAVE_SETGROUPS */
  979. }
  980. gid_t gid = (gid_t)-1;
  981. if (gid_object != Py_None) {
  982. #ifdef HAVE_SETREGID
  983. if (!_Py_Gid_Converter(gid_object, &gid))
  984. goto cleanup;
  985. #else /* HAVE_SETREGID */
  986. PyErr_BadInternalCall();
  987. goto cleanup;
  988. #endif /* HAVE_SETREUID */
  989. }
  990. uid_t uid = (uid_t)-1;
  991. if (uid_object != Py_None) {
  992. #ifdef HAVE_SETREUID
  993. if (!_Py_Uid_Converter(uid_object, &uid))
  994. goto cleanup;
  995. #else /* HAVE_SETREUID */
  996. PyErr_BadInternalCall();
  997. goto cleanup;
  998. #endif /* HAVE_SETREUID */
  999. }
  1000. c_fds_to_keep = PyMem_Malloc(fds_to_keep_len * sizeof(int));
  1001. if (c_fds_to_keep == NULL) {
  1002. PyErr_SetString(PyExc_MemoryError, "failed to malloc c_fds_to_keep");
  1003. goto cleanup;
  1004. }
  1005. if (convert_fds_to_keep_to_c(py_fds_to_keep, c_fds_to_keep) < 0) {
  1006. goto cleanup;
  1007. }
  1008. /* This must be the last thing done before fork() because we do not
  1009. * want to call PyOS_BeforeFork() if there is any chance of another
  1010. * error leading to the cleanup: code without calling fork(). */
  1011. if (preexec_fn != Py_None) {
  1012. preexec_fn_args_tuple = PyTuple_New(0);
  1013. if (!preexec_fn_args_tuple)
  1014. goto cleanup;
  1015. PyOS_BeforeFork();
  1016. need_after_fork = 1;
  1017. }
  1018. /* NOTE: When old_sigmask is non-NULL, do_fork_exec() may use vfork(). */
  1019. const void *old_sigmask = NULL;
  1020. #ifdef VFORK_USABLE
  1021. /* Use vfork() only if it's safe. See the comment above child_exec(). */
  1022. sigset_t old_sigs;
  1023. if (preexec_fn == Py_None && allow_vfork &&
  1024. uid == (uid_t)-1 && gid == (gid_t)-1 && extra_group_size < 0) {
  1025. /* Block all signals to ensure that no signal handlers are run in the
  1026. * child process while it shares memory with us. Note that signals
  1027. * used internally by C libraries won't be blocked by
  1028. * pthread_sigmask(), but signal handlers installed by C libraries
  1029. * normally service only signals originating from *within the process*,
  1030. * so it should be sufficient to consider any library function that
  1031. * might send such a signal to be vfork-unsafe and do not call it in
  1032. * the child.
  1033. */
  1034. sigset_t all_sigs;
  1035. sigfillset(&all_sigs);
  1036. if ((saved_errno = pthread_sigmask(SIG_BLOCK, &all_sigs, &old_sigs))) {
  1037. goto cleanup;
  1038. }
  1039. old_sigmask = &old_sigs;
  1040. }
  1041. #endif
  1042. pid = do_fork_exec(exec_array, argv, envp, cwd,
  1043. p2cread, p2cwrite, c2pread, c2pwrite,
  1044. errread, errwrite, errpipe_read, errpipe_write,
  1045. close_fds, restore_signals, call_setsid, pgid_to_set,
  1046. gid, extra_group_size, extra_groups,
  1047. uid, child_umask, old_sigmask,
  1048. c_fds_to_keep, fds_to_keep_len,
  1049. preexec_fn, preexec_fn_args_tuple);
  1050. /* Parent (original) process */
  1051. if (pid == (pid_t)-1) {
  1052. /* Capture errno for the exception. */
  1053. saved_errno = errno;
  1054. }
  1055. #ifdef VFORK_USABLE
  1056. if (old_sigmask) {
  1057. /* vfork() semantics guarantees that the parent is blocked
  1058. * until the child performs _exit() or execve(), so it is safe
  1059. * to unblock signals once we're here.
  1060. * Note that in environments where vfork() is implemented as fork(),
  1061. * such as QEMU user-mode emulation, the parent won't be blocked,
  1062. * but it won't share the address space with the child,
  1063. * so it's still safe to unblock the signals.
  1064. *
  1065. * We don't handle errors here because this call can't fail
  1066. * if valid arguments are given, and because there is no good
  1067. * way for the caller to deal with a failure to restore
  1068. * the thread signal mask. */
  1069. (void) pthread_sigmask(SIG_SETMASK, old_sigmask, NULL);
  1070. }
  1071. #endif
  1072. if (need_after_fork)
  1073. PyOS_AfterFork_Parent();
  1074. cleanup:
  1075. if (c_fds_to_keep != NULL) {
  1076. PyMem_Free(c_fds_to_keep);
  1077. }
  1078. if (saved_errno != 0) {
  1079. errno = saved_errno;
  1080. /* We can't call this above as PyOS_AfterFork_Parent() calls back
  1081. * into Python code which would see the unreturned error. */
  1082. PyErr_SetFromErrno(PyExc_OSError);
  1083. }
  1084. Py_XDECREF(preexec_fn_args_tuple);
  1085. PyMem_RawFree(extra_groups);
  1086. Py_XDECREF(cwd_obj2);
  1087. if (envp)
  1088. _Py_FreeCharPArray(envp);
  1089. Py_XDECREF(converted_args);
  1090. Py_XDECREF(fast_args);
  1091. if (argv)
  1092. _Py_FreeCharPArray(argv);
  1093. if (exec_array)
  1094. _Py_FreeCharPArray(exec_array);
  1095. if (need_to_reenable_gc) {
  1096. PyGC_Enable();
  1097. }
  1098. return pid == -1 ? NULL : PyLong_FromPid(pid);
  1099. }
  1100. /* module level code ********************************************************/
  1101. PyDoc_STRVAR(module_doc,
  1102. "A POSIX helper for the subprocess module.");
  1103. static PyMethodDef module_methods[] = {
  1104. SUBPROCESS_FORK_EXEC_METHODDEF
  1105. {NULL, NULL} /* sentinel */
  1106. };
  1107. static PyModuleDef_Slot _posixsubprocess_slots[] = {
  1108. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1109. {0, NULL}
  1110. };
  1111. static struct PyModuleDef _posixsubprocessmodule = {
  1112. PyModuleDef_HEAD_INIT,
  1113. .m_name = "_posixsubprocess",
  1114. .m_doc = module_doc,
  1115. .m_size = 0,
  1116. .m_methods = module_methods,
  1117. .m_slots = _posixsubprocess_slots,
  1118. };
  1119. PyMODINIT_FUNC
  1120. PyInit__posixsubprocess(void)
  1121. {
  1122. return PyModuleDef_Init(&_posixsubprocessmodule);
  1123. }