initial implementation of posix_spawn
[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 || sigismember(&attr->__def, i)) {
35                         sa.sa_handler = SIG_DFL;
36                         sigaction(i, &sa, 0);
37                 }
38         }
39
40         if ((attr->__flags&POSIX_SPAWN_SETPGROUP) && setpgid(0, attr->__pgrp))
41                 _exit(127);
42
43         /* Use syscalls directly because pthread state is not consistent
44          * for making calls to the library wrappers... */
45         if ((attr->__flags&POSIX_SPAWN_RESETIDS) && (
46                 __syscall(SYS_setgid, __syscall(SYS_getgid)) ||
47                 __syscall(SYS_setuid, __syscall(SYS_getuid)) ))
48                 _exit(127);
49
50         sigprocmask(SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK)
51                 ? &attr->__mask : &oldmask, 0);
52
53         if (envp) environ = envp;
54         exec(path, argv);
55         _exit(127);
56
57         return 0;
58 }
59
60 int posix_spawn(pid_t *res, const char *path,
61         const posix_spawn_file_actions_t *fa,
62         const posix_spawnattr_t *attr, char **argv, char **envp)
63 {
64         return __posix_spawnx(res, path, execv, fa, attr, argv, envp);
65 }