Mirror of the gdb-patches mailing list
 help / color / mirror / Atom feed
From: Matthieu Longo <matthieu.longo@arm.com>
To: <gdb-patches@sourceware.org>, Simon Marchi <simark@simark.ca>
Cc: Matthieu Longo <matthieu.longo@arm.com>,
	Thiago Jung Bauermann <thiago.bauermann@linaro.org>
Subject: [PATCH v2] gdb: rely on the first non-exited thread TPID when reading Linux procfs files
Date: Mon, 24 Aug 2026 17:21:55 +0100	[thread overview]
Message-ID: <20260824162155.467233-1-matthieu.longo@arm.com> (raw)

On Linux, /proc/<pid> is keyed by the thread-group leader PID. When
the leader has exited, some /proc/<pid>/... entries become unavailable
even though another thread is still alive. This can happen, for instance,
when the main thread calls pthread_exit() and another thread continues
the execution (existing test: gcore-stale-thread).

This causes GDB to fail to read procfs entries such as cmdline, cwd,
exe, maps, and smaps when it uses 'current_inferior ()->pid' after the
thread-group leader has exited.

Fix this by adding inferior::first_non_exited_thread(), which returns
the PTID of the first non-exited thread of the inferior. Use its LWP ID
when accessing procfs entries that only need a representative live LWP
belonging to the process.

This is a best-effort choice of a thread that is expected to still exist
in the target. Since GDB's view of the threads list may be stale, the
selected thread may already have exited by the time it is accessed.
Callers must therefore still be prepared to handle that case.

Update the following functions:
 - linux_info_proc
 - linux_process_address_in_memtag_page
 - linux_find_memory_regions_full
 - linux_fill_prpsinfo
 - linux_address_in_shadow_stack_mem_range
to use the first non-exited thread's LWP ID instead of the inferior PID
when constructing procfs paths.

Add a new test in gdb.threads.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=31207

Reviewed-by: Thiago Jung Bauermann <thiago.bauermann@linaro.org>
---
 gdb/inferior.c                                | 12 +++
 gdb/inferior.h                                | 11 +++
 gdb/linux-tdep.c                              | 90 +++++++++++++------
 ...access-procfs-while-thread-leader-exited.c | 48 ++++++++++
 ...cess-procfs-while-thread-leader-exited.exp | 78 ++++++++++++++++
 5 files changed, 211 insertions(+), 28 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.c
 create mode 100644 gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.exp

diff --git a/gdb/inferior.c b/gdb/inferior.c
index 8c619ffec5a..f6d77799ac2 100644
--- a/gdb/inferior.c
+++ b/gdb/inferior.c
@@ -250,6 +250,18 @@ inferior::find_thread (ptid_t ptid)
 
 /* See inferior.h.  */
 
+thread_info *
+inferior::first_non_exited_thread () const
+{
+  auto it = this->ptid_thread_map.cbegin ();
+  if (it != this->ptid_thread_map.cend ())
+    return it->second;
+  else
+    return nullptr;
+}
+
+/* See inferior.h.  */
+
 void
 inferior::clear_thread_list ()
 {
diff --git a/gdb/inferior.h b/gdb/inferior.h
index 217741adc07..34baf743995 100644
--- a/gdb/inferior.h
+++ b/gdb/inferior.h
@@ -513,6 +513,17 @@ class inferior : public refcounted_object,
   /* Find (non-exited) thread PTID of this inferior.  */
   thread_info *find_thread (ptid_t ptid);
 
+  /* Return the first non-exited thread of this inferior.
+
+     This is only a best-effort choice of a thread that is expected to still
+     exist in the target.  A thread may have exited after GDB last updated its
+     thread list, or GDB/gdbserver may have observed the exit but not yet
+     propagated it through all layers.  Therefore the returned thread is not
+     guaranteed to still be alive when it is later accessed.  This avoids the
+     common case where the current thread has exited, but callers must still be
+     prepared for the selected thread to no longer exist.  */
+  thread_info *first_non_exited_thread () const;
+
   /* Delete all threads in the thread list, silently.  */
   void clear_thread_list ();
 
diff --git a/gdb/linux-tdep.c b/gdb/linux-tdep.c
index e37c400bed1..588984a1ca4 100644
--- a/gdb/linux-tdep.c
+++ b/gdb/linux-tdep.c
@@ -456,6 +456,37 @@ linux_has_shared_address_space (struct gdbarch *gdbarch)
   return linux_is_uclinux ();
 }
 
