process.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to
  5. * deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  7. * sell copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  19. * IN THE SOFTWARE.
  20. */
  21. #include "uv.h"
  22. #include "internal.h"
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <assert.h>
  26. #include <errno.h>
  27. #include <signal.h>
  28. #include <string.h>
  29. #include <sys/types.h>
  30. #include <sys/wait.h>
  31. #include <unistd.h>
  32. #include <fcntl.h>
  33. #include <poll.h>
  34. #include <sched.h>
  35. #if defined(__APPLE__)
  36. /* macOS 10.8 and later have a working posix_spawn */
  37. # if MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  38. # define UV_USE_APPLE_POSIX_SPAWN
  39. # include <spawn.h>
  40. # endif
  41. # include <paths.h>
  42. # include <sys/kauth.h>
  43. # include <sys/types.h>
  44. # include <sys/sysctl.h>
  45. # include <dlfcn.h>
  46. # include <crt_externs.h>
  47. # include <xlocale.h>
  48. # define environ (*_NSGetEnviron())
  49. /* macOS 10.14 back does not define this constant */
  50. # ifndef POSIX_SPAWN_SETSID
  51. # define POSIX_SPAWN_SETSID 1024
  52. # endif
  53. #else
  54. extern char **environ;
  55. #endif
  56. #if defined(__linux__) || defined(__GLIBC__)
  57. # include <grp.h>
  58. #endif
  59. #if defined(__MVS__)
  60. # include "zos-base.h"
  61. #endif
  62. #ifndef CMAKE_BOOTSTRAP
  63. #if defined(__linux__)
  64. # define uv__cpu_set_t cpu_set_t
  65. #elif defined(__FreeBSD__)
  66. # include <sys/param.h>
  67. # include <sys/cpuset.h>
  68. # include <pthread_np.h>
  69. # define uv__cpu_set_t cpuset_t
  70. #endif
  71. #endif
  72. #ifdef CMAKE_BOOTSTRAP
  73. #define UV_USE_SIGCHLD
  74. #elif defined(__APPLE__) || \
  75. defined(__DragonFly__) || \
  76. defined(__FreeBSD__) || \
  77. defined(__NetBSD__) || \
  78. defined(__OpenBSD__)
  79. #include <sys/event.h>
  80. #else
  81. #define UV_USE_SIGCHLD
  82. #endif
  83. #ifdef UV_USE_SIGCHLD
  84. static void uv__chld(uv_signal_t* handle, int signum) {
  85. assert(signum == SIGCHLD);
  86. uv__wait_children(handle->loop);
  87. }
  88. #endif
  89. void uv__wait_children(uv_loop_t* loop) {
  90. uv_process_t* process;
  91. int exit_status;
  92. int term_signal;
  93. int status;
  94. int options;
  95. pid_t pid;
  96. QUEUE pending;
  97. QUEUE* q;
  98. QUEUE* h;
  99. QUEUE_INIT(&pending);
  100. h = &loop->process_handles;
  101. q = QUEUE_HEAD(h);
  102. while (q != h) {
  103. process = QUEUE_DATA(q, uv_process_t, queue);
  104. q = QUEUE_NEXT(q);
  105. #ifndef UV_USE_SIGCHLD
  106. if ((process->flags & UV_HANDLE_REAP) == 0)
  107. continue;
  108. options = 0;
  109. process->flags &= ~UV_HANDLE_REAP;
  110. #else
  111. options = WNOHANG;
  112. #endif
  113. do
  114. pid = waitpid(process->pid, &status, options);
  115. while (pid == -1 && errno == EINTR);
  116. #ifdef UV_USE_SIGCHLD
  117. if (pid == 0) /* Not yet exited */
  118. continue;
  119. #endif
  120. if (pid == -1) {
  121. if (errno != ECHILD)
  122. abort();
  123. /* The child died, and we missed it. This probably means someone else
  124. * stole the waitpid from us. Handle this by not handling it at all. */
  125. continue;
  126. }
  127. assert(pid == process->pid);
  128. process->status = status;
  129. QUEUE_REMOVE(&process->queue);
  130. QUEUE_INSERT_TAIL(&pending, &process->queue);
  131. }
  132. h = &pending;
  133. q = QUEUE_HEAD(h);
  134. while (q != h) {
  135. process = QUEUE_DATA(q, uv_process_t, queue);
  136. q = QUEUE_NEXT(q);
  137. QUEUE_REMOVE(&process->queue);
  138. QUEUE_INIT(&process->queue);
  139. uv__handle_stop(process);
  140. if (process->exit_cb == NULL)
  141. continue;
  142. exit_status = 0;
  143. if (WIFEXITED(process->status))
  144. exit_status = WEXITSTATUS(process->status);
  145. term_signal = 0;
  146. if (WIFSIGNALED(process->status))
  147. term_signal = WTERMSIG(process->status);
  148. process->exit_cb(process, exit_status, term_signal);
  149. }
  150. assert(QUEUE_EMPTY(&pending));
  151. }
  152. /*
  153. * Used for initializing stdio streams like options.stdin_stream. Returns
  154. * zero on success. See also the cleanup section in uv_spawn().
  155. */
  156. static int uv__process_init_stdio(uv_stdio_container_t* container, int fds[2]) {
  157. int mask;
  158. int fd;
  159. mask = UV_IGNORE | UV_CREATE_PIPE | UV_INHERIT_FD | UV_INHERIT_STREAM;
  160. switch (container->flags & mask) {
  161. case UV_IGNORE:
  162. return 0;
  163. case UV_CREATE_PIPE:
  164. assert(container->data.stream != NULL);
  165. if (container->data.stream->type != UV_NAMED_PIPE)
  166. return UV_EINVAL;
  167. else
  168. return uv_socketpair(SOCK_STREAM, 0, fds, 0, 0);
  169. case UV_INHERIT_FD:
  170. case UV_INHERIT_STREAM:
  171. if (container->flags & UV_INHERIT_FD)
  172. fd = container->data.fd;
  173. else
  174. fd = uv__stream_fd(container->data.stream);
  175. if (fd == -1)
  176. return UV_EINVAL;
  177. fds[1] = fd;
  178. return 0;
  179. default:
  180. assert(0 && "Unexpected flags");
  181. return UV_EINVAL;
  182. }
  183. }
  184. static int uv__process_open_stream(uv_stdio_container_t* container,
  185. int pipefds[2]) {
  186. int flags;
  187. int err;
  188. if (!(container->flags & UV_CREATE_PIPE) || pipefds[0] < 0)
  189. return 0;
  190. err = uv__close(pipefds[1]);
  191. if (err != 0)
  192. abort();
  193. pipefds[1] = -1;
  194. uv__nonblock(pipefds[0], 1);
  195. flags = 0;
  196. if (container->flags & UV_WRITABLE_PIPE)
  197. flags |= UV_HANDLE_READABLE;
  198. if (container->flags & UV_READABLE_PIPE)
  199. flags |= UV_HANDLE_WRITABLE;
  200. return uv__stream_open(container->data.stream, pipefds[0], flags);
  201. }
  202. static void uv__process_close_stream(uv_stdio_container_t* container) {
  203. if (!(container->flags & UV_CREATE_PIPE)) return;
  204. uv__stream_close(container->data.stream);
  205. }
  206. static void uv__write_int(int fd, int val) {
  207. ssize_t n;
  208. do
  209. n = write(fd, &val, sizeof(val));
  210. while (n == -1 && errno == EINTR);
  211. /* The write might have failed (e.g. if the parent process has died),
  212. * but we have nothing left but to _exit ourself now too. */
  213. _exit(127);
  214. }
  215. static void uv__write_errno(int error_fd) {
  216. uv__write_int(error_fd, UV__ERR(errno));
  217. }
  218. #if !(defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH))
  219. /* execvp is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED, so must be
  220. * avoided. Since this isn't called on those targets, the function
  221. * doesn't even need to be defined for them.
  222. */
  223. static void uv__process_child_init(const uv_process_options_t* options,
  224. int stdio_count,
  225. int (*pipes)[2],
  226. int error_fd) {
  227. sigset_t signewset;
  228. int close_fd;
  229. int use_fd;
  230. int fd;
  231. int n;
  232. #ifndef CMAKE_BOOTSTRAP
  233. #if defined(__linux__) || defined(__FreeBSD__)
  234. int r;
  235. int i;
  236. int cpumask_size;
  237. uv__cpu_set_t cpuset;
  238. #endif
  239. #endif
  240. /* Reset signal disposition first. Use a hard-coded limit because NSIG is not
  241. * fixed on Linux: it's either 32, 34 or 64, depending on whether RT signals
  242. * are enabled. We are not allowed to touch RT signal handlers, glibc uses
  243. * them internally.
  244. */
  245. for (n = 1; n < 32; n += 1) {
  246. if (n == SIGKILL || n == SIGSTOP)
  247. continue; /* Can't be changed. */
  248. #if defined(__HAIKU__)
  249. if (n == SIGKILLTHR)
  250. continue; /* Can't be changed. */
  251. #endif
  252. if (SIG_ERR != signal(n, SIG_DFL))
  253. continue;
  254. uv__write_errno(error_fd);
  255. }
  256. if (options->flags & UV_PROCESS_DETACHED)
  257. setsid();
  258. /* First duplicate low numbered fds, since it's not safe to duplicate them,
  259. * they could get replaced. Example: swapping stdout and stderr; without
  260. * this fd 2 (stderr) would be duplicated into fd 1, thus making both
  261. * stdout and stderr go to the same fd, which was not the intention. */
  262. for (fd = 0; fd < stdio_count; fd++) {
  263. use_fd = pipes[fd][1];
  264. if (use_fd < 0 || use_fd >= fd)
  265. continue;
  266. #ifdef F_DUPFD_CLOEXEC /* POSIX 2008 */
  267. pipes[fd][1] = fcntl(use_fd, F_DUPFD_CLOEXEC, stdio_count);
  268. #else
  269. pipes[fd][1] = fcntl(use_fd, F_DUPFD, stdio_count);
  270. #endif
  271. if (pipes[fd][1] == -1)
  272. uv__write_errno(error_fd);
  273. #ifndef F_DUPFD_CLOEXEC /* POSIX 2008 */
  274. n = uv__cloexec(pipes[fd][1], 1);
  275. if (n)
  276. uv__write_int(error_fd, n);
  277. #endif
  278. }
  279. for (fd = 0; fd < stdio_count; fd++) {
  280. close_fd = -1;
  281. use_fd = pipes[fd][1];
  282. if (use_fd < 0) {
  283. if (fd >= 3)
  284. continue;
  285. else {
  286. /* Redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is
  287. * set. */
  288. uv__close_nocheckstdio(fd); /* Free up fd, if it happens to be open. */
  289. use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR);
  290. close_fd = use_fd;
  291. if (use_fd < 0)
  292. uv__write_errno(error_fd);
  293. }
  294. }
  295. if (fd == use_fd) {
  296. if (close_fd == -1) {
  297. n = uv__cloexec(use_fd, 0);
  298. if (n)
  299. uv__write_int(error_fd, n);
  300. }
  301. }
  302. else {
  303. fd = dup2(use_fd, fd);
  304. }
  305. if (fd == -1)
  306. uv__write_errno(error_fd);
  307. if (fd <= 2 && close_fd == -1)
  308. uv__nonblock_fcntl(fd, 0);
  309. if (close_fd >= stdio_count)
  310. uv__close(close_fd);
  311. }
  312. if (options->cwd != NULL && chdir(options->cwd))
  313. uv__write_errno(error_fd);
  314. if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) {
  315. /* When dropping privileges from root, the `setgroups` call will
  316. * remove any extraneous groups. If we don't call this, then
  317. * even though our uid has dropped, we may still have groups
  318. * that enable us to do super-user things. This will fail if we
  319. * aren't root, so don't bother checking the return value, this
  320. * is just done as an optimistic privilege dropping function.
  321. */
  322. SAVE_ERRNO(setgroups(0, NULL));
  323. }
  324. if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid))
  325. uv__write_errno(error_fd);
  326. if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid))
  327. uv__write_errno(error_fd);
  328. #ifndef CMAKE_BOOTSTRAP
  329. #if defined(__linux__) || defined(__FreeBSD__)
  330. if (options->cpumask != NULL) {
  331. cpumask_size = uv_cpumask_size();
  332. assert(options->cpumask_size >= (size_t)cpumask_size);
  333. CPU_ZERO(&cpuset);
  334. for (i = 0; i < cpumask_size; ++i) {
  335. if (options->cpumask[i]) {
  336. CPU_SET(i, &cpuset);
  337. }
  338. }
  339. r = -pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
  340. if (r != 0) {
  341. uv__write_int(error_fd, r);
  342. _exit(127);
  343. }
  344. }
  345. #endif
  346. #endif
  347. if (options->env != NULL)
  348. environ = options->env;
  349. /* Reset signal mask just before exec. */
  350. sigemptyset(&signewset);
  351. if (sigprocmask(SIG_SETMASK, &signewset, NULL) != 0)
  352. abort();
  353. #ifdef __MVS__
  354. execvpe(options->file, options->args, environ);
  355. #else
  356. execvp(options->file, options->args);
  357. #endif
  358. uv__write_errno(error_fd);
  359. }
  360. #endif
  361. #if defined(UV_USE_APPLE_POSIX_SPAWN)
  362. typedef struct uv__posix_spawn_fncs_tag {
  363. struct {
  364. int (*addchdir_np)(const posix_spawn_file_actions_t *, const char *);
  365. } file_actions;
  366. } uv__posix_spawn_fncs_t;
  367. static uv_once_t posix_spawn_init_once = UV_ONCE_INIT;
  368. static uv__posix_spawn_fncs_t posix_spawn_fncs;
  369. static int posix_spawn_can_use_setsid;
  370. static void uv__spawn_init_posix_spawn_fncs(void) {
  371. /* Try to locate all non-portable functions at runtime */
  372. posix_spawn_fncs.file_actions.addchdir_np =
  373. dlsym(RTLD_DEFAULT, "posix_spawn_file_actions_addchdir_np");
  374. }
  375. static void uv__spawn_init_can_use_setsid(void) {
  376. int which[] = {CTL_KERN, KERN_OSRELEASE};
  377. unsigned major;
  378. unsigned minor;
  379. unsigned patch;
  380. char buf[256];
  381. size_t len;
  382. len = sizeof(buf);
  383. if (sysctl(which, ARRAY_SIZE(which), buf, &len, NULL, 0))
  384. return;
  385. /* NULL specifies to use LC_C_LOCALE */
  386. if (3 != sscanf_l(buf, NULL, "%u.%u.%u", &major, &minor, &patch))
  387. return;
  388. posix_spawn_can_use_setsid = (major >= 19); /* macOS Catalina */
  389. }
  390. static void uv__spawn_init_posix_spawn(void) {
  391. /* Init handles to all potentially non-defined functions */
  392. uv__spawn_init_posix_spawn_fncs();
  393. /* Init feature detection for POSIX_SPAWN_SETSID flag */
  394. uv__spawn_init_can_use_setsid();
  395. }
  396. static int uv__spawn_set_posix_spawn_attrs(
  397. posix_spawnattr_t* attrs,
  398. const uv__posix_spawn_fncs_t* posix_spawn_fncs,
  399. const uv_process_options_t* options) {
  400. int err;
  401. unsigned int flags;
  402. sigset_t signal_set;
  403. err = posix_spawnattr_init(attrs);
  404. if (err != 0) {
  405. /* If initialization fails, no need to de-init, just return */
  406. return err;
  407. }
  408. if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) {
  409. /* kauth_cred_issuser currently requires exactly uid == 0 for these
  410. * posixspawn_attrs (set_groups_np, setuid_np, setgid_np), which deviates
  411. * from the normal specification of setuid (which also uses euid), and they
  412. * are also undocumented syscalls, so we do not use them. */
  413. err = ENOSYS;
  414. goto error;
  415. }
  416. /* Set flags for spawn behavior
  417. * 1) POSIX_SPAWN_CLOEXEC_DEFAULT: (Apple Extension) All descriptors in the
  418. * parent will be treated as if they had been created with O_CLOEXEC. The
  419. * only fds that will be passed on to the child are those manipulated by
  420. * the file actions
  421. * 2) POSIX_SPAWN_SETSIGDEF: Signals mentioned in spawn-sigdefault in the
  422. * spawn attributes will be reset to behave as their default
  423. * 3) POSIX_SPAWN_SETSIGMASK: Signal mask will be set to the value of
  424. * spawn-sigmask in attributes
  425. * 4) POSIX_SPAWN_SETSID: Make the process a new session leader if a detached
  426. * session was requested. */
  427. flags = POSIX_SPAWN_CLOEXEC_DEFAULT |
  428. POSIX_SPAWN_SETSIGDEF |
  429. POSIX_SPAWN_SETSIGMASK;
  430. if (options->flags & UV_PROCESS_DETACHED) {
  431. /* If running on a version of macOS where this flag is not supported,
  432. * revert back to the fork/exec flow. Otherwise posix_spawn will
  433. * silently ignore the flag. */
  434. if (!posix_spawn_can_use_setsid) {
  435. err = ENOSYS;
  436. goto error;
  437. }
  438. flags |= POSIX_SPAWN_SETSID;
  439. }
  440. err = posix_spawnattr_setflags(attrs, flags);
  441. if (err != 0)
  442. goto error;
  443. /* Reset all signal the child to their default behavior */
  444. sigfillset(&signal_set);
  445. err = posix_spawnattr_setsigdefault(attrs, &signal_set);
  446. if (err != 0)
  447. goto error;
  448. /* Reset the signal mask for all signals */
  449. sigemptyset(&signal_set);
  450. err = posix_spawnattr_setsigmask(attrs, &signal_set);
  451. if (err != 0)
  452. goto error;
  453. return err;
  454. error:
  455. (void) posix_spawnattr_destroy(attrs);
  456. return err;
  457. }
  458. static int uv__spawn_set_posix_spawn_file_actions(
  459. posix_spawn_file_actions_t* actions,
  460. const uv__posix_spawn_fncs_t* posix_spawn_fncs,
  461. const uv_process_options_t* options,
  462. int stdio_count,
  463. int (*pipes)[2]) {
  464. int fd;
  465. int fd2;
  466. int use_fd;
  467. int err;
  468. err = posix_spawn_file_actions_init(actions);
  469. if (err != 0) {
  470. /* If initialization fails, no need to de-init, just return */
  471. return err;
  472. }
  473. /* Set the current working directory if requested */
  474. if (options->cwd != NULL) {
  475. if (posix_spawn_fncs->file_actions.addchdir_np == NULL) {
  476. err = ENOSYS;
  477. goto error;
  478. }
  479. err = posix_spawn_fncs->file_actions.addchdir_np(actions, options->cwd);
  480. if (err != 0)
  481. goto error;
  482. }
  483. /* Do not return ENOSYS after this point, as we may mutate pipes. */
  484. /* First duplicate low numbered fds, since it's not safe to duplicate them,
  485. * they could get replaced. Example: swapping stdout and stderr; without
  486. * this fd 2 (stderr) would be duplicated into fd 1, thus making both
  487. * stdout and stderr go to the same fd, which was not the intention. */
  488. for (fd = 0; fd < stdio_count; fd++) {
  489. use_fd = pipes[fd][1];
  490. if (use_fd < 0 || use_fd >= fd)
  491. continue;
  492. use_fd = stdio_count;
  493. for (fd2 = 0; fd2 < stdio_count; fd2++) {
  494. /* If we were not setting POSIX_SPAWN_CLOEXEC_DEFAULT, we would need to
  495. * also consider whether fcntl(fd, F_GETFD) returned without the
  496. * FD_CLOEXEC flag set. */
  497. if (pipes[fd2][1] == use_fd) {
  498. use_fd++;
  499. fd2 = 0;
  500. }
  501. }
  502. err = posix_spawn_file_actions_adddup2(
  503. actions,
  504. pipes[fd][1],
  505. use_fd);
  506. assert(err != ENOSYS);
  507. if (err != 0)
  508. goto error;
  509. pipes[fd][1] = use_fd;
  510. }
  511. /* Second, move the descriptors into their respective places */
  512. for (fd = 0; fd < stdio_count; fd++) {
  513. use_fd = pipes[fd][1];
  514. if (use_fd < 0) {
  515. if (fd >= 3)
  516. continue;
  517. else {
  518. /* If ignored, redirect to (or from) /dev/null, */
  519. err = posix_spawn_file_actions_addopen(
  520. actions,
  521. fd,
  522. "/dev/null",
  523. fd == 0 ? O_RDONLY : O_RDWR,
  524. 0);
  525. assert(err != ENOSYS);
  526. if (err != 0)
  527. goto error;
  528. continue;
  529. }
  530. }
  531. if (fd == use_fd)
  532. err = posix_spawn_file_actions_addinherit_np(actions, fd);
  533. else
  534. err = posix_spawn_file_actions_adddup2(actions, use_fd, fd);
  535. assert(err != ENOSYS);
  536. if (err != 0)
  537. goto error;
  538. /* Make sure the fd is marked as non-blocking (state shared between child
  539. * and parent). */
  540. uv__nonblock_fcntl(use_fd, 0);
  541. }
  542. /* Finally, close all the superfluous descriptors */
  543. for (fd = 0; fd < stdio_count; fd++) {
  544. use_fd = pipes[fd][1];
  545. if (use_fd < stdio_count)
  546. continue;
  547. /* Check if we already closed this. */
  548. for (fd2 = 0; fd2 < fd; fd2++) {
  549. if (pipes[fd2][1] == use_fd)
  550. break;
  551. }
  552. if (fd2 < fd)
  553. continue;
  554. err = posix_spawn_file_actions_addclose(actions, use_fd);
  555. assert(err != ENOSYS);
  556. if (err != 0)
  557. goto error;
  558. }
  559. return 0;
  560. error:
  561. (void) posix_spawn_file_actions_destroy(actions);
  562. return err;
  563. }
  564. char* uv__spawn_find_path_in_env(char** env) {
  565. char** env_iterator;
  566. const char path_var[] = "PATH=";
  567. /* Look for an environment variable called PATH in the
  568. * provided env array, and return its value if found */
  569. for (env_iterator = env; *env_iterator != NULL; env_iterator++) {
  570. if (strncmp(*env_iterator, path_var, sizeof(path_var) - 1) == 0) {
  571. /* Found "PATH=" at the beginning of the string */
  572. return *env_iterator + sizeof(path_var) - 1;
  573. }
  574. }
  575. return NULL;
  576. }
  577. static int uv__spawn_resolve_and_spawn(const uv_process_options_t* options,
  578. posix_spawnattr_t* attrs,
  579. posix_spawn_file_actions_t* actions,
  580. pid_t* pid) {
  581. const char *p;
  582. const char *z;
  583. const char *path;
  584. size_t l;
  585. size_t k;
  586. int err;
  587. int seen_eacces;
  588. path = NULL;
  589. err = -1;
  590. seen_eacces = 0;
  591. /* Short circuit for erroneous case */
  592. if (options->file == NULL)
  593. return ENOENT;
  594. /* The environment for the child process is that of the parent unless overriden
  595. * by options->env */
  596. char** env = environ;
  597. if (options->env != NULL)
  598. env = options->env;
  599. /* If options->file contains a slash, posix_spawn/posix_spawnp should behave
  600. * the same, and do not involve PATH resolution at all. The libc
  601. * `posix_spawnp` provided by Apple is buggy (since 10.15), so we now emulate it
  602. * here, per https://github.com/libuv/libuv/pull/3583. */
  603. if (strchr(options->file, '/') != NULL) {
  604. do
  605. err = posix_spawn(pid, options->file, actions, attrs, options->args, env);
  606. while (err == EINTR);
  607. return err;
  608. }
  609. /* Look for the definition of PATH in the provided env */
  610. path = uv__spawn_find_path_in_env(env);
  611. /* The following resolution logic (execvpe emulation) is copied from
  612. * https://git.musl-libc.org/cgit/musl/tree/src/process/execvp.c
  613. * and adapted to work for our specific usage */
  614. /* If no path was provided in env, use the default value
  615. * to look for the executable */
  616. if (path == NULL)
  617. path = _PATH_DEFPATH;
  618. k = strnlen(options->file, NAME_MAX + 1);
  619. if (k > NAME_MAX)
  620. return ENAMETOOLONG;
  621. l = strnlen(path, PATH_MAX - 1) + 1;
  622. for (p = path;; p = z) {
  623. /* Compose the new process file from the entry in the PATH
  624. * environment variable and the actual file name */
  625. char b[PATH_MAX + NAME_MAX];
  626. z = strchr(p, ':');
  627. if (!z)
  628. z = p + strlen(p);
  629. if ((size_t)(z - p) >= l) {
  630. if (!*z++)
  631. break;
  632. continue;
  633. }
  634. memcpy(b, p, z - p);
  635. b[z - p] = '/';
  636. memcpy(b + (z - p) + (z > p), options->file, k + 1);
  637. /* Try to spawn the new process file. If it fails with ENOENT, the
  638. * new process file is not in this PATH entry, continue with the next
  639. * PATH entry. */
  640. do
  641. err = posix_spawn(pid, b, actions, attrs, options->args, env);
  642. while (err == EINTR);
  643. switch (err) {
  644. case EACCES:
  645. seen_eacces = 1;
  646. break; /* continue search */
  647. case ENOENT:
  648. case ENOTDIR:
  649. break; /* continue search */
  650. default:
  651. return err;
  652. }
  653. if (!*z++)
  654. break;
  655. }
  656. if (seen_eacces)
  657. return EACCES;
  658. return err;
  659. }
  660. static int uv__spawn_and_init_child_posix_spawn(
  661. const uv_process_options_t* options,
  662. int stdio_count,
  663. int (*pipes)[2],
  664. pid_t* pid,
  665. const uv__posix_spawn_fncs_t* posix_spawn_fncs) {
  666. int err;
  667. posix_spawnattr_t attrs;
  668. posix_spawn_file_actions_t actions;
  669. err = uv__spawn_set_posix_spawn_attrs(&attrs, posix_spawn_fncs, options);
  670. if (err != 0)
  671. goto error;
  672. /* This may mutate pipes. */
  673. err = uv__spawn_set_posix_spawn_file_actions(&actions,
  674. posix_spawn_fncs,
  675. options,
  676. stdio_count,
  677. pipes);
  678. if (err != 0) {
  679. (void) posix_spawnattr_destroy(&attrs);
  680. goto error;
  681. }
  682. /* Try to spawn options->file resolving in the provided environment
  683. * if any */
  684. err = uv__spawn_resolve_and_spawn(options, &attrs, &actions, pid);
  685. assert(err != ENOSYS);
  686. /* Destroy the actions/attributes */
  687. (void) posix_spawn_file_actions_destroy(&actions);
  688. (void) posix_spawnattr_destroy(&attrs);
  689. error:
  690. /* In an error situation, the attributes and file actions are
  691. * already destroyed, only the happy path requires cleanup */
  692. return UV__ERR(err);
  693. }
  694. #endif
  695. static int uv__spawn_and_init_child_fork(const uv_process_options_t* options,
  696. int stdio_count,
  697. int (*pipes)[2],
  698. int error_fd,
  699. pid_t* pid) {
  700. sigset_t signewset;
  701. sigset_t sigoldset;
  702. /* Start the child with most signals blocked, to avoid any issues before we
  703. * can reset them, but allow program failures to exit (and not hang). */
  704. sigfillset(&signewset);
  705. sigdelset(&signewset, SIGKILL);
  706. sigdelset(&signewset, SIGSTOP);
  707. sigdelset(&signewset, SIGTRAP);
  708. sigdelset(&signewset, SIGSEGV);
  709. sigdelset(&signewset, SIGBUS);
  710. sigdelset(&signewset, SIGILL);
  711. sigdelset(&signewset, SIGSYS);
  712. sigdelset(&signewset, SIGABRT);
  713. if (pthread_sigmask(SIG_BLOCK, &signewset, &sigoldset) != 0)
  714. abort();
  715. *pid = fork();
  716. if (*pid == 0) {
  717. /* Fork succeeded, in the child process */
  718. uv__process_child_init(options, stdio_count, pipes, error_fd);
  719. abort();
  720. }
  721. if (pthread_sigmask(SIG_SETMASK, &sigoldset, NULL) != 0)
  722. abort();
  723. if (*pid == -1)
  724. /* Failed to fork */
  725. return UV__ERR(errno);
  726. /* Fork succeeded, in the parent process */
  727. return 0;
  728. }
  729. static int uv__spawn_and_init_child(
  730. uv_loop_t* loop,
  731. const uv_process_options_t* options,
  732. int stdio_count,
  733. int (*pipes)[2],
  734. pid_t* pid) {
  735. int signal_pipe[2] = { -1, -1 };
  736. int status;
  737. int err;
  738. int exec_errorno;
  739. ssize_t r;
  740. #if defined(UV_USE_APPLE_POSIX_SPAWN)
  741. uv_once(&posix_spawn_init_once, uv__spawn_init_posix_spawn);
  742. /* Special child process spawn case for macOS Big Sur (11.0) onwards
  743. *
  744. * Big Sur introduced a significant performance degradation on a call to
  745. * fork/exec when the process has many pages mmaped in with MAP_JIT, like, say
  746. * a javascript interpreter. Electron-based applications, for example,
  747. * are impacted; though the magnitude of the impact depends on how much the
  748. * app relies on subprocesses.
  749. *
  750. * On macOS, though, posix_spawn is implemented in a way that does not
  751. * exhibit the problem. This block implements the forking and preparation
  752. * logic with posix_spawn and its related primitives. It also takes advantage of
  753. * the macOS extension POSIX_SPAWN_CLOEXEC_DEFAULT that makes impossible to
  754. * leak descriptors to the child process. */
  755. err = uv__spawn_and_init_child_posix_spawn(options,
  756. stdio_count,
  757. pipes,
  758. pid,
  759. &posix_spawn_fncs);
  760. /* The posix_spawn flow will return UV_ENOSYS if any of the posix_spawn_x_np
  761. * non-standard functions is both _needed_ and _undefined_. In those cases,
  762. * default back to the fork/execve strategy. For all other errors, just fail. */
  763. if (err != UV_ENOSYS)
  764. return err;
  765. #endif
  766. /* This pipe is used by the parent to wait until
  767. * the child has called `execve()`. We need this
  768. * to avoid the following race condition:
  769. *
  770. * if ((pid = fork()) > 0) {
  771. * kill(pid, SIGTERM);
  772. * }
  773. * else if (pid == 0) {
  774. * execve("/bin/cat", argp, envp);
  775. * }
  776. *
  777. * The parent sends a signal immediately after forking.
  778. * Since the child may not have called `execve()` yet,
  779. * there is no telling what process receives the signal,
  780. * our fork or /bin/cat.
  781. *
  782. * To avoid ambiguity, we create a pipe with both ends
  783. * marked close-on-exec. Then, after the call to `fork()`,
  784. * the parent polls the read end until it EOFs or errors with EPIPE.
  785. */
  786. err = uv__make_pipe(signal_pipe, 0);
  787. if (err)
  788. return err;
  789. /* Acquire write lock to prevent opening new fds in worker threads */
  790. uv_rwlock_wrlock(&loop->cloexec_lock);
  791. err = uv__spawn_and_init_child_fork(options, stdio_count, pipes, signal_pipe[1], pid);
  792. /* Release lock in parent process */
  793. uv_rwlock_wrunlock(&loop->cloexec_lock);
  794. uv__close(signal_pipe[1]);
  795. if (err == 0) {
  796. do
  797. r = read(signal_pipe[0], &exec_errorno, sizeof(exec_errorno));
  798. while (r == -1 && errno == EINTR);
  799. if (r == 0)
  800. ; /* okay, EOF */
  801. else if (r == sizeof(exec_errorno)) {
  802. do
  803. err = waitpid(*pid, &status, 0); /* okay, read errorno */
  804. while (err == -1 && errno == EINTR);
  805. assert(err == *pid);
  806. err = exec_errorno;
  807. } else if (r == -1 && errno == EPIPE) {
  808. /* Something unknown happened to our child before spawn */
  809. do
  810. err = waitpid(*pid, &status, 0); /* okay, got EPIPE */
  811. while (err == -1 && errno == EINTR);
  812. assert(err == *pid);
  813. err = UV_EPIPE;
  814. } else
  815. abort();
  816. }
  817. uv__close_nocheckstdio(signal_pipe[0]);
  818. return err;
  819. }
  820. int uv_spawn(uv_loop_t* loop,
  821. uv_process_t* process,
  822. const uv_process_options_t* options) {
  823. #if defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH)
  824. /* fork is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED. */
  825. return UV_ENOSYS;
  826. #else
  827. int pipes_storage[8][2];
  828. int (*pipes)[2];
  829. int stdio_count;
  830. pid_t pid;
  831. int err;
  832. int exec_errorno;
  833. int i;
  834. if (options->cpumask != NULL) {
  835. #ifndef CMAKE_BOOTSTRAP
  836. #if defined(__linux__) || defined(__FreeBSD__)
  837. if (options->cpumask_size < (size_t)uv_cpumask_size()) {
  838. return UV_EINVAL;
  839. }
  840. #else
  841. return UV_ENOTSUP;
  842. #endif
  843. #else
  844. return UV_ENOTSUP;
  845. #endif
  846. }
  847. assert(options->file != NULL);
  848. assert(!(options->flags & ~(UV_PROCESS_DETACHED |
  849. UV_PROCESS_SETGID |
  850. UV_PROCESS_SETUID |
  851. UV_PROCESS_WINDOWS_FILE_PATH_EXACT_NAME |
  852. UV_PROCESS_WINDOWS_HIDE |
  853. UV_PROCESS_WINDOWS_HIDE_CONSOLE |
  854. UV_PROCESS_WINDOWS_HIDE_GUI |
  855. UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
  856. uv__handle_init(loop, (uv_handle_t*)process, UV_PROCESS);
  857. QUEUE_INIT(&process->queue);
  858. process->status = 0;
  859. stdio_count = options->stdio_count;
  860. if (stdio_count < 3)
  861. stdio_count = 3;
  862. err = UV_ENOMEM;
  863. pipes = pipes_storage;
  864. if (stdio_count > (int) ARRAY_SIZE(pipes_storage))
  865. pipes = uv__malloc(stdio_count * sizeof(*pipes));
  866. if (pipes == NULL)
  867. goto error;
  868. for (i = 0; i < stdio_count; i++) {
  869. pipes[i][0] = -1;
  870. pipes[i][1] = -1;
  871. }
  872. for (i = 0; i < options->stdio_count; i++) {
  873. err = uv__process_init_stdio(options->stdio + i, pipes[i]);
  874. if (err)
  875. goto error;
  876. }
  877. #ifdef UV_USE_SIGCHLD
  878. uv_signal_start(&loop->child_watcher, uv__chld, SIGCHLD);
  879. #endif
  880. /* Spawn the child */
  881. exec_errorno = uv__spawn_and_init_child(loop, options, stdio_count, pipes, &pid);
  882. #if 0
  883. /* This runs into a nodejs issue (it expects initialized streams, even if the
  884. * exec failed).
  885. * See https://github.com/libuv/libuv/pull/3107#issuecomment-782482608 */
  886. if (exec_errorno != 0)
  887. goto error;
  888. #endif
  889. /* Activate this handle if exec() happened successfully, even if we later
  890. * fail to open a stdio handle. This ensures we can eventually reap the child
  891. * with waitpid. */
  892. if (exec_errorno == 0) {
  893. #ifndef UV_USE_SIGCHLD
  894. struct kevent event;
  895. EV_SET(&event, pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, 0);
  896. if (kevent(loop->backend_fd, &event, 1, NULL, 0, NULL)) {
  897. if (errno != ESRCH)
  898. abort();
  899. /* Process already exited. Call waitpid on the next loop iteration. */
  900. process->flags |= UV_HANDLE_REAP;
  901. loop->flags |= UV_LOOP_REAP_CHILDREN;
  902. }
  903. #endif
  904. process->pid = pid;
  905. process->exit_cb = options->exit_cb;
  906. QUEUE_INSERT_TAIL(&loop->process_handles, &process->queue);
  907. uv__handle_start(process);
  908. }
  909. for (i = 0; i < options->stdio_count; i++) {
  910. err = uv__process_open_stream(options->stdio + i, pipes[i]);
  911. if (err == 0)
  912. continue;
  913. while (i--)
  914. uv__process_close_stream(options->stdio + i);
  915. goto error;
  916. }
  917. if (pipes != pipes_storage)
  918. uv__free(pipes);
  919. return exec_errorno;
  920. error:
  921. if (pipes != NULL) {
  922. for (i = 0; i < stdio_count; i++) {
  923. if (i < options->stdio_count)
  924. if (options->stdio[i].flags & (UV_INHERIT_FD | UV_INHERIT_STREAM))
  925. continue;
  926. if (pipes[i][0] != -1)
  927. uv__close_nocheckstdio(pipes[i][0]);
  928. if (pipes[i][1] != -1)
  929. uv__close_nocheckstdio(pipes[i][1]);
  930. }
  931. if (pipes != pipes_storage)
  932. uv__free(pipes);
  933. }
  934. return err;
  935. #endif
  936. }
  937. int uv_process_kill(uv_process_t* process, int signum) {
  938. return uv_kill(process->pid, signum);
  939. }
  940. int uv_kill(int pid, int signum) {
  941. if (kill(pid, signum)) {
  942. #if defined(__MVS__)
  943. /* EPERM is returned if the process is a zombie. */
  944. siginfo_t infop;
  945. if (errno == EPERM &&
  946. waitid(P_PID, pid, &infop, WNOHANG | WNOWAIT | WEXITED) == 0)
  947. return 0;
  948. #endif
  949. return UV__ERR(errno);
  950. } else
  951. return 0;
  952. }
  953. void uv__process_close(uv_process_t* handle) {
  954. QUEUE_REMOVE(&handle->queue);
  955. uv__handle_stop(handle);
  956. if (QUEUE_EMPTY(&handle->loop->process_handles))
  957. uv_signal_stop(&handle->loop->child_watcher);
  958. }