PageRenderTime 1461ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/sysdeps/unix/sysv/linux/spawni.c

https://github.com/hjl-tools/glibc
C | 433 lines | 260 code | 51 blank | 122 comment | 78 complexity | 96dd25f54a87cf30127c286fe2c20f80 MD5 | raw file
  1. /* POSIX spawn interface. Linux version.
  2. Copyright (C) 2016-2020 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #include <spawn.h>
  16. #include <fcntl.h>
  17. #include <paths.h>
  18. #include <string.h>
  19. #include <sys/resource.h>
  20. #include <sys/wait.h>
  21. #include <sys/param.h>
  22. #include <sys/mman.h>
  23. #include <not-cancel.h>
  24. #include <local-setxid.h>
  25. #include <shlib-compat.h>
  26. #include <nptl/pthreadP.h>
  27. #include <dl-sysdep.h>
  28. #include <libc-pointer-arith.h>
  29. #include <ldsodefs.h>
  30. #include "spawn_int.h"
  31. /* The Linux implementation of posix_spawn{p} uses the clone syscall directly
  32. with CLONE_VM and CLONE_VFORK flags and an allocated stack. The new stack
  33. and start function solves most the vfork limitation (possible parent
  34. clobber due stack spilling). The remaining issue are:
  35. 1. That no signal handlers must run in child context, to avoid corrupting
  36. parent's state.
  37. 2. The parent must ensure child's stack freeing.
  38. 3. Child must synchronize with parent to enforce 2. and to possible
  39. return execv issues.
  40. The first issue is solved by blocking all signals in child, even
  41. the NPTL-internal ones (SIGCANCEL and SIGSETXID). The second and
  42. third issue is done by a stack allocation in parent, and by using a
  43. field in struct spawn_args where the child can write an error
  44. code. CLONE_VFORK ensures that the parent does not run until the
  45. child has either exec'ed successfully or exited. */
  46. /* The Unix standard contains a long explanation of the way to signal
  47. an error after the fork() was successful. Since no new wait status
  48. was wanted there is no way to signal an error using one of the
  49. available methods. The committee chose to signal an error by a
  50. normal program exit with the exit code 127. */
  51. #define SPAWN_ERROR 127
  52. #ifdef __ia64__
  53. # define CLONE(__fn, __stackbase, __stacksize, __flags, __args) \
  54. __clone2 (__fn, __stackbase, __stacksize, __flags, __args, 0, 0, 0)
  55. #else
  56. # define CLONE(__fn, __stack, __stacksize, __flags, __args) \
  57. __clone (__fn, __stack, __flags, __args)
  58. #endif
  59. /* Since ia64 wants the stackbase w/clone2, re-use the grows-up macro. */
  60. #if _STACK_GROWS_UP || defined (__ia64__)
  61. # define STACK(__stack, __stack_size) (__stack)
  62. #elif _STACK_GROWS_DOWN
  63. # define STACK(__stack, __stack_size) (__stack + __stack_size)
  64. #endif
  65. struct posix_spawn_args
  66. {
  67. sigset_t oldmask;
  68. const char *file;
  69. int (*exec) (const char *, char *const *, char *const *);
  70. const posix_spawn_file_actions_t *fa;
  71. const posix_spawnattr_t *restrict attr;
  72. char *const *argv;
  73. ptrdiff_t argc;
  74. char *const *envp;
  75. int xflags;
  76. int err;
  77. };
  78. /* Older version requires that shell script without shebang definition
  79. to be called explicitly using /bin/sh (_PATH_BSHELL). */
  80. static void
  81. maybe_script_execute (struct posix_spawn_args *args)
  82. {
  83. if (SHLIB_COMPAT (libc, GLIBC_2_2, GLIBC_2_15)
  84. && (args->xflags & SPAWN_XFLAGS_TRY_SHELL) && errno == ENOEXEC)
  85. {
  86. char *const *argv = args->argv;
  87. ptrdiff_t argc = args->argc;
  88. /* Construct an argument list for the shell. */
  89. char *new_argv[argc + 2];
  90. new_argv[0] = (char *) _PATH_BSHELL;
  91. new_argv[1] = (char *) args->file;
  92. if (argc > 1)
  93. memcpy (new_argv + 2, argv + 1, argc * sizeof (char *));
  94. else
  95. new_argv[2] = NULL;
  96. /* Execute the shell. */
  97. args->exec (new_argv[0], new_argv, args->envp);
  98. }
  99. }
  100. /* Function used in the clone call to setup the signals mask, posix_spawn
  101. attributes, and file actions. It run on its own stack (provided by the
  102. posix_spawn call). */
  103. static int
  104. __spawni_child (void *arguments)
  105. {
  106. struct posix_spawn_args *args = arguments;
  107. const posix_spawnattr_t *restrict attr = args->attr;
  108. const posix_spawn_file_actions_t *file_actions = args->fa;
  109. /* The child must ensure that no signal handler are enabled because it shared
  110. memory with parent, so the signal disposition must be either SIG_DFL or
  111. SIG_IGN. It does by iterating over all signals and although it could
  112. possibly be more optimized (by tracking which signal potentially have a
  113. signal handler), it might requires system specific solutions (since the
  114. sigset_t data type can be very different on different architectures). */
  115. struct sigaction sa;
  116. memset (&sa, '\0', sizeof (sa));
  117. sigset_t hset;
  118. __sigprocmask (SIG_BLOCK, 0, &hset);
  119. for (int sig = 1; sig < _NSIG; ++sig)
  120. {
  121. if ((attr->__flags & POSIX_SPAWN_SETSIGDEF)
  122. && __sigismember (&attr->__sd, sig))
  123. {
  124. sa.sa_handler = SIG_DFL;
  125. }
  126. else if (__sigismember (&hset, sig))
  127. {
  128. if (__is_internal_signal (sig))
  129. sa.sa_handler = SIG_IGN;
  130. else
  131. {
  132. __libc_sigaction (sig, 0, &sa);
  133. if (sa.sa_handler == SIG_IGN)
  134. continue;
  135. sa.sa_handler = SIG_DFL;
  136. }
  137. }
  138. else
  139. continue;
  140. __libc_sigaction (sig, &sa, 0);
  141. }
  142. #ifdef _POSIX_PRIORITY_SCHEDULING
  143. /* Set the scheduling algorithm and parameters. */
  144. if ((attr->__flags & (POSIX_SPAWN_SETSCHEDPARAM | POSIX_SPAWN_SETSCHEDULER))
  145. == POSIX_SPAWN_SETSCHEDPARAM)
  146. {
  147. if (__sched_setparam (0, &attr->__sp) == -1)
  148. goto fail;
  149. }
  150. else if ((attr->__flags & POSIX_SPAWN_SETSCHEDULER) != 0)
  151. {
  152. if (__sched_setscheduler (0, attr->__policy, &attr->__sp) == -1)
  153. goto fail;
  154. }
  155. #endif
  156. if ((attr->__flags & POSIX_SPAWN_SETSID) != 0
  157. && __setsid () < 0)
  158. goto fail;
  159. /* Set the process group ID. */
  160. if ((attr->__flags & POSIX_SPAWN_SETPGROUP) != 0
  161. && __setpgid (0, attr->__pgrp) != 0)
  162. goto fail;
  163. /* Set the effective user and group IDs. */
  164. if ((attr->__flags & POSIX_SPAWN_RESETIDS) != 0
  165. && (local_seteuid (__getuid ()) != 0
  166. || local_setegid (__getgid ()) != 0))
  167. goto fail;
  168. /* Execute the file actions. */
  169. if (file_actions != 0)
  170. {
  171. int cnt;
  172. struct rlimit64 fdlimit;
  173. bool have_fdlimit = false;
  174. for (cnt = 0; cnt < file_actions->__used; ++cnt)
  175. {
  176. struct __spawn_action *action = &file_actions->__actions[cnt];
  177. switch (action->tag)
  178. {
  179. case spawn_do_close:
  180. if (__close_nocancel (action->action.close_action.fd) != 0)
  181. {
  182. if (!have_fdlimit)
  183. {
  184. __getrlimit64 (RLIMIT_NOFILE, &fdlimit);
  185. have_fdlimit = true;
  186. }
  187. /* Signal errors only for file descriptors out of range. */
  188. if (action->action.close_action.fd < 0
  189. || action->action.close_action.fd >= fdlimit.rlim_cur)
  190. goto fail;
  191. }
  192. break;
  193. case spawn_do_open:
  194. {
  195. /* POSIX states that if fildes was already an open file descriptor,
  196. it shall be closed before the new file is opened. This avoid
  197. pontential issues when posix_spawn plus addopen action is called
  198. with the process already at maximum number of file descriptor
  199. opened and also for multiple actions on single-open special
  200. paths (like /dev/watchdog). */
  201. __close_nocancel (action->action.open_action.fd);
  202. int ret = __open_nocancel (action->action.open_action.path,
  203. action->action.
  204. open_action.oflag | O_LARGEFILE,
  205. action->action.open_action.mode);
  206. if (ret == -1)
  207. goto fail;
  208. int new_fd = ret;
  209. /* Make sure the desired file descriptor is used. */
  210. if (ret != action->action.open_action.fd)
  211. {
  212. if (__dup2 (new_fd, action->action.open_action.fd)
  213. != action->action.open_action.fd)
  214. goto fail;
  215. if (__close_nocancel (new_fd) != 0)
  216. goto fail;
  217. }
  218. }
  219. break;
  220. case spawn_do_dup2:
  221. /* Austin Group issue #411 requires adddup2 action with source
  222. and destination being equal to remove close-on-exec flag. */
  223. if (action->action.dup2_action.fd
  224. == action->action.dup2_action.newfd)
  225. {
  226. int fd = action->action.dup2_action.newfd;
  227. int flags = __fcntl (fd, F_GETFD, 0);
  228. if (flags == -1)
  229. goto fail;
  230. if (__fcntl (fd, F_SETFD, flags & ~FD_CLOEXEC) == -1)
  231. goto fail;
  232. }
  233. else if (__dup2 (action->action.dup2_action.fd,
  234. action->action.dup2_action.newfd)
  235. != action->action.dup2_action.newfd)
  236. goto fail;
  237. break;
  238. case spawn_do_chdir:
  239. if (__chdir (action->action.chdir_action.path) != 0)
  240. goto fail;
  241. break;
  242. case spawn_do_fchdir:
  243. if (__fchdir (action->action.fchdir_action.fd) != 0)
  244. goto fail;
  245. break;
  246. }
  247. }
  248. }
  249. /* Set the initial signal mask of the child if POSIX_SPAWN_SETSIGMASK
  250. is set, otherwise restore the previous one. */
  251. __sigprocmask (SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK)
  252. ? &attr->__ss : &args->oldmask, 0);
  253. args->exec (args->file, args->argv, args->envp);
  254. /* This is compatibility function required to enable posix_spawn run
  255. script without shebang definition for older posix_spawn versions
  256. (2.15). */
  257. maybe_script_execute (args);
  258. fail:
  259. /* errno should have an appropriate non-zero value; otherwise,
  260. there's a bug in glibc or the kernel. For lack of an error code
  261. (EINTERNALBUG) describing that, use ECHILD. Another option would
  262. be to set args->err to some negative sentinel and have the parent
  263. abort(), but that seems needlessly harsh. */
  264. args->err = errno ? : ECHILD;
  265. _exit (SPAWN_ERROR);
  266. }
  267. /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
  268. Before running the process perform the actions described in FILE-ACTIONS. */
  269. static int
  270. __spawnix (pid_t * pid, const char *file,
  271. const posix_spawn_file_actions_t * file_actions,
  272. const posix_spawnattr_t * attrp, char *const argv[],
  273. char *const envp[], int xflags,
  274. int (*exec) (const char *, char *const *, char *const *))
  275. {
  276. pid_t new_pid;
  277. struct posix_spawn_args args;
  278. int ec;
  279. /* To avoid imposing hard limits on posix_spawn{p} the total number of
  280. arguments is first calculated to allocate a mmap to hold all possible
  281. values. */
  282. ptrdiff_t argc = 0;
  283. /* Linux allows at most max (0x7FFFFFFF, 1/4 stack size) arguments
  284. to be used in a execve call. We limit to INT_MAX minus one due the
  285. compatiblity code that may execute a shell script (maybe_script_execute)
  286. where it will construct another argument list with an additional
  287. argument. */
  288. ptrdiff_t limit = INT_MAX - 1;
  289. while (argv[argc++] != NULL)
  290. if (argc == limit)
  291. {
  292. errno = E2BIG;
  293. return errno;
  294. }
  295. int prot = (PROT_READ | PROT_WRITE
  296. | ((GL (dl_stack_flags) & PF_X) ? PROT_EXEC : 0));
  297. /* Add a slack area for child's stack. */
  298. size_t argv_size = (argc * sizeof (void *)) + 512;
  299. /* We need at least a few pages in case the compiler's stack checking is
  300. enabled. In some configs, it is known to use at least 24KiB. We use
  301. 32KiB to be "safe" from anything the compiler might do. Besides, the
  302. extra pages won't actually be allocated unless they get used. */
  303. argv_size += (32 * 1024);
  304. size_t stack_size = ALIGN_UP (argv_size, GLRO(dl_pagesize));
  305. void *stack = __mmap (NULL, stack_size, prot,
  306. MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
  307. if (__glibc_unlikely (stack == MAP_FAILED))
  308. return errno;
  309. /* Disable asynchronous cancellation. */
  310. int state;
  311. __libc_ptf_call (__pthread_setcancelstate,
  312. (PTHREAD_CANCEL_DISABLE, &state), 0);
  313. /* Child must set args.err to something non-negative - we rely on
  314. the parent and child sharing VM. */
  315. args.err = 0;
  316. args.file = file;
  317. args.exec = exec;
  318. args.fa = file_actions;
  319. args.attr = attrp ? attrp : &(const posix_spawnattr_t) { 0 };
  320. args.argv = argv;
  321. args.argc = argc;
  322. args.envp = envp;
  323. args.xflags = xflags;
  324. __libc_signal_block_all (&args.oldmask);
  325. /* The clone flags used will create a new child that will run in the same
  326. memory space (CLONE_VM) and the execution of calling thread will be
  327. suspend until the child calls execve or _exit.
  328. Also since the calling thread execution will be suspend, there is not
  329. need for CLONE_SETTLS. Although parent and child share the same TLS
  330. namespace, there will be no concurrent access for TLS variables (errno
  331. for instance). */
  332. new_pid = CLONE (__spawni_child, STACK (stack, stack_size), stack_size,
  333. CLONE_VM | CLONE_VFORK | SIGCHLD, &args);
  334. /* It needs to collect the case where the auxiliary process was created
  335. but failed to execute the file (due either any preparation step or
  336. for execve itself). */
  337. if (new_pid > 0)
  338. {
  339. /* Also, it handles the unlikely case where the auxiliary process was
  340. terminated before calling execve as if it was successfully. The
  341. args.err is set to 0 as default and changed to a positive value
  342. only in case of failure, so in case of premature termination
  343. due a signal args.err will remain zeroed and it will be up to
  344. caller to actually collect it. */
  345. ec = args.err;
  346. if (ec > 0)
  347. /* There still an unlikely case where the child is cancelled after
  348. setting args.err, due to a positive error value. Also there is
  349. possible pid reuse race (where the kernel allocated the same pid
  350. to an unrelated process). Unfortunately due synchronization
  351. issues where the kernel might not have the process collected
  352. the waitpid below can not use WNOHANG. */
  353. __waitpid (new_pid, NULL, 0);
  354. }
  355. else
  356. ec = -new_pid;
  357. __munmap (stack, stack_size);
  358. if ((ec == 0) && (pid != NULL))
  359. *pid = new_pid;
  360. __libc_signal_restore_set (&args.oldmask);
  361. __libc_ptf_call (__pthread_setcancelstate, (state, NULL), 0);
  362. return ec;
  363. }
  364. /* Spawn a new process executing PATH with the attributes describes in *ATTRP.
  365. Before running the process perform the actions described in FILE-ACTIONS. */
  366. int
  367. __spawni (pid_t * pid, const char *file,
  368. const posix_spawn_file_actions_t * acts,
  369. const posix_spawnattr_t * attrp, char *const argv[],
  370. char *const envp[], int xflags)
  371. {
  372. /* It uses __execvpex to avoid run ENOEXEC in non compatibility mode (it
  373. will be handled by maybe_script_execute). */
  374. return __spawnix (pid, file, acts, attrp, argv, envp, xflags,
  375. xflags & SPAWN_XFLAGS_USE_PATH ? __execvpex :__execve);
  376. }