fexecve.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Copyright (C) 1994-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #include <errno.h>
  15. #include <stddef.h>
  16. #include <stdio.h>
  17. #include <unistd.h>
  18. #include <fcntl.h>
  19. #include <sys/stat.h>
  20. #include <sysdep.h>
  21. #include <sys/syscall.h>
  22. #include <kernel-features.h>
  23. /* Execute the file FD refers to, overlaying the running program image.
  24. ARGV and ENVP are passed to the new program, as for `execve'. */
  25. int
  26. fexecve (int fd, char *const argv[], char *const envp[])
  27. {
  28. if (fd < 0 || argv == NULL || envp == NULL)
  29. {
  30. __set_errno (EINVAL);
  31. return -1;
  32. }
  33. #ifdef __NR_execveat
  34. /* Avoid implicit array coercion in syscall macros. */
  35. INLINE_SYSCALL (execveat, 5, fd, "", &argv[0], &envp[0], AT_EMPTY_PATH);
  36. # ifndef __ASSUME_EXECVEAT
  37. if (errno != ENOSYS)
  38. return -1;
  39. # endif
  40. #endif
  41. #ifndef __ASSUME_EXECVEAT
  42. /* We use the /proc filesystem to get the information. If it is not
  43. mounted we fail. */
  44. char buf[sizeof "/proc/self/fd/" + sizeof (int) * 3];
  45. __snprintf (buf, sizeof (buf), "/proc/self/fd/%d", fd);
  46. /* We do not need the return value. */
  47. __execve (buf, argv, envp);
  48. int save = errno;
  49. /* We come here only if the 'execve' call fails. Determine whether
  50. /proc is mounted. If not we return ENOSYS. */
  51. struct stat st;
  52. if (stat ("/proc/self/fd", &st) != 0 && errno == ENOENT)
  53. save = ENOSYS;
  54. __set_errno (save);
  55. #endif
  56. return -1;
  57. }