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