| 1 | //===-- Linux implementation of fork --------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "src/unistd/fork.h" |
| 10 | |
| 11 | #include "src/__support/OSUtil/syscall.h" // For internal syscall function. |
| 12 | #include "src/__support/common.h" |
| 13 | #include "src/__support/macros/config.h" |
| 14 | #include "src/__support/threads/fork_callbacks.h" |
| 15 | #include "src/__support/threads/identifier.h" |
| 16 | #include "src/__support/threads/thread.h" // For thread self object |
| 17 | |
| 18 | #include "src/__support/libc_errno.h" |
| 19 | #include <signal.h> // For SIGCHLD |
| 20 | #include <sys/syscall.h> // For syscall numbers. |
| 21 | |
| 22 | namespace LIBC_NAMESPACE_DECL { |
| 23 | |
| 24 | // The implementation of fork here is very minimal. We will add more |
| 25 | // functionality and standard compliance in future. |
| 26 | |
| 27 | LLVM_LIBC_FUNCTION(pid_t, fork, (void)) { |
| 28 | invoke_prepare_callbacks(); |
| 29 | pid_t parent_tid = internal::gettid(); |
| 30 | // Invalidate parent's tid cache before forking. We cannot do this in child |
| 31 | // process because in the post-fork instruction windows, there may be a signal |
| 32 | // handler triggered which may get the wrong tid. |
| 33 | internal::force_set_tid(0); |
| 34 | #ifdef SYS_fork |
| 35 | pid_t ret = syscall_impl<pid_t>(SYS_fork); |
| 36 | #elif defined(SYS_clone) |
| 37 | pid_t ret = syscall_impl<pid_t>(SYS_clone, SIGCHLD, 0); |
| 38 | #else |
| 39 | #error "fork and clone syscalls not available." |
| 40 | #endif |
| 41 | |
| 42 | if (ret == 0) { |
| 43 | // Return value is 0 in the child process. |
| 44 | // The child is created with a single thread whose self object will be a |
| 45 | // copy of parent process' thread which called fork. So, we have to fix up |
| 46 | // the child process' self object with the new process' tid. |
| 47 | internal::force_set_tid(syscall_impl<pid_t>(SYS_gettid)); |
| 48 | invoke_child_callbacks(); |
| 49 | return 0; |
| 50 | } |
| 51 | |
| 52 | if (ret < 0) { |
| 53 | // Error case, a child process was not created. |
| 54 | libc_errno = static_cast<int>(-ret); |
| 55 | return -1; |
| 56 | } |
| 57 | // recover parent's tid. |
| 58 | internal::force_set_tid(parent_tid); |
| 59 | invoke_parent_callbacks(); |
| 60 | return ret; |
| 61 | } |
| 62 | |
| 63 | } // namespace LIBC_NAMESPACE_DECL |
| 64 | |