[libc-commits] [libc] [libc] implement cached process/thread identity (PR #95965)

via libc-commits libc-commits at lists.llvm.org
Wed Jun 19 21:25:15 PDT 2024


================
@@ -24,29 +25,41 @@ namespace LIBC_NAMESPACE {
 
 LLVM_LIBC_FUNCTION(pid_t, fork, (void)) {
   invoke_prepare_callbacks();
+
+  // Invalidate tid/pid cache before fork to avoid post fork signal handler from
+  // getting wrong values. gettid() is not async-signal-safe, but let's provide
+  // our best efforts here.
+  self.invalidate_tid();
+  ProcessIdentity::start_fork();
+
 #ifdef SYS_fork
   pid_t ret = LIBC_NAMESPACE::syscall_impl<pid_t>(SYS_fork);
 #elif defined(SYS_clone)
   pid_t ret = LIBC_NAMESPACE::syscall_impl<pid_t>(SYS_clone, SIGCHLD, 0);
 #else
 #error "fork and clone syscalls not available."
 #endif
-  if (ret == 0) {
-    // Return value is 0 in the child process.
-    // The child is created with a single thread whose self object will be a
-    // copy of parent process' thread which called fork. So, we have to fix up
-    // the child process' self object with the new process' tid.
-    self.attrib->tid = LIBC_NAMESPACE::syscall_impl<pid_t>(SYS_gettid);
-    invoke_child_callbacks();
-    return 0;
-  }
 
   if (ret < 0) {
     // Error case, a child process was not created.
     libc_errno = static_cast<int>(-ret);
     return -1;
   }
 
+  // Common
+  // Refresh tid/pid cache after fork
+  self.refresh_tid();
----------------
QuarticCat wrote:

Will the tid of parent process change after forking? If not, we can probably avoid syscall in the parent process here.

https://github.com/llvm/llvm-project/pull/95965


More information about the libc-commits mailing list