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