Mirror of the gdb-patches mailing list
 help / color / mirror / Atom feed
From: Andrew Burgess <aburgess@redhat.com>
To: gdb-patches@sourceware.org
Cc: Andrew Burgess <aburgess@redhat.com>
Subject: [PATCH 2/3] gdbserver: add support for p/P packets and flag to disable g/G packets
Date: Mon,  9 Nov 2026 15:35:51 +0000	[thread overview]
Message-ID: <56997cef31b53dbd71d0a1cfa5d163aee6e9f422.1794238395.git.aburgess@redhat.com> (raw)
In-Reply-To: <cover.1794238395.git.aburgess@redhat.com>

In the next commit I want to make some changes to GDB's handling of
the 'p' packet.  I was looking for how I could test this packet's
handling using gdbserver and I realised that currently gdbserver
doesn't support the 'p' or 'P' packets at all.  Instead all registers
are read and written using the 'g' and 'G' packets respectively.

I understand that gdbserver is a real tool, so we should not be
overloading it with "testing" features, but supporting the 'p' and 'P'
packets doesn't cost that much, and this would allow for greater
testing of GDB.

So, in this commit I have added a new gdbserver command line option:
--disable-packet=gG, which disables use of the 'g' and 'G' packets.
These now return the empty packet indicating the server doesn't
understand them.  GDB will then fall back to using 'p' and 'P'
packets.

I then add support for these packets to gdbserver.

I have guarded the new code such that these packets will only work
when the g/G packets are disabled.  This maintains gdbserver's current
functionality by default.  But we could, if we wanted, allow the p/P
packets to be used in parallel to the g/G packets.  This might allow
GDB to use p/P in cases where only a few registers need to be read or
written.  However, I propose leaving such a change for the future,
it's not something I plan to work on right now.

Annoyingly there was one fix needed in GDB itself.  The 'g' packet
handling in remote_target::send_g_packet (gdb/remote.c) has a rather
nasty loop which tries to "resync" with gdbserver by resending the 'g'
packet if the response doesn't look right.  This code seems really
suspect to me; I don't know why this would be the correct thing to do
over fixing whatever bug causes the packet exchange to get out of
sync.

Still, this loop didn't know about empty packets, i.e. servers that
don't support the 'g' packet, so GDB would sit in an infinite loop
spamming the gdbserver with 'g' packets.  I've extended this loop so
that if GDB gets back an empty packet then the 'g' packet is
considered answered.

With these fixes in place I was now able to run tests like this:

  make check-gdb RUNTESTFLAGS="--target_board=native-gdbserver \
     GDBSERVER='/path/to/patched/gdbserver --disable-packet=gG'"

And compare the results to those of running without the disable-packet
option.  The only issues I saw were in trace related tests, the
function remote_target::get_trace_status relies on sizeof_g_packet to
define the trace register block.  For a target without 'g' packet
support the sizeof_g_packet becomes 0, which means the trace file
records a register block size of 0, which breaks all the trace related
tests.  This is a pre-existing issue, and not something I plan to
address in this commit.

The new --disable-packet=gG option is not added to the documentation
or the NEWS entry.  This feature is not intended for users.  None of
the other --disable-packet options are mentioned in either of these
sources either.
---
 gdb/remote.c                                  |   1 +
 .../gdb.server/disable-gG-packet.exp          | 143 +++++++++++++++
 gdbserver/server.cc                           | 170 +++++++++++++++++-
 gdbserver/server.h                            |   1 +
 4 files changed, 312 insertions(+), 3 deletions(-)
 create mode 100644 gdb/testsuite/gdb.server/disable-gG-packet.exp

diff --git a/gdb/remote.c b/gdb/remote.c
index a728d57df6e..e33e9f0181d 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -9320,6 +9320,7 @@ remote_target::send_g_packet ()
   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
 	 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
 	 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
