posix_spawn.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <spawn.h>
  2. #include <unistd.h>
  3. #include <signal.h>
  4. #include <stdint.h>
  5. #include <fcntl.h>
  6. #include "syscall.h"
  7. #include "fdop.h"
  8. extern char **environ;
  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. if (!attr) attr = &dummy_attr;
  19. sigprocmask(SIG_BLOCK, (void *)(uint64_t []){-1}, &oldmask);
  20. pid = __syscall(SYS_fork);
  21. if (pid) {
  22. sigprocmask(SIG_SETMASK, &oldmask, 0);
  23. if (pid < 0) return -pid;
  24. *res = pid;
  25. return 0;
  26. }
  27. for (i=1; i<=64; i++) {
  28. struct sigaction sa;
  29. sigaction(i, 0, &sa);
  30. if (sa.sa_handler!=SIG_IGN ||
  31. ((attr->__flags & POSIX_SPAWN_SETSIGDEF)
  32. && sigismember(&attr->__def, i) )) {
  33. sa.sa_handler = SIG_DFL;
  34. sigaction(i, &sa, 0);
  35. }
  36. }
  37. if ((attr->__flags&POSIX_SPAWN_SETPGROUP) && setpgid(0, attr->__pgrp))
  38. _exit(127);
  39. /* Use syscalls directly because pthread state is not consistent
  40. * for making calls to the library wrappers... */
  41. if ((attr->__flags&POSIX_SPAWN_RESETIDS) && (
  42. __syscall(SYS_setgid, __syscall(SYS_getgid)) ||
  43. __syscall(SYS_setuid, __syscall(SYS_getuid)) ))
  44. _exit(127);
  45. if (fa) {
  46. struct fdop *op;
  47. int ret, fd;
  48. for (op = fa->__actions; op; op = op->next) {
  49. switch(op->cmd) {
  50. case FDOP_CLOSE:
  51. ret = __syscall(SYS_close, op->fd);
  52. break;
  53. case FDOP_DUP2:
  54. ret = __syscall(SYS_dup2, op->fd, op->newfd)<0;
  55. break;
  56. case FDOP_OPEN:
  57. fd = __syscall(SYS_open, op->path,
  58. op->oflag | O_LARGEFILE, op->mode);
  59. if (fd == op->fd) {
  60. ret = 0;
  61. } else {
  62. ret = __syscall(SYS_dup2, fd, op->fd)<0;
  63. __syscall(SYS_close, fd);
  64. }
  65. break;
  66. }
  67. if (ret) _exit(127);
  68. }
  69. }
  70. sigprocmask(SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK)
  71. ? &attr->__mask : &oldmask, 0);
  72. if (envp) environ = envp;
  73. exec(path, argv);
  74. _exit(127);
  75. return 0;
  76. }
  77. int posix_spawn(pid_t *res, const char *path,
  78. const posix_spawn_file_actions_t *fa,
  79. const posix_spawnattr_t *attr, char **argv, char **envp)
  80. {
  81. return __posix_spawnx(res, path, execv, fa, attr, argv, envp);
  82. }