+/* Return a PTID that identifies the current process and can be used to
+   access procfs safely.
+
+   The returned PTID is that of the thread-group leader whenever it is
+   still alive.  If the leader has already exited, the PTID of the first
+   non-exited thread in the current inferior is returned instead.
+   This ensures that the returned PTID always refers to a live thread
+   whose procfs entries are present and populated.  */
+static ptid_t
+get_process_reference_ptid ()
+{
+  /* Get the current thread.  */
+  thread_info *thr = inferior_thread ();
+
+  /* Construct the PTID of the thread-group leader.  On Linux,
+     the leader's LWP ID is equal to the process ID.  */
+  ptid_t leader_ptid (thr->ptid.pid (), thr->ptid.pid ());
+
+  /* Use the thread-group leader if it is still alive.  */
+  thread_info *leader_thr
+    = current_inferior ()->find_thread (leader_ptid);
+  if (leader_thr != nullptr)
+    return leader_thr->ptid;
+
+  /* Otherwise, use the first thread that has not exited.  */
+  thread_info *non_exited_thread
+    = current_inferior ()->first_non_exited_thread ();
+  gdb_assert (non_exited_thread != nullptr);
+  return non_exited_thread->ptid;
+}
+
 /* This is how we want PTIDs from core files to be printed.  */
 
 static std::string
@@ -841,9 +872,7 @@ static void
 linux_info_proc (struct gdbarch *gdbarch, const char *args,
 		 enum info_proc_what what)
 {
-  /* A long is used for pid instead of an int to avoid a loss of precision
-     compiler warning from the output of strtoul.  */
-  long pid;
+  ptid_t ptid;
   int cmdline_f = (what == IP_MINIMAL || what == IP_CMDLINE || what == IP_ALL);
   int cwd_f = (what == IP_MINIMAL || what == IP_CWD || what == IP_ALL);
   int environ_f = (what == IP_ENVIRON || what == IP_ALL);
@@ -858,7 +887,8 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
     {
       char *tem;
 
-      pid = strtoul (args, &tem, 10);
+      long pid = strtoul (args, &tem, 10);
+      ptid = ptid_t (pid, pid);
       args = tem;
     }
   else
@@ -868,17 +898,23 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
       if (current_inferior ()->fake_pid_p)
 	error (_("Can't determine the current process's PID: you must name one."));
 
-      pid = current_inferior ()->pid;
+      ptid = get_process_reference_ptid ();
+
+      if (ptid.pid () == ptid.lwp ())
+	gdb_printf (_("process %d\n"), ptid.pid ());
+      else
+	gdb_printf (_("process %d [Note: information was gathered from LWP %ld " \
+		      "as the thread-group leader (LWP=%d) already exited.]\n"),
+		    ptid.pid (), ptid.lwp (), ptid.pid ());
     }
 
   args = skip_spaces (args);
   if (args && args[0])
     error (_("Too many parameters: %s"), args);
 