+	 && rs->buf[0] != '\0'
 	 && rs->buf[0] != 'x')	/* New: unavailable register value.  */
     {
       remote_debug_printf ("Bad register packet; fetching a new packet");
diff --git a/gdb/testsuite/gdb.server/disable-gG-packet.exp b/gdb/testsuite/gdb.server/disable-gG-packet.exp
new file mode 100644
index 00000000000..1124aab2a75
--- /dev/null
+++ b/gdb/testsuite/gdb.server/disable-gG-packet.exp
@@ -0,0 +1,143 @@
+# 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/>.
+
+# Basic testing of the gdbserver '--disable-packet=gG' option.  Connect GDB
+# to a gdbserver started with default flags.  Send the 'info registers'
+# command and record the register names that are printed.  Also use 'maint
+# packet' to check that the p/P packets are disabled by default.
+#
+# Connect to a new gdbserver, this one started with '--disable-packet=gG'.
+# Send 'info registers' again and check we see the same set of registers.
+# Use 'maint packet' to send some invalid p/P packets and check we get back
+# an error.
+
+load_lib gdbserver-support.exp
+
+standard_testfile normal.c
+
+require allow_gdbserver_tests
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile] } {
+    return
+}
+
+set target_exec [gdbserver_download_current_prog]
+
+# Run 'info registers'.  Build and return an array containing the
+# register names of each register.
+proc register_names_from_info_registers { testname } {
+    set reg_names {}
+    gdb_test_multiple "info registers" $testname -lbl {
+	-re "^info registers(?=\r\n)" {
+	    exp_continue
+	}
+
+	-re "^\r\n$::gdb_prompt $" {
+	    gdb_assert { [llength $reg_names] > 1 } \
+		$gdb_test_name
+	}
+
+	-re "^\r\n(\\S+)\\s+\[^\r\n\]+(?=\r\n)" {
+	    lappend reg_names $expect_out(1,string)
+	    exp_continue
+	}
+    }
+
+    return $reg_names
+}
+
+# Start gdbserver passing it OPTIONS.  Connect to gdbserver and runto
+# the main function.
+proc start_gdbserver_connect_and_runto_main { testname {options ""} } {
+    with_test_prefix $testname {
+	save_vars { ::GDBFLAGS } {
+	    # If GDB and GDBserver are both running locally, set the
+	    # sysroot to avoid reading files via the remote protocol
+	    # (the `is_remote target` check is already done above).
+	    if { ![is_remote host] } {
+		set ::GDBFLAGS "$::GDBFLAGS -ex \"set sysroot\""
+	    }
+
+	    clean_restart $::testfile
+	}
+
+	# Make sure we're disconnected, in case we're testing with an
+	# extended-remote board, therefore already connected.
+	gdb_test "disconnect" ".*"
+
+	set res [gdbserver_start $options $::target_exec]
+
+	set gdbserver_protocol [lindex $res 0]
+	set gdbserver_gdbport [lindex $res 1]
+	gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport
+
+	gdb_breakpoint main
+	gdb_continue_to_breakpoint "break in main"
+    }
+}
+
+start_gdbserver_connect_and_runto_main \
+    "start gdbserver with default flags"
+
+set expected_regnames [register_names_from_info_registers \
+			  "info registers using g packet"]
+
+# Check that the p/P packets are not available by default.
+gdb_test "maint packet p0" \
+    "received: \"\"" \
+    "p packet is disabled"
+gdb_test "maint packet P0=0" \
+    "received: \"\"" \
+    "P packet is disabled"
+
+start_gdbserver_connect_and_runto_main \
+    "start gdbserver without g/G packet" "--disable-packet=gG"
+
+set regnames [register_names_from_info_registers \
+		 "info registers using p packet"]
+
+gdb_assert { $expected_regnames == $regnames } \
+    "saw all the expected registers"
+
+# Check we can write to a register using a 'P' packet.
+gdb_test_no_output "set \$sp = 0x1234"
+gdb_test "maint flush register-cache" \
+    "Register cache flushed\\."
+gdb_test "print/x \$sp" " = 0x0*1234" \
+    "updated stack pointer value seen"
+
+# Test 'p' packet error handling.  Try with a register number that is
+# larger than an int.  Then try with a register number that should fit
+# in an int, but is large enough to be outside the range of valid
+# register numbers.
+gdb_test "maint packet pffffffffffffffffffff" \
+    "received: \"E01\"" \
+    "p-packet, huge regno is an error"
+gdb_test "maint packet pfffffff" \
+    "received: \"E01\"" \
+    "p-packet, large regno is an error"
+gdb_test "maint packet Pffffffffffffffffffff=0" \
+    "received: \"E01\"" \
+    "P-packet, huge regno is an error"
+gdb_test "maint packet Pfffffff=0" \
+    "received: \"E01\"" \
+    "P-packet, large regno is an error"
+
+# Check gdbserver is still running by asking for a valid register.
+gdb_test "maint packet p0" \
+    "received: \"\[0-9a-f\]+\"" \
+    "gdbserver still active"
diff --git a/gdbserver/server.cc b/gdbserver/server.cc
index 74774fcde7c..a41d53c016f 100644
--- a/gdbserver/server.cc
+++ b/gdbserver/server.cc
@@ -144,6 +144,7 @@ bool disable_packet_Tthread;
 bool disable_packet_qC;
 bool disable_packet_qfThreadInfo;
 bool disable_packet_T;
