94084c
commit a8ac8c4725ddb1119764126a8674a04c9dd5aea8
94084c
Author: Florian Weimer <fweimer@redhat.com>
94084c
Date:   Mon Sep 13 11:06:08 2021 +0200
94084c
94084c
    nptl: Fix race between pthread_kill and thread exit (bug 12889)
94084c
    
94084c
    A new thread exit lock and flag are introduced.  They are used to
94084c
    detect that the thread is about to exit or has exited in
94084c
    __pthread_kill_internal, and the signal is not sent in this case.
94084c
    
94084c
    The test sysdeps/pthread/tst-pthread_cancel-select-loop.c is derived
94084c
    from a downstream test originally written by Marek Polacek.
94084c
    
94084c
    Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
94084c
    (cherry picked from commit 526c3cf11ee9367344b6b15d669e4c3cb461a2be)
94084c
94084c
diff --git a/nptl/allocatestack.c b/nptl/allocatestack.c
94084c
index cfe37a3443b69454..50065bc9bd8a28e5 100644
94084c
--- a/nptl/allocatestack.c
94084c
+++ b/nptl/allocatestack.c
94084c
@@ -32,6 +32,7 @@
94084c
 #include <futex-internal.h>
94084c
 #include <kernel-features.h>
94084c
 #include <nptl-stack.h>
94084c
+#include <libc-lock.h>
94084c
 
94084c
 /* Default alignment of stack.  */
94084c
 #ifndef STACK_ALIGN
94084c
@@ -127,6 +128,8 @@ get_cached_stack (size_t *sizep, void **memp)
94084c
   /* No pending event.  */
94084c
   result->nextevent = NULL;
94084c
 
94084c
+  result->exiting = false;
94084c
+  __libc_lock_init (result->exit_lock);
94084c
   result->tls_state = (struct tls_internal_t) { 0 };
94084c
 
94084c
   /* Clear the DTV.  */
94084c
diff --git a/nptl/descr.h b/nptl/descr.h
94084c
index c85778d44941a42f..4de84138fb960fa4 100644
94084c
--- a/nptl/descr.h
94084c
+++ b/nptl/descr.h
94084c
@@ -396,6 +396,12 @@ struct pthread
94084c
      PTHREAD_CANCEL_ASYNCHRONOUS).  */
94084c
   unsigned char canceltype;
94084c
 
94084c
+  /* Used in __pthread_kill_internal to detected a thread that has
94084c
+     exited or is about to exit.  exit_lock must only be acquired
94084c
+     after blocking signals.  */
94084c
+  bool exiting;
94084c
+  int exit_lock; /* A low-level lock (for use with __libc_lock_init etc).  */
94084c
+
94084c
   /* Used on strsignal.  */
94084c
   struct tls_internal_t tls_state;
94084c
 
94084c
diff --git a/nptl/pthread_create.c b/nptl/pthread_create.c
94084c
index d8ec299cb1661e82..33b426fc682300dc 100644
94084c
--- a/nptl/pthread_create.c
94084c
+++ b/nptl/pthread_create.c
94084c
@@ -37,6 +37,7 @@
94084c
 #include <sys/single_threaded.h>
94084c
 #include <version.h>
94084c
 #include <clone_internal.h>
94084c
+#include <futex-internal.h>
94084c
 
94084c
 #include <shlib-compat.h>
94084c
 
94084c
@@ -485,6 +486,19 @@ start_thread (void *arg)
94084c
     /* This was the last thread.  */
94084c
     exit (0);
94084c
 
94084c
+  /* This prevents sending a signal from this thread to itself during
94084c
+     its final stages.  This must come after the exit call above
94084c
+     because atexit handlers must not run with signals blocked.  */
94084c
+  __libc_signal_block_all (NULL);
94084c
+
94084c
+  /* Tell __pthread_kill_internal that this thread is about to exit.
94084c
+     If there is a __pthread_kill_internal in progress, this delays
94084c
+     the thread exit until the signal has been queued by the kernel
94084c
+     (so that the TID used to send it remains valid).  */
94084c
+  __libc_lock_lock (pd->exit_lock);
94084c
+  pd->exiting = true;
94084c
+  __libc_lock_unlock (pd->exit_lock);
94084c
+
94084c
 #ifndef __ASSUME_SET_ROBUST_LIST
