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