-  gdb_printf (_("process %ld\n"), pid);
   if (cmdline_f)
     {
-      xsnprintf (filename, sizeof filename, "/proc/%ld/cmdline", pid);
+      xsnprintf (filename, sizeof filename, "/proc/%ld/cmdline", ptid.lwp ());
       gdb_byte *buffer;
       LONGEST len = target_fileio_read_alloc (nullptr, filename, &buffer);
 
@@ -900,7 +936,7 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
     }
   if (cwd_f)
     {
-      xsnprintf (filename, sizeof filename, "/proc/%ld/cwd", pid);
+      xsnprintf (filename, sizeof filename, "/proc/%ld/cwd", ptid.lwp ());
       std::optional<std::string> contents
 	= target_fileio_readlink (NULL, filename, &target_errno);
       if (contents.has_value ())
@@ -910,7 +946,7 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
     }
   if (environ_f)
     {
-      xsnprintf (filename, sizeof filename, "/proc/%ld/environ", pid);
+      xsnprintf (filename, sizeof filename, "/proc/%ld/environ", ptid.lwp ());
       gdb_byte *buffer;
       LONGEST len = target_fileio_read_alloc (nullptr, filename, &buffer);
 
@@ -934,7 +970,7 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
     }
   if (exe_f)
     {
-      xsnprintf (filename, sizeof filename, "/proc/%ld/exe", pid);
+      xsnprintf (filename, sizeof filename, "/proc/%ld/exe", ptid.lwp ());
       std::optional<std::string> contents
 	= target_fileio_readlink (NULL, filename, &target_errno);
       if (contents.has_value ())
@@ -944,7 +980,7 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
     }
   if (mappings_f)
     {
-      xsnprintf (filename, sizeof filename, "/proc/%ld/maps", pid);
+      xsnprintf (filename, sizeof filename, "/proc/%ld/maps", ptid.lwp ());
       gdb::unique_xmalloc_ptr<char> map
 	= target_fileio_read_stralloc (NULL, filename);
       if (map != NULL)
@@ -989,7 +1025,7 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
     }
   if (status_f)
     {
-      xsnprintf (filename, sizeof filename, "/proc/%ld/status", pid);
+      xsnprintf (filename, sizeof filename, "/proc/%ld/status", ptid.lwp ());
       gdb::unique_xmalloc_ptr<char> status
 	= target_fileio_read_stralloc (NULL, filename);
       if (status)
@@ -999,7 +1035,7 @@ linux_info_proc (struct gdbarch *gdbarch, const char *args,
     }
   if (stat_f)
     {
-      xsnprintf (filename, sizeof filename, "/proc/%ld/stat", pid);
+      xsnprintf (filename, sizeof filename, "/proc/%ld/stat", ptid.lwp ());
       gdb::unique_xmalloc_ptr<char> statstr
 	= target_fileio_read_stralloc (NULL, filename);
       if (statstr)
@@ -1670,9 +1706,9 @@ linux_process_address_in_memtag_page (CORE_ADDR address)
   if (current_inferior ()->fake_pid_p)
     return false;
 
-  pid_t pid = current_inferior ()->pid;
+  ptid_t ptid = get_process_reference_ptid ();
 
-  std::string smaps_file = string_printf ("/proc/%d/smaps", pid);
+  std::string smaps_file = string_printf ("/proc/%ld/smaps", ptid.lwp ());
 
   gdb::unique_xmalloc_ptr<char> data
     = target_fileio_read_stralloc (NULL, smaps_file.c_str ());
@@ -1730,7 +1766,6 @@ linux_find_memory_regions_full (struct gdbarch *gdbarch,
 				linux_dump_mapping_p_ftype *should_dump_mapping_p,
 				linux_find_memory_region_ftype func)
 {
-  pid_t pid;
   /* Default dump behavior of coredump_filter (0x33), according to
      Documentation/filesystems/proc.txt from the Linux kernel
      tree.  */
@@ -1743,12 +1778,12 @@ linux_find_memory_regions_full (struct gdbarch *gdbarch,
   if (current_inferior ()->fake_pid_p)
     return false;
 
-  pid = current_inferior ()->pid;
+  ptid_t ptid = get_process_reference_ptid ();
 
   if (use_coredump_filter)
     {
       std::string core_dump_filter_name
-	= string_printf ("/proc/%d/coredump_filter", pid);
+	= string_printf ("/proc/%ld/coredump_filter", ptid.lwp ());
 
       gdb::unique_xmalloc_ptr<char> coredumpfilterdata
 	= target_fileio_read_stralloc (NULL, core_dump_filter_name.c_str ());
@@ -1762,7 +1797,7 @@ linux_find_memory_regions_full (struct gdbarch *gdbarch,
 	}
     }
 
-  std::string maps_filename = string_printf ("/proc/%d/smaps", pid);
+  std::string maps_filename = string_printf ("/proc/%ld/smaps", ptid.lwp ());
 
   gdb::unique_xmalloc_ptr<char> data
     = target_fileio_read_stralloc (NULL, maps_filename.c_str ());
@@ -1770,7 +1805,7 @@ linux_find_memory_regions_full (struct gdbarch *gdbarch,
   if (data == NULL)
     {
       /* Older Linux kernels did not support /proc/PID/smaps.  */
-      maps_filename = string_printf ("/proc/%d/maps", pid);
+      maps_filename = string_printf ("/proc/%ld/maps", ptid.lwp ());
       data = target_fileio_read_stralloc (NULL, maps_filename.c_str ());
 
       if (data == nullptr)
@@ -2274,7 +2309,7 @@ linux_fill_prpsinfo (struct elf_internal_linux_prpsinfo *p)
   /* The state of the process.  */
   char pr_sname;
   /* The PID of the program which generated the corefile.  */
-  pid_t pid;
+  ptid_t ptid = get_process_reference_ptid ();
   /* Process flags.  */
   unsigned int pr_flag;
   /* Process nice value.  */
@@ -2285,8 +2320,7 @@ linux_fill_prpsinfo (struct elf_internal_linux_prpsinfo *p)
   gdb_assert (p != nullptr);
 
   /* Obtaining PID and filename.  */
-  pid = inferior_ptid.pid ();
-  xsnprintf (filename, sizeof (filename), "/proc/%d/cmdline", (int) pid);
+  xsnprintf (filename, sizeof (filename), "/proc/%ld/cmdline", ptid.lwp ());
   /* The full name of the program which generated the corefile.  */
   gdb_byte *buf = nullptr;
   LONGEST buf_len = target_fileio_read_alloc (nullptr, filename, &buf);
@@ -2309,7 +2343,7 @@ linux_fill_prpsinfo (struct elf_internal_linux_prpsinfo *p)
   memset (p, 0, sizeof (*p));
 
   /* Defining the PID.  */
-  p->pr_pid = pid;
+  p->pr_pid = ptid.pid ();
 
   /* Copying the program name.  Only the basename matters.  */
   basename = lbasename (fname.get ());
@@ -2326,7 +2360,7 @@ linux_fill_prpsinfo (struct elf_internal_linux_prpsinfo *p)
   strncpy (p->pr_psargs, psargs.c_str (), sizeof (p->pr_psargs) - 1);
   p->pr_psargs[sizeof (p->pr_psargs) - 1] = '\0';
 
-  xsnprintf (filename, sizeof (filename), "/proc/%d/stat", (int) pid);
+  xsnprintf (filename, sizeof (filename), "/proc/%ld/stat", ptid.lwp ());
   /* The contents of `/proc/PID/stat'.  */
   gdb::unique_xmalloc_ptr<char> proc_stat_contents
     = target_fileio_read_stralloc (NULL, filename);
@@ -2404,7 +2438,7 @@ linux_fill_prpsinfo (struct elf_internal_linux_prpsinfo *p)
 
   /* Finally, obtaining the UID and GID.  For that, we read and parse the
      contents of the `/proc/PID/status' file.  */
-  xsnprintf (filename, sizeof (filename), "/proc/%d/status", (int) pid);
+  xsnprintf (filename, sizeof (filename), "/proc/%ld/status", ptid.lwp ());
   /* The contents of `/proc/PID/status'.  */
   gdb::unique_xmalloc_ptr<char> proc_status_contents
     = target_fileio_read_stralloc (NULL, filename);
@@ -3205,9 +3239,9 @@ linux_address_in_shadow_stack_mem_range
   if (!target_has_execution () || current_inferior ()->fake_pid_p)
     return false;
 
-  const int pid = current_inferior ()->pid;
+  ptid_t ptid = get_process_reference_ptid ();
 
-  std::string smaps_file = string_printf ("/proc/%d/smaps", pid);
+  std::string smaps_file = string_printf ("/proc/%ld/smaps", ptid.lwp ());
 
   gdb::unique_xmalloc_ptr<char> data
     = target_fileio_read_stralloc (nullptr, smaps_file.c_str ());
diff --git a/gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.c b/gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.c
new file mode 100644
index 00000000000..0686b746c06
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.c
@@ -0,0 +1,48 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2026 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <pthread.h>
+#include <assert.h>
+
+static pthread_t main_thread;
+
+static void *
+start (void *arg)
+{
+  int i;
+
+  i = pthread_join (main_thread, NULL);
+  assert (i == 0);
+
+  return arg; /* break-here */
+}
+
+int
+main (void)
+{
+  pthread_t thread;
+  int i;
+
+  main_thread = pthread_self ();
+
+  i = pthread_create (&thread, NULL, start, NULL);
+  assert (i == 0);
+
+  pthread_exit (NULL);
+  assert (0);
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.exp b/gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.exp
new file mode 100644
index 00000000000..67bf3a17c26
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/access-procfs-while-thread-leader-exited.exp
@@ -0,0 +1,78 @@
+# Copyright 2026 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+standard_testfile
+set corefile [standard_output_file ${testfile}.core]
+
+if {[gdb_compile_pthreads "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable debug] != ""} {
+    return
+}
+
+clean_restart ${testfile}
+
+gdb_test_no_output "set non-stop on"
+
+if {![runto_main]} {
+    return
+}
+
+gdb_test_multiple "info threads" "threads are supported" {
+    -re ".* main .*\r\n$gdb_prompt $" {
+	# OK, threads are supported.
+    }
+    -re "\r\n$gdb_prompt $" {
+	unsupported "gdb does not support threads on this target"
+	return
+    }
+}
+
+gdb_breakpoint ${srcfile}:[gdb_get_line_number "break-here"]
+# gdb_continue_to_breakpoint does not work as it uses "$gdb_prompt $" regex
+# which does not work due to the output: (gdb) [Thread ... exited]
+set name "continue to breakpoint: break-here"
+gdb_test_multiple "continue" $name {
+    -re "Breakpoint .* (at|in) .* break-here .*\r\n$gdb_prompt " {
+	pass $name
+    }
+}
+
+set test "info proc"
+set fail_re \
+    [multi_line \
+	"process $decimal" \
+	"warning: unable to open /proc file '/proc/$decimal/cmdline'" \
+	"warning: unable to read link '/proc/$decimal/cwd'" \
+	"warning: unable to read link '/proc/$decimal/exe'"]
+set pass_re \
+    [multi_line \
+	"process $decimal \\\[Note: information was gathered from LWP $decimal as the thread-group leader \\(LWP=$decimal\\) already exited\\.\\\]" \
+	"cmdline = '$binfile'" \
+	"cwd = '.+'" \
+	"exe = '$binfile'"]
+
+gdb_test_multiple "$test" $test {
+    -re -wrap $fail_re {
+	fail $test
+    }
+    -re -wrap $pass_re {
+	pass $test
+    }
+}
+
+# Do not run "info threads" before "gcore" as it could workaround the bug
+# by discarding non-current exited threads.
+gdb_test "info threads" \
+	 {The current thread <Thread ID 1> has terminated\.  See `help thread'\.} \
+	 "exited thread is current due to non-stop"
-- 
2.55.0


                 reply	other threads:[~2026-08-24 16:24 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260824162155.467233-1-matthieu.longo@arm.com \
    --to=matthieu.longo@arm.com \
    --cc=gdb-patches@sourceware.org \
    --cc=simark@simark.ca \
    --cc=thiago.bauermann@linaro.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox