7018c37ef6e6a6bfb391f2f1c3b26004625a4544
[musl] / src / process / posix_spawn.c
1 #include <spawn.h>
2 #include <unistd.h>
3 #include <signal.h>
4 #include <stdint.h>
5 #include "syscall.h"
6
7 extern char **environ;
8
9 int __posix_spawnx(pid_t *res, const char *path,
10         int (*exec)(const char *, char *const *),
11         const posix_spawn_file_actions_t *fa,
12         const posix_spawnattr_t *attr, char **argv, char **envp)
13 {
14         pid_t pid;
15         sigset_t oldmask;
16         int i;
17         posix_spawnattr_t dummy_attr = { 0 };
18
19         if (!attr) attr = &dummy_attr;
20
21         sigprocmask(SIG_BLOCK, (void *)(uint64_t []){-1}, &oldmask);
22         pid = __syscall(SYS_fork);
23
24         if (pid) {
25                 sigprocmask(SIG_SETMASK, &oldmask, 0);
26                 if (pid < 0) return -pid;
27                 *res = pid;
28                 return 0;
29         }
30
31         for (i=1; i<=64; i++) {
32                 struct sigaction sa;
33                 sigaction(i, 0, &sa);
34                 if (sa.sa_handler!=SIG_IGN ||
35                     ((attr->__flags & POSIX_SPAWN_SETSIGDEF)
36                      && sigismember(&attr->__def, i) )) {
37                         sa.sa_handler = SIG_DFL;
38                         sigaction(i, &sa, 0);
39                 }
40         }
41
42         if ((attr->__flags&POSIX_SPAWN_SETPGROUP) && setpgid(0, attr->__pgrp))
43                 _exit(127);
44
45         /* Use syscalls directly because pthread state is not consistent
46          * for making calls to the library wrappers... */
47         if ((attr->__flags&POSIX_SPAWN_RESETIDS) && (
48                 __syscall(SYS_setgid, __syscall(SYS_getgid)) ||
49                 __syscall(SYS_setuid, __syscall(SYS_getuid)) ))
50                 _exit(127);
51
52         sigprocmask(SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK)
53                 ? &attr->__mask : &oldmask, 0);
54
55         if (envp) environ = envp;
56         exec(path, argv);
57         _exit(127);
58
59         return 0;
60 }
61
62 int posix_spawn(pid_t *res, const char *path,
63         const posix_spawn_file_actions_t *fa,
64         const posix_spawnattr_t *attr, char **argv, char **envp)
65 {
66         return __posix_spawnx(res, path, execv, fa, attr, argv, envp);
67 }