+bool disable_packet_gG;
 
 static unsigned char *mem_buf;
 
@@ -1113,6 +1114,141 @@ handle_general_set (char *own_buf)
   own_buf[0] = 0;
 }
 
+/* Handle the 'p' packet for reading registers.  */
+
+static void
+handle_p_packet (char *own_buf)
+{
+  /* When the 'g' packet is in use, which is the default, all registers are
+     served via the 'g' packet.  If a client tries to use the 'p' packet
+     then gdbserver replies with the empty packet; this function is not
+     called.  */
+  gdb_assert (disable_packet_gG);
+
+  /* This should be checked before we get here.  */
+  gdb_assert (own_buf[0] == 'p');
+
+  /* If target is not running then set an error and return.  */
+  require_running_or_return (own_buf);
+
+  /* The packet format is 'p<regno>' where <regno> is a hex string.  Parse
+     the hex string then check that there is nothing else left in the
+     packet buffer, and that the register number is not out of range.  */
+  ULONGEST hex_value;
+  const char *p = &own_buf[1];
+  const char *end = unpack_varlen_hex (p, &hex_value);
+  if (hex_value > INT_MAX || *end != '\0' || (end - p) > (sizeof (int) * 2))
+    {
+      write_enn (own_buf);
+      return;
+    }
+  int regno = static_cast<int> (hex_value);
+  gdb_assert (regno >= 0);
+
+  if (regno >= static_cast<int> (current_target_desc ()->reg_defs.size ()))
+    {
+      write_enn (own_buf);
+      return;
+    }
+
+  client_state &cs = get_client_state ();
+  if (cs.current_traceframe >= 0)
+    {
+      regcache a_regcache (current_target_desc ());
+
+      if (fetch_traceframe_registers (cs.current_traceframe,
+				      &a_regcache, -1) == 0)
+	collect_register_as_string (&a_regcache, regno, own_buf);
+      else
+	write_enn (own_buf);
+    }
+  else
+    {
+      struct regcache *regcache;
+
+      if (!set_desired_thread ())
+	write_enn (own_buf);
+      else
+	{
+	  regcache = get_thread_regcache (current_thread);
+	  collect_register_as_string (regcache, regno, own_buf);
+	}
+    }
+}
+
+/* Handle the 'P' packet for setting registers.  */
+
+static void
+handle_P_packet (char *own_buf)
+{
+  /* When the 'g' packet is in use, which is the default, all registers are
+     served via the 'g' packet and GDB will then try setting all registers
+     via the 'G' packet.  If however the 'g' packet is disabled then GDB
+     will not use the 'G' packet for setting registers, and instead relies
+     only on the 'P' packet.  */
+  gdb_assert (disable_packet_gG);
+
+  /* This should be checked before we get here.  */
+  gdb_assert (own_buf[0] == 'P');
+
+  /* If target is not running then set an error and return.  */
+  require_running_or_return (own_buf);
+
+  /* Cannot write into a trace frame.  */
+  client_state &cs = get_client_state ();
+  if (cs.current_traceframe >= 0)
+    {
+      write_enn (own_buf);
+      return;
+    }
+
+  /* Set the thread.  */
+  if (!set_desired_thread ())
+    {
+      write_enn (own_buf);
+      return;
+    }
+
+  /* The packet format is 'P<regno>=<value>' where <regno> and <value> are
+     hex strings.  First parse <regno>, check it is in range.  */
+  ULONGEST hex_value;
+  const char *p = &own_buf[1];
+  const char *end = unpack_varlen_hex (p, &hex_value);
+  if (hex_value > INT_MAX || *end != '=' || (end - p) > (sizeof (int) * 2))
+    {
+      write_enn (own_buf);
+      return;
+    }
+  int regno = static_cast<int> (hex_value);
+  gdb_assert (regno >= 0);
+
+  if (regno >= static_cast<int> (current_target_desc ()->reg_defs.size ()))
+    {
+      write_enn (own_buf);
+      return;
+    }
+
+  /* Set P to point to the first character of the <value> hex string.  */
+  p = end + 1;
+
+  /* Parse the <value> hex string.  Ensure that the string is the expected
+     length.  */
+  struct regcache *regcache = get_thread_regcache (current_thread);
+  int reg_size = register_size (regcache->tdesc, regno);
+  gdb_byte *val = (gdb_byte *) alloca (reg_size);
+  int len = strlen (p);
+  int bytes_converted = hex2bin (p, val, reg_size);
+  if (bytes_converted != reg_size || (bytes_converted * 2) != len)
+    {
+      write_enn (own_buf);
+      return;
+    }
+
+  /* Supply the new register value into the register cache.  */
+  supply_register (regcache, regno, val);
+  write_ok (own_buf);
+}
+
 static const char *
 get_features_xml (const char *annex)
 {
@@ -3927,8 +4063,9 @@ gdbserver_usage (FILE *stream)
 	   "  --disable-packet=OPT1[,OPT2,...]\n"
 	   "                        Disable support for RSP packets or features.\n"
 	   "                          Options:\n"
-	   "                            vCont, vConts, T, Tthread, qC, qfThreadInfo and\n"
-	   "                            threads (disable all threading packets).\n"
+	   "                            vCont, vConts, T, Tthread, qC, qfThreadInfo,\n"
+	   "                            threads (disable all threading packets), and\n"
+	   "                            gG.\n"
 	   "\n"
 	   "For more information, consult the GDB manual (available as on-line \n"
 	   "info or a printed manual).\n");
