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