posix_spawn.c 2.3 KB

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