[v2] Make `linux_info_proc` prefer using the LWP over the PID

Message ID 20240119164921.62544-1-dark.ryu.550@gmail.com
State New
Headers
Series [v2] Make `linux_info_proc` prefer using the LWP over the PID |

Checks

Context Check Description
linaro-tcwg-bot/tcwg_gdb_build--master-aarch64 success Testing passed
linaro-tcwg-bot/tcwg_gdb_build--master-arm success Testing passed
linaro-tcwg-bot/tcwg_gdb_check--master-aarch64 success Testing passed
linaro-tcwg-bot/tcwg_gdb_check--master-arm success Testing passed

Commit Message

Matheus Branco Borella Jan. 19, 2024, 4:49 p.m. UTC
  Normally, `linux_info_proc` would use the PID to determine which subfolder in
`/proc` to read information from. While this is usually fine, it breaks down
after the main thread exits, at which point the information in `/proc/$pid`
becomes become unreliable, if it is available at all. While it is the case
that most programs terminate after their main thread exits, some may continue
running from detached threads, in which case `info proc` will start misbehaving.

This patch addresses this by making it so that the LWP - the Lightweight Process
ID, that, in the case of GNU/Linux is the number of the process backing up the
thread[1] - is prefered over the PID. By doing this, `linux_info_proc` will
always access valid procfs information, even after the main thread exits.

[1]: https://man7.org/linux/man-pages/man2/clone.2.html

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=31207
---
 gdb/linux-tdep.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
  

Patch

diff --git a/gdb/linux-tdep.c b/gdb/linux-tdep.c
index 82e8bc3db3c..4fa7a98adde 100644
--- a/gdb/linux-tdep.c
+++ b/gdb/linux-tdep.c
@@ -840,7 +840,17 @@  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;
+      /* Seeing as, when the main thread exits, the information in /proc/$pid
+       * becomes unreliable, we should prefer using the current TID, whenever
+       * possible. */
+      pid = 0;
+      struct thread_info *info = any_live_thread_of_inferior (current_inferior ());
+      if (info != nullptr)
+	pid = info->ptid.lwp ();
+
+      /* And fall back to the actual PID only when the TID is not available. */
+      if (pid == 0)
+	pid = current_inferior ()->pid;
     }
 
   args = skip_spaces (args);