1 //===-- Linux implementation of fork --------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/unistd/fork.h"
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
18 #include "src/errno/libc_errno.h"
19 #include <signal.h> // For SIGCHLD
20 #include <sys/syscall.h> // For syscall numbers.
22 namespace LIBC_NAMESPACE_DECL
{
24 // The implementation of fork here is very minimal. We will add more
25 // functionality and standard compliance in future.
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);
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);
39 #error "fork and clone syscalls not available."
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();
53 // Error case, a child process was not created.
54 libc_errno
= static_cast<int>(-ret
);
57 // recover parent's tid.
58 internal::force_set_tid(parent_tid
);
59 invoke_parent_callbacks();
63 } // namespace LIBC_NAMESPACE_DECL