@@ -3946,7 +4083,8 @@ gdbserver_show_disableable (FILE *stream)
 	   "  Tthread     \tPassing the thread specifier in the "
 	   "T stop reply packet\n"
 	   "  threads     \tAll of the above\n"
-	   "  T           \tAll 'T' packets\n");
+	   "  T           \tAll 'T' packets\n"
+	   "  gG          \tThe 'g' and 'G' packets\n");
 }
 
 /* Start up the event loop.  This is the entry point to the event
@@ -4398,6 +4536,8 @@ captured_main (int argc, char *argv[])
 		    disable_packet_qC = true;
 		    disable_packet_qfThreadInfo = true;
 		  }
+		else if (streq ("gG", tok))
+		  disable_packet_gG = true;
 		else
 		  {
 		    fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
@@ -4899,6 +5039,12 @@ process_serial_event (void)
 	}
       break;
     case 'g':
+      if (disable_packet_gG)
+	{
+	  cs.own_buf[0] = '\0';
+	  break;
+	}
+
       require_running_or_break (cs.own_buf);
       if (cs.current_traceframe >= 0)
 	{
@@ -4924,6 +5070,12 @@ process_serial_event (void)
 	}
       break;
     case 'G':
+      if (disable_packet_gG)
+	{
+	  cs.own_buf[0] = '\0';
+	  break;
+	}
+
       require_running_or_break (cs.own_buf);
       if (cs.current_traceframe >= 0)
 	write_enn (cs.own_buf);
@@ -4941,6 +5093,18 @@ process_serial_event (void)
 	    }
 	}
       break;
+    case 'p':
+      if (disable_packet_gG)
+	handle_p_packet (cs.own_buf);
+      else
+	cs.own_buf[0] = '\0';
+      break;
+    case 'P':
+      if (disable_packet_gG)
+	handle_P_packet (cs.own_buf);
+      else
+	cs.own_buf[0] = '\0';
+      break;
     case 'm':
       {
 	require_running_or_break (cs.own_buf);
diff --git a/gdbserver/server.h b/gdbserver/server.h
index 1a9e6ef62f8..ba12e228f98 100644
--- a/gdbserver/server.h
+++ b/gdbserver/server.h
@@ -60,6 +60,7 @@ extern bool disable_packet_Tthread;
 extern bool disable_packet_qC;
 extern bool disable_packet_qfThreadInfo;
 extern bool disable_packet_T;
+extern bool disable_packet_gG;
 
 extern bool run_once;
 extern bool non_stop;
-- 
2.25.4


  parent reply	other threads:[~2026-11-09 15:37 UTC|newest]

Thread overview: 8+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-09 15:35 [PATCH 0/3] gdb/remote: improve packet buffer checks for p packet Andrew Burgess
2026-11-09 15:35 ` [PATCH 1/3] gdbsupport: update comment on hex2bin Andrew Burgess
2026-11-09 16:49   ` Tom Tromey
2026-11-09 15:35 ` Andrew Burgess [this message]
2026-11-09 17:16   ` [PATCH 2/3] gdbserver: add support for p/P packets and flag to disable g/G packets Tom Tromey
2026-11-09 15:35 ` [PATCH 3/3] gdb/remote: improve error checking for 'p' packet reply Andrew Burgess
2026-11-09 17:27   ` Tom Tromey
2026-11-23 16:44     ` Andrew Burgess

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=56997cef31b53dbd71d0a1cfa5d163aee6e9f422.1794238395.git.aburgess@redhat.com \
    --to=aburgess@redhat.com \
    --cc=gdb-patches@sourceware.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