94084c
   /* If this thread has any robust mutexes locked, handle them now.  */
94084c
 # if __PTHREAD_MUTEX_HAVE_PREV
94084c
diff --git a/nptl/pthread_kill.c b/nptl/pthread_kill.c
94084c
index 5d4c86f9205a6fb5..fb7862eff787a94f 100644
94084c
--- a/nptl/pthread_kill.c
94084c
+++ b/nptl/pthread_kill.c
94084c
@@ -16,6 +16,7 @@
94084c
    License along with the GNU C Library; if not, see
94084c
    <https://www.gnu.org/licenses/>.  */
94084c
 
94084c
+#include <libc-lock.h>
94084c
 #include <unistd.h>
94084c
 #include <pthreadP.h>
94084c
 #include <shlib-compat.h>
94084c
@@ -23,37 +24,51 @@
94084c
 int
94084c
 __pthread_kill_internal (pthread_t threadid, int signo)
94084c
 {
94084c
-  pid_t tid;
94084c
   struct pthread *pd = (struct pthread *) threadid;
94084c
-
94084c
   if (pd == THREAD_SELF)
94084c
-    /* It is a special case to handle raise() implementation after a vfork
94084c
-       call (which does not update the PD tid field).  */
94084c
-    tid = INLINE_SYSCALL_CALL (gettid);
94084c
-  else
94084c
-    /* Force load of pd->tid into local variable or register.  Otherwise
94084c
-       if a thread exits between ESRCH test and tgkill, we might return
94084c
-       EINVAL, because pd->tid would be cleared by the kernel.  */
94084c
-    tid = atomic_forced_read (pd->tid);
94084c
-
94084c
-  int val;
94084c
-  if (__glibc_likely (tid > 0))
94084c
     {
94084c
-      pid_t pid = __getpid ();
94084c
-
94084c
-      val = INTERNAL_SYSCALL_CALL (tgkill, pid, tid, signo);
94084c
-      val = (INTERNAL_SYSCALL_ERROR_P (val)
94084c
-	    ? INTERNAL_SYSCALL_ERRNO (val) : 0);
94084c
+      /* Use the actual TID from the kernel, so that it refers to the
94084c
+         current thread even if called after vfork.  There is no
94084c
+         signal blocking in this case, so that the signal is delivered
94084c
+         immediately, before __pthread_kill_internal returns: a signal
94084c
+         sent to the thread itself needs to be delivered
94084c
+         synchronously.  (It is unclear if Linux guarantees the
94084c
+         delivery of all pending signals after unblocking in the code
94084c
+         below.  POSIX only guarantees delivery of a single signal,
94084c
+         which may not be the right one.)  */
94084c
+      pid_t tid = INTERNAL_SYSCALL_CALL (gettid);
94084c
+      int ret = INTERNAL_SYSCALL_CALL (kill, tid, signo);
94084c
+      return INTERNAL_SYSCALL_ERROR_P (ret) ? INTERNAL_SYSCALL_ERRNO (ret) : 0;
94084c
     }
94084c
+
94084c
+  /* Block all signals, as required by pd->exit_lock.  */
94084c
+  sigset_t old_mask;
94084c
+  __libc_signal_block_all (&old_mask);
94084c
+  __libc_lock_lock (pd->exit_lock);
94084c
+
94084c
+  int ret;
94084c
+  if (pd->exiting)
94084c
+    /* The thread is about to exit (or has exited).  Sending the
94084c
+       signal is either not observable (the target thread has already
94084c
+       blocked signals at this point), or it will fail, or it might be
94084c
+       delivered to a new, unrelated thread that has reused the TID.
94084c
+       So do not actually send the signal.  Do not report an error
94084c
+       because the threadid argument is still valid (the thread ID
94084c
+       lifetime has not ended), and ESRCH (for example) would be
94084c
+       misleading.  */
94084c
+    ret = 0;
94084c
   else
94084c
-    /* The kernel reports that the thread has exited.  POSIX specifies
94084c
-       the ESRCH error only for the case when the lifetime of a thread
94084c
-       ID has ended, but calling pthread_kill on such a thread ID is
94084c
-       undefined in glibc.  Therefore, do not treat kernel thread exit
94084c
-       as an error.  */
94084c
-    val = 0;
94084c
+    {
94084c
+      /* Using tgkill is a safety measure.  pd->exit_lock ensures that
94084c
+	 the target thread cannot exit.  */
94084c
+      ret = INTERNAL_SYSCALL_CALL (tgkill, __getpid (), pd->tid, signo);
94084c
+      ret = INTERNAL_SYSCALL_ERROR_P (ret) ? INTERNAL_SYSCALL_ERRNO (ret) : 0;
94084c
+    }
94084c
+
94084c
+  __libc_lock_unlock (pd->exit_lock);
94084c
+  __libc_signal_restore_set (&old_mask);
94084c
 
94084c
-  return val;
94084c
+  return ret;
94084c
 }
