_Fork.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* _Fork implementation. Linux version.
  2. Copyright (C) 2021-2026 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 <arch-fork.h>
  16. #include <libc-lock.h>
  17. #include <pthreadP.h>
  18. #include <getrandom-internal.h>
  19. pid_t
  20. _Fork (void)
  21. {
  22. /* Block all signals to avoid revealing the inconsistent TCB state
  23. to a signal handler after fork. The abort lock should AS-safe
  24. to avoid deadlock if _Fork is called from a signal handler. */
  25. internal_sigset_t original_sigmask;
  26. __abort_lock_rdlock (&original_sigmask);
  27. pid_t pid = arch_fork (&THREAD_SELF->tid);
  28. if (pid == 0)
  29. {
  30. struct pthread *self = THREAD_SELF;
  31. /* Initialize the robust mutex list setting in the kernel which has
  32. been reset during the fork. We do not check for errors because if
  33. it fails here, it must have failed at process startup as well and
  34. nobody could have used robust mutexes.
  35. Before we do that, we have to clear the list of robust mutexes
  36. because we do not inherit ownership of mutexes from the parent.
  37. We do not have to set self->robust_head.futex_offset since we do
  38. inherit the correct value from the parent. We do not need to clear
  39. the pending operation because it must have been zero when fork was
  40. called. */
  41. #if __PTHREAD_MUTEX_HAVE_PREV
  42. self->robust_prev = &self->robust_head;
  43. #endif
  44. self->robust_head.list = &self->robust_head;
  45. INTERNAL_SYSCALL_CALL (set_robust_list, &self->robust_head,
  46. sizeof (struct robust_list_head));
  47. call_function_static_weak (__getrandom_fork_subprocess);
  48. }
  49. __abort_lock_unlock (&original_sigmask);
  50. return pid;
  51. }
  52. libc_hidden_def (_Fork)