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/threads/fork_callbacks.h" 14 #include "src/__support/threads/thread.h" // For thread self object 15 16 #include "src/errno/libc_errno.h" 17 #include <signal.h> // For SIGCHLD 18 #include <sys/syscall.h> // For syscall numbers. 19 20 namespace LIBC_NAMESPACE { 21 22 // The implementation of fork here is very minimal. We will add more 23 // functionality and standard compliance in future. 24 25 LLVM_LIBC_FUNCTION(pid_t, fork, (void)) { 26 invoke_prepare_callbacks(); 27 #ifdef SYS_fork 28 pid_t ret = LIBC_NAMESPACE::syscall_impl<pid_t>(SYS_fork); 29 #elif defined(SYS_clone) 30 pid_t ret = LIBC_NAMESPACE::syscall_impl<pid_t>(SYS_clone, SIGCHLD, 0); 31 #else 32 #error "fork and clone syscalls not available." 33 #endif 34 if (ret == 0) { 35 // Return value is 0 in the child process. 36 // The child is created with a single thread whose self object will be a 37 // copy of parent process' thread which called fork. So, we have to fix up 38 // the child process' self object with the new process' tid. 39 self.attrib->tid = LIBC_NAMESPACE::syscall_impl<pid_t>(SYS_gettid); 40 invoke_child_callbacks(); 41 return 0; 42 } 43 44 if (ret < 0) { 45 // Error case, a child process was not created. 46 libc_errno = static_cast<int>(-ret); 47 return -1; 48 } 49 50 invoke_parent_callbacks(); 51 return ret; 52 } 53 54 } // namespace LIBC_NAMESPACE 55