94084c
 
94084c
 int
94084c
diff --git a/sysdeps/pthread/Makefile b/sysdeps/pthread/Makefile
94084c
index dedfa0d290da4949..48dba717a1cdc20a 100644
94084c
--- a/sysdeps/pthread/Makefile
94084c
+++ b/sysdeps/pthread/Makefile
94084c
@@ -119,7 +119,9 @@ tests += tst-cnd-basic tst-mtx-trylock tst-cnd-broadcast \
94084c
 	 tst-unwind-thread \
94084c
 	 tst-pt-vfork1 tst-pt-vfork2 tst-vfork1x tst-vfork2x \
94084c
 	 tst-pthread_cancel-exited \
94084c
+	 tst-pthread_cancel-select-loop \
94084c
 	 tst-pthread_kill-exited \
94084c
+	 tst-pthread_kill-exiting \
94084c
 	 # tests
94084c
 
94084c
 tests-time64 := \
94084c
diff --git a/sysdeps/pthread/tst-pthread_cancel-select-loop.c b/sysdeps/pthread/tst-pthread_cancel-select-loop.c
94084c
new file mode 100644
94084c
index 0000000000000000..a62087589cee24b5
94084c
--- /dev/null
94084c
+++ b/sysdeps/pthread/tst-pthread_cancel-select-loop.c
94084c
@@ -0,0 +1,87 @@
94084c
+/* Test that pthread_cancel succeeds during thread exit.
94084c
+   Copyright (C) 2021 Free Software Foundation, Inc.
94084c
+   This file is part of the GNU C Library.
94084c
+
94084c
+   The GNU C Library is free software; you can redistribute it and/or
94084c
+   modify it under the terms of the GNU Lesser General Public
94084c
+   License as published by the Free Software Foundation; either
94084c
+   version 2.1 of the License, or (at your option) any later version.
94084c
+
94084c
+   The GNU C Library is distributed in the hope that it will be useful,
94084c
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
94084c
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
94084c
+   Lesser General Public License for more details.
94084c
+
94084c
+   You should have received a copy of the GNU Lesser General Public
94084c
+   License along with the GNU C Library; if not, see
94084c
+   <https://www.gnu.org/licenses/>.  */
94084c
+
94084c
+/* This test tries to trigger an internal race condition in
94084c
+   pthread_cancel, where the cancellation signal is sent after the
94084c
+   thread has begun the cancellation process.  This can result in a
94084c
+   spurious ESRCH error.  For the original bug 12889, the window is
94084c
+   quite small, so the bug was not reproduced in every run.  */
94084c
+
94084c
+#include <stdbool.h>
94084c
+#include <stddef.h>
94084c
+#include <support/check.h>
94084c
+#include <support/xthread.h>
94084c
+#include <support/xunistd.h>
94084c
+#include <sys/select.h>
94084c
+#include <unistd.h>
94084c
+
94084c
+/* Set to true by timeout_thread_function when the test should
94084c
+   terminate.  */
94084c
+static bool timeout;
94084c
+
94084c
+static void *
94084c
+timeout_thread_function (void *unused)
94084c
+{
94084c
+  usleep (5 * 1000 * 1000);
94084c
+  __atomic_store_n (&timeout, true, __ATOMIC_RELAXED);
94084c
+  return NULL;
94084c
+}
94084c
+
94084c
+/* Used for blocking the select function below.  */
94084c
+static int pipe_fds[2];
94084c
+
94084c
+static void *
94084c
+canceled_thread_function (void *unused)
94084c
+{
94084c
+  while (true)
94084c
+    {
94084c
+      fd_set rfs;
94084c
+      fd_set wfs;
94084c
+      fd_set efs;
94084c
+      FD_ZERO (&rfs;;
94084c
+      FD_ZERO (&wfs;;
94084c
+      FD_ZERO (&efs;;
94084c
+      FD_SET (pipe_fds[0], &rfs;;
94084c
+
94084c
+      /* If the cancellation request is recognized early, the thread
94084c
+         begins exiting while the cancellation signal arrives.  */
94084c
+      select (FD_SETSIZE, &rfs, &wfs, &efs, NULL);
94084c
+    }
94084c
+  return NULL;
94084c
+}
94084c
+
94084c
+static int
94084c
+do_test (void)
94084c
+{
94084c
+  xpipe (pipe_fds);
94084c
+  pthread_t thr_timeout = xpthread_create (NULL, timeout_thread_function, NULL);
94084c
+
94084c
+  while (!__atomic_load_n (&timeout, __ATOMIC_RELAXED))
94084c
+    {
94084c
+      pthread_t thr = xpthread_create (NULL, canceled_thread_function, NULL);
94084c
+      xpthread_cancel (thr);
94084c
+      TEST_VERIFY (xpthread_join (thr) == PTHREAD_CANCELED);
94084c
+    }
94084c
+
94084c
+  xpthread_join (thr_timeout);
94084c
+  xclose (pipe_fds[0]);
94084c
+  xclose (pipe_fds[1]);
94084c
+  return 0;
94084c
+}
94084c
+
94084c
+#include <support/test-driver.c>
94084c
diff --git a/sysdeps/pthread/tst-pthread_kill-exiting.c b/sysdeps/pthread/tst-pthread_kill-exiting.c
94084c
new file mode 100644
94084c
index 0000000000000000..f803e94f1195f204
94084c
--- /dev/null
94084c
+++ b/sysdeps/pthread/tst-pthread_kill-exiting.c
94084c
@@ -0,0 +1,123 @@
94084c
+/* Test that pthread_kill succeeds during thread exit.
94084c
+   Copyright (C) 2021 Free Software Foundation, Inc.
94084c
+   This file is part of the GNU C Library.
94084c
+
94084c
+   The GNU C Library is free software; you can redistribute it and/or
94084c
+   modify it under the terms of the GNU Lesser General Public
94084c
+   License as published by the Free Software Foundation; either
94084c
+   version 2.1 of the License, or (at your option) any later version.
94084c
+
94084c
+   The GNU C Library is distributed in the hope that it will be useful,
94084c
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
94084c
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
94084c
+   Lesser General Public License for more details.
94084c
+
94084c
+   You should have received a copy of the GNU Lesser General Public
94084c
+   License along with the GNU C Library; if not, see
94084c
+   <https://www.gnu.org/licenses/>.  */
94084c
+
94084c
+/* This test verifies that pthread_kill for a thread that is exiting
94084c
+   succeeds (with or without actually delivering the signal).  */
94084c
+
94084c
+#include <array_length.h>
94084c
+#include <stdbool.h>
94084c
+#include <stddef.h>
94084c
+#include <support/xsignal.h>
94084c
+#include <support/xthread.h>
94084c
+#include <unistd.h>
94084c
+
94084c
+/* Set to true by timeout_thread_function when the test should
94084c
+   terminate.  */
94084c
+static bool timeout;
94084c
+
94084c
+static void *
94084c
+timeout_thread_function (void *unused)
94084c
+{
94084c
+  usleep (1000 * 1000);
94084c
+  __atomic_store_n (&timeout, true, __ATOMIC_RELAXED);
94084c
+  return NULL;
94084c
+}
94084c
+
94084c
+/* Used to synchronize the sending threads with the target thread and
94084c
+   main thread.  */
94084c
+static pthread_barrier_t barrier_1;
94084c
+static pthread_barrier_t barrier_2;
94084c
+
94084c
+/* The target thread to which signals are to be sent.  */
94084c
+static pthread_t target_thread;
94084c
+
94084c
+/* Set by the main thread to true after timeout has been set to
94084c
+   true.  */
94084c
+static bool exiting;
94084c
+
94084c
+static void *
94084c
+sender_thread_function (void *unused)
94084c
+{
94084c
+  while (true)
94084c
+    {
94084c
+      /* Wait until target_thread has been initialized.  The target
94084c
+         thread and main thread participate in this barrier.  */
94084c
+      xpthread_barrier_wait (&barrier_1);
94084c
+
94084c
+      if (exiting)
94084c
+        break;
94084c
+
94084c
+      xpthread_kill (target_thread, SIGUSR1);
94084c
+
94084c
+      /* Communicate that the signal has been sent.  The main thread
94084c
+         participates in this barrier.  */
94084c
+      xpthread_barrier_wait (&barrier_2);
94084c
+    }
94084c
+  return NULL;
94084c
+}
94084c
+
94084c
+static void *
94084c
+target_thread_function (void *unused)
94084c
+{
94084c
+  target_thread = pthread_self ();
94084c
+  xpthread_barrier_wait (&barrier_1);
94084c
+  return NULL;
94084c
+}
94084c
+
94084c
+static int
94084c
+do_test (void)
94084c
+{
94084c
+  xsignal (SIGUSR1, SIG_IGN);
94084c
+
94084c
+  pthread_t thr_timeout = xpthread_create (NULL, timeout_thread_function, NULL);
94084c
+
94084c
+  pthread_t threads[4];
94084c
+  xpthread_barrier_init (&barrier_1, NULL, array_length (threads) + 2);
94084c
+  xpthread_barrier_init (&barrier_2, NULL, array_length (threads) + 1);
94084c
+
94084c
+  for (int i = 0; i < array_length (threads); ++i)
94084c
+    threads[i] = xpthread_create (NULL, sender_thread_function, NULL);
94084c
+
94084c
+  while (!__atomic_load_n (&timeout, __ATOMIC_RELAXED))
94084c
+    {
94084c
+      xpthread_create (NULL, target_thread_function, NULL);
94084c
+
94084c
+      /* Wait for the target thread to be set up and signal sending to
94084c
+         start.  */
94084c
+      xpthread_barrier_wait (&barrier_1);
94084c
+
94084c
+      /* Wait for signal sending to complete.  */
94084c
+      xpthread_barrier_wait (&barrier_2);
94084c
+
94084c
+      xpthread_join (target_thread);
94084c
+    }
94084c
+
94084c
+  exiting = true;
94084c
+
94084c
+  /* Signal the sending threads to exit.  */
94084c
+  xpthread_create (NULL, target_thread_function, NULL);
94084c
+  xpthread_barrier_wait (&barrier_1);
94084c
+
94084c
+  for (int i = 0; i < array_length (threads); ++i)
94084c
+    xpthread_join (threads[i]);
94084c
+  xpthread_join (thr_timeout);
94084c
+
94084c
+  return 0;
94084c
+}
94084c
+
94084c
+#include <support/test-driver.c>