[v2,4/6] gdbserver/linux-low.cc: Connect the inferior to the terminal

Message ID 20240119115659.491195-6-ahajkova@redhat.com
State New
Headers
Series Add vDefaultInferiorFd feature |

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

Alexandra Hájková Jan. 19, 2024, 11:56 a.m. UTC
  If GDBserver is connected to GDB via stdio and it recieved file
descriptors of the STDIN/OUT/ERR of the terminal GDB is connected to,
GDBserver will start the inferior connected to them.
---
 gdbserver/linux-low.cc | 32 +++++++++++++++++++++++++++++++-
 1 file changed, 31 insertions(+), 1 deletion(-)
  

Patch

diff --git a/gdbserver/linux-low.cc b/gdbserver/linux-low.cc
index dc3d2629fdb..2e91f00da24 100644
--- a/gdbserver/linux-low.cc
+++ b/gdbserver/linux-low.cc
@@ -954,6 +954,8 @@  linux_process_target::low_new_thread (lwp_info *info)
 static void
 linux_ptrace_fun ()
 {
+  client_state &cs = get_client_state ();
+
   if (ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
 	      (PTRACE_TYPE_ARG4) 0) < 0)
     trace_start_error_with_name ("ptrace");
@@ -961,10 +963,38 @@  linux_ptrace_fun ()
   if (setpgid (0, 0) < 0)
     trace_start_error_with_name ("setpgid");
 
+  /* If GDBserver is connected to GDB via stdio and it recieved the file
+     descriptors for the terminal stdin/out/err from GDB, start the inferior
+     connected to them.  */
+  if (remote_connection_is_stdio () && cs.vDefaultInferiorFd_accepted)
+  {
+    struct stat buf{};
+
+    if ((fstat(cs.fds[0], &buf) == -1)
+        || (fstat(cs.fds[1], &buf) == -1)
+        || (fstat(cs.fds[2], &buf) == -1))
+    {
+      write (2, "Fstat failed. Can't connect inferior to the terminal.\n",
+             sizeof ("Fstat failed. Can't connect inferior to the terminal.\n") - 1);
+      cs.vDefaultInferiorFd_accepted = false;
+    }
+
+    /* Dupped file descriptors will be inherited by the inferior.  */
+    if (!cs.vDefaultInferiorFd_accepted
+        || (dup2 (cs.fds[0], 0) == -1)
+        || (dup2 (cs.fds[1], 1) == -1)
+        || (dup2 (cs.fds[2], 2) == -1))
+      {
+        write (2, "Dup2 failed. Can't connect inferior to the terminal.\n",
+               sizeof ("Dup2 failed. Can't connect inferior to the terminal.\n") - 1);
+        cs.vDefaultInferiorFd_accepted = false;
+      }
+  }
+
   /* If GDBserver is connected to gdb via stdio, redirect the inferior's
      stdout to stderr so that inferior i/o doesn't corrupt the connection.
      Also, redirect stdin to /dev/null.  */
-  if (remote_connection_is_stdio ())
+  if (remote_connection_is_stdio () && !cs.vDefaultInferiorFd_accepted)
     {
       if (close (0) < 0)
 	trace_start_error_with_name ("close");