Mirror of the gdb-patches mailing list
 help / color / mirror / Atom feed
* [PATCH 0/5] gdbserver: fix memory bugs in x, X, m, and M packet handling
@ 2026-11-20 15:12 Andrew Burgess
  2026-11-20 15:12 ` [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets Andrew Burgess
                   ` (4 more replies)
  0 siblings, 5 replies; 14+ messages in thread
From: Andrew Burgess @ 2026-11-20 15:12 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Fix a number of bugs in the handling of x, X, m, and M packets on the gdbserver
side.  These include buffer overflows, allowing the debug client (GDB) to
request allocation of huge memory buffers in gdbserver, which could cause
crashes or slow down, and writing uninitialised memory from gdbserver into the
inferior.

As part of this series I've merged two similar packet handling loops in
gdbserver/remote-utils.cc which removes some duplicate code.

Thanks,
Andrew

---

Andrew Burgess (5):
  gdbserver: avoid buffer overflow from 'm' and 'x' packets
  gdbserver: merge look_up_one_symbol and relocate_instruction packet
    handling
  gdbserver: fix buffer overflow in more m/x packet handling
  gdbserver: reject X packets with an invalid declared length
  gdbserver: reject M packets with an invalid declared length

 gdb/doc/gdb.texinfo                           |  16 +
 gdb/testsuite/gdb.server/mx-packet-overflow.c |  71 ++++
 .../gdb.server/mx-packet-overflow.exp         | 306 +++++++++++++++
 gdbserver/remote-utils.cc                     | 364 ++++++++++--------
 gdbserver/remote-utils.h                      |  10 +-
 gdbserver/server.cc                           |  19 +-
 6 files changed, 624 insertions(+), 162 deletions(-)
 create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.c
 create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.exp


base-commit: 5678a7bfceb3a6ea18bcde1ae68f7e96c43c998b
-- 
2.56.0


^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets
  2026-11-20 15:12 [PATCH 0/5] gdbserver: fix memory bugs in x, X, m, and M packet handling Andrew Burgess
@ 2026-11-20 15:12 ` Andrew Burgess
  2026-11-20 15:37   ` Eli Zaretskii
  2026-11-23  5:26   ` Kevin Buettner
  2026-11-20 15:12 ` [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling Andrew Burgess
                   ` (3 subsequent siblings)
  4 siblings, 2 replies; 14+ messages in thread
From: Andrew Burgess @ 2026-11-20 15:12 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In the process_serial_event function (gdbserver/server.cc), the 'm'
and 'x' packets, which both read inferior memory, take a length from
the incoming packet and read that much data into a fixed-size buffer.
This read can overflow the buffer.

Cap the length to avoid this overflow.  For 'm', the length is capped
at half the buffer size, as the result of the read is passed through
bin2hex, which encodes each byte as two hex characters, doubling the
space required for the result.

For 'x' the raw binary data is returned, so the full buffer size is
available.  The binary data reply places a 'b' at the front; however,
the outbound result buffer is actually sized to 'PBUFSIZ + 1'.  The
'+1' in this case allows for the 'b', as a binary data packet does not
need a trailing '\0' character.

I've added a new test gdb.server/mx-packet-overflow.exp which tests a
number of different read request sizes with the 'm' and 'x' packets.
---
 gdb/doc/gdb.texinfo                           |  16 ++
 gdb/testsuite/gdb.server/mx-packet-overflow.c |  63 ++++++
 .../gdb.server/mx-packet-overflow.exp         | 179 ++++++++++++++++++
 gdbserver/server.cc                           |  15 ++
 4 files changed, 273 insertions(+)
 create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.c
 create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.exp

diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 7998dfb58c8..69f649f2e68 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -43926,6 +43926,13 @@ Packets
 of the region of memory.
 @end table
 
+The maximum requestable @var{length} is limited by the maximum
+supported packet size, which is currently 131104 bytes.  Each byte
+read is returned as two hex characters, so any @var{length} over 65552
+will fail because the reply would exceed the current maximum packet
+length.  The maximum packet length could change in future releases of
+@value{GDBN} and should not be relied on.
+
 Unlike most packets, this packet does not support
 @samp{E.@var{errtext}}-style textual error replies (@pxref{textual
 error reply}) by default.  Stubs should be careful to only send such a
@@ -44312,6 +44319,15 @@ Packets
 for an error
 @end table
 
+The maximum requestable @var{length} is limited by the maximum
+supported packet size, which is currently 131104 bytes.  Any read over
+this length will return an error.  Shorter reads can also fail due to
+added escape bytes (@pxref{Binary Data}).  Worst case is that every
+byte read needs an additional escape byte, which halves the number of
+data bytes that can be returned; any read over 65552 bytes might
+return an error.  The maximum packet length could change in future
+releases of @value{GDBN} and should not be relied on.
+
 @item X @var{addr},@var{length}:@var{XX@dots{}}
 @anchor{X packet}
 @cindex @samp{X} packet
diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.c b/gdb/testsuite/gdb.server/mx-packet-overflow.c
new file mode 100644
index 00000000000..dc3a92d8031
--- /dev/null
+++ b/gdb/testsuite/gdb.server/mx-packet-overflow.c
@@ -0,0 +1,63 @@
+/* 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 <stdlib.h>
+#include <assert.h>
+#include <limits.h>
+
+unsigned char *buffer = NULL;
+size_t buffer_length = 1024 * 1024 * 100;
+volatile int global_var = 0;
+
+/* Is C a byte that must be escaped in a reply from gdbserver to
+   GDB?  Return 1 if it is, otherwise, return 0.  */
+static int
+is_escapable_byte (unsigned char c)
+{
+  switch (c)
+    {
+    case 0x23:
+    case 0x24:
+    case 0x7d:
+    case 0x2a:
+      return 1;
+    default:
+      return 0;
+    }
+}
+
+int
+main ()
+{
+  buffer = malloc ( buffer_length );
+  assert (buffer != NULL);
+
+  unsigned char val = 0;
+  for (size_t i = 0; i < buffer_length; ++i)
+    {
+      buffer[i] = val;
+      do
+	{
+	  val = (val + 1) % UCHAR_MAX;
+	}
+      while (is_escapable_byte (val));
+    }
+
+  global_var = 42;	/* Break here.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
new file mode 100644
index 00000000000..09cb4a4cb83
--- /dev/null
+++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
@@ -0,0 +1,179 @@
+# 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/>.
+
+# Test that the 'm' and 'x' packets protect against buffer overflow.
+
+load_lib gdbserver-support.exp
+
+require allow_gdbserver_tests
+
+standard_testfile
+
+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\""
+    }
+    if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+	return
+    }
+}
+
+# Make sure we're disconnected, in case we're testing with an
+# extended-remote board, therefore already connected.
+gdb_test "disconnect" ".*"
+
+# Start gdbserver and connect.
+set res [gdbserver_spawn ""]
+set gdbserver_protocol [lindex $res 0]
+set gdbserver_gdbport [lindex $res 1]
+set res [gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport]
+if {![gdb_assert {$res == 0} "connect"]} {
+    return
+}
+
+# Get into position for the test.
+gdb_breakpoint [gdb_get_line_number "/* Break here.  */"]
+gdb_continue_to_breakpoint "test position"
+
+# Send PACKET, a full 'm' or 'x' packet, to the server using 'maint
+# packet ...'.  EXPECTED is one of 'hex', 'binary', or 'error', and
+# indicates the type of reply that gdbserver should send.
+#
+#   'hex' -- the result should be a hex encoded data packet, as
+#            returned by a successful 'm' packet.
+#
+#   'binary' -- the result should be a binary encoded data packet, as
+#               returned by a successful 'x' packet.
+#
+#   'error' -- the result should be an error packet, the 'm' or 'x'
+#              packet failed.
+#
+# TESTNAME is used as the name for this test.
+proc send_mx_packet { packet expected testname } {
+    set result ""
+    set drain_buffer false
+
+    # Send the initial packet.  Detect full error reply here, or the
+    # start of a hex or binary encoded result.  Do not parse the GDB
+    # prompt pattern here.
+    gdb_test_multiple "maint packet ${packet}" $testname {
+	-re "\r\nreceived: \"E01\"" {
+	    set result "error"
+	}
+
+	-re "\r\nreceived: \"b\[^\r\n\]*" {
+	    set drain_buffer true
+	    set result "binary"
+	}
+
+	-re "\r\nreceived: \"00\[^\r\n\]*" {
+	    set drain_buffer true
+	    set result "hex"
+	}
+    }
+
+    # If the previous gdb_test_multiple found the start of a data
+    # packet then consume the input now.  This avoids having to read
+    # the entire result into the expect buffer; there could be a lot
+    # of output.  Again, we don't parse the GDB prompt here.
+    if { $drain_buffer } {
+	gdb_test_multiple "" "" {
+	    -re "^\[^\r\n\]+" {
+		exp_continue
+	    }
+
+	    -re "^(?=\r\n)" {
+	    }
+	}
+    }
+
+    # Finally, consume the GDB prompt.  Check that the RESULT matches
+    # EXPECTED.
+    gdb_test_multiple "" "" {
+	-re "\r\n$::gdb_prompt $" {
+	    gdb_assert { $result eq $expected } $testname
+	}
+    }
+
+    return $result
+}
+
+# Send 'm' and 'x' packets to gdbserver with various requested
+# lengths, check that gdbserver handles the packets as we expect,
+# rejecting those that are too long.
+proc run_mx_packet_tests {} {
+    # The size of the buffer allocated within gdbserver.  See PBUFSIZ in
+    # gdbserver/server.h.
+    set pbufsiz 0x20020
+
+    # The address of 'buffer' within the inferior, without the leading '0x'.
+    set addr [get_hexadecimal_valueof buffer 0x0 "get buffer address"]
+    set addr [string range $addr 2 end]
+
+    # The size of buffer.  Leave this as hex with 0x prefix for now.
+    set buffer_len [get_hexadecimal_valueof buffer_length 0x0 "get buffer length"]
+
+    # If we ask GDB to read the entire buffer from the inferior, GDB will
+    # perform many 4-byte reads.  This does a good job of protecting
+    # gdbserver from buffer overflows, but it hides the bug that this test
+    # is trying to expose.
+    #
+    # Manually send 'm' or 'x' packets so we can control the contents.
+    #
+    # Try different sizes, BUFFER_LEN is huge, far bigger than the
+    # allocated buffer.  PBUFSIZ is the exact size of the buffer within
+    # gdbserver used to build the result packet.  Test various sizes based
+    # on PBUFSIZ as well as the full BUFFER_LEN.
+    #
+    # This test works best when gdbserver is built with the address
+    # sanitizers, as out-of-bounds writes will trigger the sanitizer.
+    set test_lengths [list $pbufsiz \
+			  [expr { $pbufsiz + 1 }] \
+			  [expr { $pbufsiz / 2 }] \
+			  [expr { $pbufsiz / 2 + 1 }] \
+			  $buffer_len]
+    foreach_with_prefix req_len $test_lengths {
+	# Make LEN be REQ_LEN in hex, without the '0x' prefix.
+	set len [string range [format "0x%x" $req_len] 2 end]
+
+	# Set M_RESULT and X_RESULT to 'hex', 'binary', or 'error'
+	# depending on what the packet result should be.  See
+	# send_mx_packet for more details.
+	set m_result "hex"
+	set x_result "binary"
+
+	if { $req_len > $pbufsiz } {
+	    set x_result "error"
+	}
+
+	if { $req_len > $pbufsiz / 2 } {
+	    set m_result "error"
+	}
+
+	# Send the packets.
+	send_mx_packet "m${addr},${len}" $m_result \
+	    "test 'm' packet, expect $m_result"
+	send_mx_packet "x${addr},${len}" $x_result \
+	    "test 'x' packet, expect $x_result"
+    }
+}
+
+# Run the m/x packet tests.
+run_mx_packet_tests
diff --git a/gdbserver/server.cc b/gdbserver/server.cc
index 74774fcde7c..7ad40e8e2b2 100644
--- a/gdbserver/server.cc
+++ b/gdbserver/server.cc
@@ -4945,6 +4945,15 @@ process_serial_event (void)
       {
 	require_running_or_break (cs.own_buf);
 	decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
+	/* The bin2hex call converts each byte in MEM_BUF into two hex
+	   characters, doubling the number of bytes required.  We can
+	   therefore only read half a packet's worth of bytes from the
+	   inferior memory.  */
+	if (len > PBUFSIZ / 2)
+	  {
+	    write_enn (cs.own_buf);
+	    break;
+	  }
 	int res = gdb_read_memory (mem_addr, mem_buf, len);
 	if (res < 0)
 	  write_enn (cs.own_buf);
@@ -4964,6 +4973,12 @@ process_serial_event (void)
       {
 	require_running_or_break (cs.own_buf);
 	decode_x_packet (&cs.own_buf[1], &mem_addr, &len);
+	/* Ensure we don't overflow MEM_BUF.  */
+	if (len > PBUFSIZ)
+	  {
+	    write_enn (cs.own_buf);
+	    break;
+	  }
 	int res = gdb_read_memory (mem_addr, mem_buf, len);
 	if (res < 0)
 	  write_enn (cs.own_buf);
-- 
2.56.0


^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling
  2026-11-20 15:12 [PATCH 0/5] gdbserver: fix memory bugs in x, X, m, and M packet handling Andrew Burgess
  2026-11-20 15:12 ` [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets Andrew Burgess
@ 2026-11-20 15:12 ` Andrew Burgess
  2026-11-25  5:55   ` Kevin Buettner
  2026-11-20 15:12 ` [PATCH 3/5] gdbserver: fix buffer overflow in more m/x " Andrew Burgess
                   ` (2 subsequent siblings)
  4 siblings, 1 reply; 14+ messages in thread
From: Andrew Burgess @ 2026-11-20 15:12 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Both the look_up_one_symbol and relocate_instruction functions contain a
loop which handles a limited number of packets received from GDB.  This
commit merges these loops in order to reduce code duplication.  A
follow-up commit fixes a buffer overflow bug in this code.  The bug was
present at both locations, merging the code means only one site needs
fixing.  The new merged code is added in a new function
handle_limited_packets_while_waiting.

There is a potentially user-visible change in this commit though.
Previously look_up_one_symbol handled m, x, and v packets only, while
relocate_instruction handled m, M, x, and X packets.  By merging the
code both functions now handle the superset of these packets, m, M, x,
X, and v.  Both functions contained a comment saying something along the
lines of "we should really handle all packets here, but for now these
will do", I assume the current lists are based on what GDB happens to
send.  Supporting more packets in each case should not have any negative
consequences.  If it turns out that there are problems caused by
accepting this wider set of packets then we can add a packet filter
argument to handle_limited_packets_while_waiting, but I'd prefer to only
do this once we know there's a need for it.

As part of the commit, the result of sending the reply to a 'v' packet
is now error checked; previously, the look_up_one_symbol loop ignored a
failure to send this reply.

Additionally, while thinking about the 'v' packet handling, I wondered
what would happen if we received a vCont or vKill while we were within
look_up_one_symbol or relocate_instruction, and I suspect the outcome
would not be good.  If the inferior disappeared then these functions
might end up trying to operate on freed process state.  The 'v' packet
handling was added in commit:

  commit 28170b88cc8b40fdea2b065dafe6e1872a47ee4e
  Date:   Sat Mar 12 14:03:26 2016 +0100

    gdbserver: Handle 'v' packet while processing qSymbol.

The commit message talks about needing vFile support.  So, while making
this merge I have made the 'v' packet handling stricter.  We now drop
out of the handle_limited_packets_while_waiting loop for vCont, vAttach,
vRun, or vKill.  All other 'v' packets (including vFile) are handled as
before.

To the best of my knowledge, existing GDB does not send any packets
other than m, M, x, X, or v during these two exchanges.  If it did, the
old code would have rejected the packet as a malformed response, and the
resulting symbol lookup or instruction relocation failure would most
likely have shown up as a failing test somewhere.  There should
therefore be no visible changes after this commit.
---
 gdbserver/remote-utils.cc | 294 ++++++++++++++++++--------------------
 1 file changed, 138 insertions(+), 156 deletions(-)

diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
index 8192e4577f2..d1b17a33e2b 100644
--- a/gdbserver/remote-utils.cc
+++ b/gdbserver/remote-utils.cc
@@ -1417,6 +1417,139 @@ clear_symbol_cache (struct sym_cache **symcache_p)
   *symcache_p = NULL;
 }
 
+/* In some cases a packet from the debug client triggers a prolonged
+   packet exchange between gdbserver and the client.  For example,
+   gdbserver can send a qRelocInsn request in response to some
+   packets.  When the debug client receives the qRelocInsn request it
+   will perform a series of memory accesses using x, X, m, or M
+   packets before finally sending its own qRelocInsn reply.
+
+   Similarly, the debug client can send 'qSymbol::'; gdbserver will
+   then request symbol values, which the debug client provides with
+   another qSymbol packet.  Before sending the qSymbol packet, the
+   debug client might access memory or send 'v' packets (for vFile
+   transfers).
+
+   This function takes care of handling the limited set of packets
+   that might arrive while waiting for the final response packet.
+   Returns false if there is a communication error; otherwise returns
+   true, and the first packet that is not one of those handled here is
+   left, unprocessed, in the client_state's OWN_BUF for the caller to
+   handle.
+
+   We ought to handle pretty much any packet at this point while we
+   wait for the final response, but that requires re-entering the main
+   loop.  For now, this is an adequate approximation.  */
+
+static bool
+handle_limited_packets_while_waiting ()
+{
+  client_state &cs = get_client_state ();
+
+  bool leave_packet_handling_loop = false;
+  while (!leave_packet_handling_loop)
+    {
+      int len = getpkt (cs.own_buf);
+      if (len < 0)
+	return false;
+
+      CORE_ADDR mem_addr;
+      unsigned char *mem_buf = nullptr;
+      unsigned int mem_len;
+      int new_len = -1;
+
+      switch (cs.own_buf[0])
+	{
+	case 'm':
+	  {
+	    decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
+	    mem_buf = (unsigned char *) xmalloc (mem_len);
+	    if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
+	      bin2hex (mem_buf, cs.own_buf, mem_len);
+	    else
+	      write_enn (cs.own_buf);
+	  }
+	  break;
+	case 'x':
+	  {
+	    decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len);
+	    mem_buf = (unsigned char *) xmalloc (mem_len);
+	    if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
+	      {
+		gdb_byte *buffer = (gdb_byte *) cs.own_buf;
+		*buffer++ = 'b';
+
+		int out_len_units;
+		new_len = remote_escape_output (mem_buf, mem_len, 1,
+						buffer,
+						&out_len_units,
+						PBUFSIZ);
+		new_len++; /* For the 'b' marker.  */
+
+		if (out_len_units != mem_len)
+		  {
+		    write_enn (cs.own_buf);
+		    new_len = -1;
+		  }
+		else
+		  suppress_next_putpkt_log ();
+	      }
+	    else
+	      write_enn (cs.own_buf);
+	  }
+	  break;
+	case 'X':
+	  {
+	    if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr,
+				 &mem_len, &mem_buf) < 0
+		|| target_write_memory (mem_addr, mem_buf, mem_len) != 0)
+	      write_enn (cs.own_buf);
+	    else
+	      write_ok (cs.own_buf);
+	  }
+	  break;
+	case 'M':
+	  {
+	    decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
+	    if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
+	      write_ok (cs.own_buf);
+	    else
+	      write_enn (cs.own_buf);
+	  }
+	  break;
+	case 'v':
+	  /* Don't service packets that change which process we are
+	     debugging, or its execution state, while we are in the middle
+	     of another operation.  Handling these here could leave the
+	     caller operating on freed, or stale, state.  Any other 'v'
+	     packets, e.g. vFile, are fine to handle.  */
+	  if (startswith (cs.own_buf, "vCont;")
+	      || startswith (cs.own_buf, "vAttach;")
+	      || startswith (cs.own_buf, "vRun;")
+	      || startswith (cs.own_buf, "vKill;"))
+	    leave_packet_handling_loop = true;
+	  else
+	    handle_v_requests (cs.own_buf, len, &new_len);
+	  break;
+	default:
+	  leave_packet_handling_loop = true;
+	  break;
+	}
+      free (mem_buf);
+
+      if (!leave_packet_handling_loop)
+	{
+	  int res = ((new_len == -1)
+		     ? putpkt (cs.own_buf)
+		     : putpkt_binary (cs.own_buf, new_len));
+	  if (res < 0)
+	    return false;
+	}
+    }
+
+  return true;
+}
+
 /* Get the address of NAME, and return it in ADDRP if found.  if
    MAY_ASK_GDB is false, assume symbol cache misses are failures.
    Returns 1 if the symbol is found, 0 if it is not, -1 on error.  */
@@ -1426,7 +1559,6 @@ look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
 {
   client_state &cs = get_client_state ();
   char *p, *q;
-  int len;
   struct sym_cache *sym;
   struct process_info *proc;
 
@@ -1452,83 +1584,9 @@ look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
   if (putpkt (cs.own_buf) < 0)
     return -1;
 
-  len = getpkt (cs.own_buf);
-  if (len < 0)
+  if (!handle_limited_packets_while_waiting ())
     return -1;
 
-  /* We ought to handle pretty much any packet at this point while we
-     wait for the qSymbol "response".  That requires re-entering the
-     main loop.  For now, this is an adequate approximation; allow
-     GDB to read from memory and handle 'v' packets (for vFile transfers)
-     while it figures out the address of the symbol.  */
-  while (1)
-    {
-      CORE_ADDR mem_addr;
-      unsigned char *mem_buf;
-      unsigned int mem_len;
-      int new_len = -1;
-
-      if (cs.own_buf[0] == 'm')
-	{
-	  decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    bin2hex (mem_buf, cs.own_buf, mem_len);
-	  else
-	    write_enn (cs.own_buf);
-	  free (mem_buf);
-	  if (putpkt (cs.own_buf) < 0)
-	    return -1;
-	}
-      else if (cs.own_buf[0] == 'x')
-	{
-	  decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    {
-	      gdb_byte *buffer = (gdb_byte *) cs.own_buf;
-	      *buffer++ = 'b';
-
-	      int out_len_units;
-	      new_len = remote_escape_output (mem_buf, mem_len, 1,
-					      buffer,
-					      &out_len_units,
-					      PBUFSIZ);
-	      new_len++; /* For the 'b' marker.  */
-
-	      if (out_len_units != mem_len)
-		{
-		  write_enn (cs.own_buf);
-		  new_len = -1;
-		}
-	      else
-		suppress_next_putpkt_log ();
-	    }
-	  else
-	    write_enn (cs.own_buf);
-
-	  free (mem_buf);
-	  int res = ((new_len == -1)
-		     ? putpkt (cs.own_buf)
-		     : putpkt_binary (cs.own_buf, new_len));
-	  if (res < 0)
-	    return -1;
-	}
-      else if (cs.own_buf[0] == 'v')
-	{
-	  handle_v_requests (cs.own_buf, len, &new_len);
-	  if (new_len != -1)
-	    putpkt_binary (cs.own_buf, new_len);
-	  else
-	    putpkt (cs.own_buf);
-	}
-      else
-	break;
-      len = getpkt (cs.own_buf);
-      if (len < 0)
-	return -1;
-    }
-
   if (!startswith (cs.own_buf, "qSymbol:"))
     {
       warning (_("Malformed response to qSymbol, ignoring: %s"), cs.own_buf);
@@ -1572,7 +1630,6 @@ int
 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
 {
   client_state &cs = get_client_state ();
-  int len;
   ULONGEST written = 0;
 
   /* Send the request.  */
@@ -1581,87 +1638,12 @@ relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
   if (putpkt (cs.own_buf) < 0)
     return -1;
 
-  len = getpkt (cs.own_buf);
-  if (len < 0)
+  if (!handle_limited_packets_while_waiting ())
     return -1;
 
-  /* We ought to handle pretty much any packet at this point while we
-     wait for the qRelocInsn "response".  That requires re-entering
-     the main loop.  For now, this is an adequate approximation; allow
-     GDB to access memory.  */
-  while (cs.own_buf[0] == 'm' || cs.own_buf[0] == 'M'
-	 || cs.own_buf[0] == 'X' || cs.own_buf[0] == 'x')
-    {
-      CORE_ADDR mem_addr;
-      unsigned char *mem_buf = NULL;
-      unsigned int mem_len;
-      int new_len = -1;
-
-      if (cs.own_buf[0] == 'm')
-	{
-	  decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    bin2hex (mem_buf, cs.own_buf, mem_len);
-	  else
-	    write_enn (cs.own_buf);
-	}
-      else if (cs.own_buf[0] == 'x')
-	{
-	  decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    {
-	      gdb_byte *buffer = (gdb_byte *) cs.own_buf;
-	      *buffer++ = 'b';
-
-	      int out_len_units;
-	      new_len = remote_escape_output (mem_buf, mem_len, 1,
-					      buffer,
-					      &out_len_units,
-					      PBUFSIZ);
-	      new_len++; /* For the 'b' marker.  */
-
-	      if (out_len_units != mem_len)
-		{
-		  write_enn (cs.own_buf);
-		  new_len = -1;
-		}
-	      else
-		suppress_next_putpkt_log ();
-	    }
-	  else
-	    write_enn (cs.own_buf);
-	}
-      else if (cs.own_buf[0] == 'X')
-	{
-	  if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr,
-			       &mem_len, &mem_buf) < 0
-	      || target_write_memory (mem_addr, mem_buf, mem_len) != 0)
-	    write_enn (cs.own_buf);
-	  else
-	    write_ok (cs.own_buf);
-	}
-      else
-	{
-	  decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
-	  if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
-	    write_ok (cs.own_buf);
-	  else
-	    write_enn (cs.own_buf);
-	}
-      free (mem_buf);
-
-      int res = ((new_len == -1)
-		 ? putpkt (cs.own_buf)
-		 : putpkt_binary (cs.own_buf, new_len));
-      if (res < 0)
-	return -1;
-      len = getpkt (cs.own_buf);
-      if (len < 0)
-	return -1;
-    }
-
+  /* When gdbserver sends qRelocInsn back to GDB, GDB itself can reply
+     with an error packet, starting with 'E'.  If this happens, warn
+     the user and return.  */
   if (cs.own_buf[0] == 'E')
     {
       warning (_("An error occurred while relocating an instruction: %s"),
-- 
2.56.0


^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH 3/5] gdbserver: fix buffer overflow in more m/x packet handling
  2026-11-20 15:12 [PATCH 0/5] gdbserver: fix memory bugs in x, X, m, and M packet handling Andrew Burgess
  2026-11-20 15:12 ` [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets Andrew Burgess
  2026-11-20 15:12 ` [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling Andrew Burgess
@ 2026-11-20 15:12 ` Andrew Burgess
  2026-11-25  7:24   ` Kevin Buettner
  2026-11-20 15:12 ` [PATCH 4/5] gdbserver: reject X packets with an invalid declared length Andrew Burgess
  2026-11-20 15:12 ` [PATCH 5/5] gdbserver: reject M " Andrew Burgess
  4 siblings, 1 reply; 14+ messages in thread
From: Andrew Burgess @ 2026-11-20 15:12 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Building on the work from two patches back, this commit addresses more
buffer overflow issues with 'm' and 'x' packet handling.  The function
handle_limited_packets_while_waiting (in gdbserver/remote-utils.cc)
contains a loop which handles a small sub-set of packets, including 'm'
and 'x'.

Both the 'm' and 'x' packets include a length field which declares how
much data should be read from the inferior.  This length is used,
unchecked, to allocate a buffer in gdbserver.  A malicious, or buggy
debug client could ask for a very large read which would cause gdbserver
to go out of memory trying to allocate the buffer.

If the buffer allocation succeeds then the result is copied into the
client_state's own_buf buffer, which is 'PBUFSIZ + 1' bytes in size.
For the 'm' packet the amount written into own_buf is determined by the
size the client requested, which means we could overflow own_buf with
content read from the inferior's memory.

This commit fixes these issues.  For the 'm' packet we only support
lengths up to PBUFSIZ / 2.  Each byte read from the inferior is encoded
as two hex characters, so trying to read any more from the inferior will
overflow own_buf.  This limit is imposed before we try to allocate the
temporary buffer, so we know the requested buffer size will be
reasonable.

For the 'x' packet we only allow reads of up to PBUFSIZ bytes.  This
limit means that the allocated buffer size will be reasonable.  The 'x'
packet code already protected writes into own_buf so overflow was never
a problem in this case.

I've used gdb::unique_xmalloc_ptr to handle the buffer allocations for
'm' and 'x' packets.  This means that for the 'X' and 'M' packets, which
still manage their buffers with xmalloc and free, the MEM_BUF variable
is pushed down into the specific case block for each packet type.  I
also used SCOPE_EXIT to ensure the buffers are always freed for these
two packets.

There's an extension to the gdb.server/mx-packet-overflow.exp test which
manually sends a qSymbol packet to gdbserver to enter
handle_limited_packets_while_waiting, then sends various m and x packets
to test their handling.

It is worth noting that the 'M' and 'X' packet handling performed by
decode_M_packet and decode_X_packet also have issues with trusting
client supplied lengths which could lead to excessive memory allocation
and buffer overflow.  These will be addressed in a follow on commit.
---
 .../gdb.server/mx-packet-overflow.exp         | 40 ++++++++++++++
 gdbserver/remote-utils.cc                     | 54 ++++++++++++++++---
 2 files changed, 86 insertions(+), 8 deletions(-)

diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
index 09cb4a4cb83..3e5f97872d0 100644
--- a/gdb/testsuite/gdb.server/mx-packet-overflow.exp
+++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
@@ -177,3 +177,43 @@ proc run_mx_packet_tests {} {
 
 # Run the m/x packet tests.
 run_mx_packet_tests
+
+# Test within a qSymbol loop.  Send a 'qSymbol::' packet to gdbserver.
+# It should either reply with 'qSymbol:<name>' or 'OK'.  If we get OK
+# then gdbserver doesn't want to know any symbols from GDB, so we
+# cannot get access to its inner packet processing loop.  If we get
+# back a symbol request though, then we can send some m/x packets to
+# test the inner packet processing loop.
+set first_symbol_requested ""
+gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
+    -re -wrap "\r\nreceived: \"OK\"" {
+	unsupported "$gdb_test_name (no symbols requested)"
+    }
+
+    -re -wrap "\r\nreceived: \"qSymbol:(\[^\"\]+)\"" {
+	set first_symbol_requested $expect_out(1,string)
+	pass $gdb_test_name
+    }
+}
+
+# We got a symbol request from gdbserver; run the m/x packet tests
+# then, complete the qSymbol loop.
+if { $first_symbol_requested ne "" } {
+    with_test_prefix "in qSymbol loop" {
+	run_mx_packet_tests
+    }
+
+    set symbol_name $first_symbol_requested
+    gdb_test_multiple "maint packet qSymbol::$symbol_name" \
+	"qSymbol loop completed" {
+	    -re -wrap "\r\nreceived: \"OK\"" {
+		pass $gdb_test_name
+	    }
+
+	    -re -wrap "\r\nreceived: \"qSymbol:(\[^\"\]+)\"" {
+		set symbol_name $expect_out(1,string)
+		send_gdb "maint packet qSymbol::$symbol_name\n"
+		exp_continue
+	    }
+	}
+}
diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
index d1b17a33e2b..0d600e8844d 100644
--- a/gdbserver/remote-utils.cc
+++ b/gdbserver/remote-utils.cc
@@ -1454,7 +1454,6 @@ handle_limited_packets_while_waiting ()
 	return false;
 
       CORE_ADDR mem_addr;
-      unsigned char *mem_buf = nullptr;
       unsigned int mem_len;
       int new_len = -1;
 
@@ -1463,9 +1462,24 @@ handle_limited_packets_while_waiting ()
 	case 'm':
 	  {
 	    decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	    mem_buf = (unsigned char *) xmalloc (mem_len);
-	    if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	      bin2hex (mem_buf, cs.own_buf, mem_len);
+	    /* MEM_LEN will be used to allocate a buffer, MEM_BUF, which is
+	       filled from inferior memory.  The bin2hex call converts each
+	       byte in MEM_BUF into two hex characters, doubling the number
+	       of bytes required.  This result is written to the
+	       client_state's OWN_BUF, which is PBUFSIZ in length (+1 for a
+	       trailing null).  We can therefore only read half a packet's
+	       worth of bytes from the inferior memory; otherwise we will
+	       overflow OWN_BUF.  */
+	    if (mem_len > PBUFSIZ / 2)
+	      {
+		write_enn (cs.own_buf);
+		break;
+	      }
+
+	    gdb::unique_xmalloc_ptr<unsigned char> mem_buf
+	      ((unsigned char *) xmalloc (mem_len));
+	    if (read_inferior_memory (mem_addr, mem_buf.get (), mem_len) == 0)
+	      bin2hex (mem_buf.get (), cs.own_buf, mem_len);
 	    else
 	      write_enn (cs.own_buf);
 	  }
@@ -1473,14 +1487,35 @@ handle_limited_packets_while_waiting ()
 	case 'x':
 	  {
 	    decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	    mem_buf = (unsigned char *) xmalloc (mem_len);
-	    if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
+
+	    /* MEM_LEN will be used to allocate a buffer, MEM_BUF, which is
+	       filled from inferior memory.  This buffer is then escaped
+	       (see remote_escape_output) into the client_state's OWN_BUF,
+	       which is PBUFSIZ in length (+1 for the leading 'b').  The
+	       escaping never reduces the number of bytes needed, so a
+	       request for more than PBUFSIZ bytes could never produce a
+	       complete reply.
+
+	       GDB usually only requests small reads, a few bytes at a time.
+	       So, limiting MEM_LEN to PBUFSIZ will easily handle everything
+	       GDB sends us, and allows other debug clients space to ask for
+	       larger reads if they need it, but still places a sane limit
+	       on the size of buffer we are about to allocate.  */
+	    if (mem_len > PBUFSIZ)
+	      {
+		write_enn (cs.own_buf);
+		break;
+	      }
+
+	    gdb::unique_xmalloc_ptr<unsigned char> mem_buf
+	      ((unsigned char *) xmalloc (mem_len));
+	    if (read_inferior_memory (mem_addr, mem_buf.get (), mem_len) == 0)
 	      {
 		gdb_byte *buffer = (gdb_byte *) cs.own_buf;
 		*buffer++ = 'b';
 
 		int out_len_units;
-		new_len = remote_escape_output (mem_buf, mem_len, 1,
+		new_len = remote_escape_output (mem_buf.get (), mem_len, 1,
 						buffer,
 						&out_len_units,
 						PBUFSIZ);
@@ -1500,6 +1535,8 @@ handle_limited_packets_while_waiting ()
 	  break;
 	case 'X':
 	  {
+	    unsigned char *mem_buf = nullptr;
+	    SCOPE_EXIT { free (mem_buf); };
 	    if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr,
 				 &mem_len, &mem_buf) < 0
 		|| target_write_memory (mem_addr, mem_buf, mem_len) != 0)
@@ -1510,6 +1547,8 @@ handle_limited_packets_while_waiting ()
 	  break;
 	case 'M':
 	  {
+	    unsigned char *mem_buf = nullptr;
+	    SCOPE_EXIT { free (mem_buf); };
 	    decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
 	    if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
 	      write_ok (cs.own_buf);
@@ -1535,7 +1574,6 @@ handle_limited_packets_while_waiting ()
 	  leave_packet_handling_loop = true;
 	  break;
 	}
-      free (mem_buf);
 
       if (!leave_packet_handling_loop)
 	{
-- 
2.56.0


^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH 4/5] gdbserver: reject X packets with an invalid declared length
  2026-11-20 15:12 [PATCH 0/5] gdbserver: fix memory bugs in x, X, m, and M packet handling Andrew Burgess
                   ` (2 preceding siblings ...)
  2026-11-20 15:12 ` [PATCH 3/5] gdbserver: fix buffer overflow in more m/x " Andrew Burgess
@ 2026-11-20 15:12 ` Andrew Burgess
  2026-11-25  7:48   ` Kevin Buettner
  2026-11-25  7:48   ` Kevin Buettner
  2026-11-20 15:12 ` [PATCH 5/5] gdbserver: reject M " Andrew Burgess
  4 siblings, 2 replies; 14+ messages in thread
From: Andrew Burgess @ 2026-11-20 15:12 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The decode_X_packet function in gdbserver/remote-utils.cc decodes
incoming 'X' packets.  Each of these packets includes a declared length
that says how much data the packet is carrying.  When the caller passes
a null pointer for the buffer argument TO_P, decode_X_packet uses this
declared length, unchecked, to allocate a buffer to hold the packet's
data.

One of decode_X_packet's callers, the 'X' case within
handle_limited_packets_while_waiting, passes a null TO_P; this is the
loop that handles packets while gdbserver waits for the reply to a
qSymbol or qRelocInsn query.  A malicious, or buggy, debug client could
reply to a qSymbol query with an X packet that declares a huge length,
for example 'X<addr>,ffffffff:a', while only actually sending a single
byte of data.  This would cause gdbserver to try to allocate a ~4 GB
buffer, at which point gdbserver would either die with an out of memory
error, or slow the machine down through memory pressure.

The main loop's 'X' handling is not affected; it always passes the
static, pre-allocated, mem_buf buffer, so no allocation takes place on
this path.

In this commit, decode_X_packet now rejects any packet for which the
declared length is greater than the number of bytes remaining in the
packet after the header.  The remaining data within the packet might
include escape characters, so we might not need the full buffer size.
But we will never need a buffer larger than the number of bytes
remaining in the packet buffer.  A packet that declares more data than
it has room for can never be complete, so rejecting ths packet is the
right thing to do.  Performing this check before the buffer allocation
means the size of the allocation is now bounded by the size of the
incoming packet.

Packets that carry more data than they declare are still rejected, as
they always were, by the count check on the return value of
remote_unescape_input; however, for these packets, remote_unescape_input
calls error, which throws.  This leaves the pre-existing behaviour for
this mismatch, where gdbserver drops the connection, rather than
replying with an error.  We might want to improve this in the future,
but that is not something I plan to do in this series.

The 'M' packet equivalent, decode_M_packet, still has two problems: the
declared length is used, unchecked, to allocate a buffer, and the return
value from hex2bin, which says how many bytes were actually decoded, is
ignored, so a packet that declares more data than it carries will have
uninitialized bytes from the allocated buffer written into the inferior.
Fixing these problems is left for a follow-on commit.

The gdb.server/mx-packet-overflow.exp test is extended with a new
run_X_packet_tests proc, which is run twice: once against the main
packet loop, and once inside a qSymbol exchange, in order to reach
handle_limited_packets_while_waiting, where the buggy code path lives.
The tests send valid X packets, then read the memory back to check that
the correct bytes were written, as well as sending packets with invalid
declared lengths, and packets where the escaped data expands to fewer
bytes than declared, all of which should be rejected.
---
 gdb/testsuite/gdb.server/mx-packet-overflow.c |  8 +++
 .../gdb.server/mx-packet-overflow.exp         | 60 +++++++++++++++++--
 gdbserver/remote-utils.cc                     | 11 +++-
 3 files changed, 73 insertions(+), 6 deletions(-)

diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.c b/gdb/testsuite/gdb.server/mx-packet-overflow.c
index dc3a92d8031..0603d0c75e7 100644
--- a/gdb/testsuite/gdb.server/mx-packet-overflow.c
+++ b/gdb/testsuite/gdb.server/mx-packet-overflow.c
@@ -20,6 +20,7 @@
 #include <limits.h>
 
 unsigned char *buffer = NULL;
+unsigned char *buffer2 = NULL;
 size_t buffer_length = 1024 * 1024 * 100;
 volatile int global_var = 0;
 
@@ -46,6 +47,9 @@ main ()
   buffer = malloc ( buffer_length );
   assert (buffer != NULL);
 
+  buffer2 = malloc ( buffer_length );
+  assert (buffer2 != NULL);
+
   unsigned char val = 0;
   for (size_t i = 0; i < buffer_length; ++i)
     {
@@ -55,6 +59,10 @@ main ()
 	  val = (val + 1) % UCHAR_MAX;
 	}
       while (is_escapable_byte (val));
+
+      /* BUFFER2 is written to by GDB.  Just make sure it starts in a
+	 known state.  */
+      buffer2[i] = 0;
     }
 
   global_var = 42;	/* Break here.  */
diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
index 3e5f97872d0..e41495b8f86 100644
--- a/gdb/testsuite/gdb.server/mx-packet-overflow.exp
+++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
@@ -15,7 +15,9 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test that the 'm' and 'x' packets protect against buffer overflow.
+# Test that the 'm' and 'x' packets protect against buffer overflow,
+# and that the 'X' packet rejects packets where the declared length
+# doesn't match the amount of data actually sent.
 
 load_lib gdbserver-support.exp
 
@@ -175,14 +177,61 @@ proc run_mx_packet_tests {} {
     }
 }
 
-# Run the m/x packet tests.
+# Send 'X' packets to gdbserver with various different declared
+# lengths and payloads, check that gdbserver handles the packets as we
+# expect; rejecting those where the declared length doesn't match the
+# amount of data actually sent.
+proc run_X_packet_tests {} {
+    # The 'X' packet tests write into the inferior.  Use BUFFER2 as the
+    # write target.
+    set x_addr [get_hexadecimal_valueof buffer2 0x0 "get buffer2 address"]
+    set x_addr [string range $x_addr 2 end]
+
+    # Send a couple of valid 'X' packets, and, for each one, read the
+    # memory back to check that the correct bytes were written.
+    gdb_test "maint packet X${x_addr},4:abcd" "\r\nreceived: \"OK\"" \
+	"test 'X' packet, 4 declared, 4 sent"
+    gdb_test "maint packet m${x_addr},4" "\r\nreceived: \"61626364\"" \
+	"check 'X' packet, 4 declared, wrote correct bytes"
+
+    gdb_test "maint packet X${x_addr},2:ef" "\r\nreceived: \"OK\"" \
+	"test 'X' packet, 2 declared, 2 sent"
+    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"6566\"" \
+	"check 'X' packet, 2 declared, wrote correct bytes"
+
+    # A packet where the data contains escape sequences; the escaped
+    # sequence resolves to two bytes of data, which matches the declared
+    # length, so this should be accepted.
+    gdb_test "maint packet X${x_addr},2:\}G\}H" "\r\nreceived: \"OK\"" \
+	"test 'X' packet, 2 declared, data expands to 2 bytes"
+    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"6768\"" \
+	"check 'X' packet, 2 declared, escaped, wrote correct bytes"
+
+    # Claim to be sending more data than is actually sent.
+    gdb_test "maint packet X${x_addr},8:ab" "\r\nreceived: \"E01\"" \
+	"test 'X' packet, 8 declared, 2 sent"
+
+    # A packet where the declared length is more than the amount of
+    # data sent once the escape sequences have been expanded.
+    gdb_test "maint packet X${x_addr},2:\}A" "\r\nreceived: \"E01\"" \
+	"test 'X' packet, 2 declared, data expands to 1 byte"
+
+    # Claim a huge payload is being sent.  Without some sanity checks
+    # gdbserver would try to allocate a buffer to hold all the
+    # declared data, and run out of memory.
+    gdb_test "maint packet X${x_addr},ffffffff:a" "\r\nreceived: \"E01\"" \
+	"test 'X' packet, huge declared length"
+}
+
+# Run the m/x packet tests, then the 'X' packet tests.
 run_mx_packet_tests
+run_X_packet_tests
 
 # Test within a qSymbol loop.  Send a 'qSymbol::' packet to gdbserver.
 # It should either reply with 'qSymbol:<name>' or 'OK'.  If we get OK
 # then gdbserver doesn't want to know any symbols from GDB, so we
 # cannot get access to its inner packet processing loop.  If we get
-# back a symbol request though, then we can send some m/x packets to
+# back a symbol request though, then we can send some m/x/X packets to
 # test the inner packet processing loop.
 set first_symbol_requested ""
 gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
@@ -196,11 +245,12 @@ gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
     }
 }
 
-# We got a symbol request from gdbserver; run the m/x packet tests
-# then, complete the qSymbol loop.
+# We got a symbol request from gdbserver; run the m/x and 'X' packet
+# tests, then complete the qSymbol loop.
 if { $first_symbol_requested ne "" } {
     with_test_prefix "in qSymbol loop" {
 	run_mx_packet_tests
+	run_X_packet_tests
     }
 
     set symbol_name $first_symbol_requested
diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
index 0d600e8844d..24f7c9ccdb6 100644
--- a/gdbserver/remote-utils.cc
+++ b/gdbserver/remote-utils.cc
@@ -1340,10 +1340,19 @@ decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
       *len_ptr |= fromhex (ch) & 0x0f;
     }
 
+  /* Adjust PACKET_LEN to account for the bytes already read.  */
+  packet_len -= i;
+
+  /*If the declared length is greater than the number of bytes remaining in
+    the packet, then the packet is malformed and cannot possibly carry
+    enough data; reject it.  */
+  if (*len_ptr > packet_len)
+    return -1;
+
   if (*to_p == NULL)
     *to_p = (unsigned char *) xmalloc (*len_ptr);
 
-  if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
+  if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len,
 			     *to_p, *len_ptr) != *len_ptr)
     return -1;
 
-- 
2.56.0


^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH 5/5] gdbserver: reject M packets with an invalid declared length
  2026-11-20 15:12 [PATCH 0/5] gdbserver: fix memory bugs in x, X, m, and M packet handling Andrew Burgess
                   ` (3 preceding siblings ...)
  2026-11-20 15:12 ` [PATCH 4/5] gdbserver: reject X packets with an invalid declared length Andrew Burgess
@ 2026-11-20 15:12 ` Andrew Burgess
  2026-11-25  8:03   ` Kevin Buettner
  4 siblings, 1 reply; 14+ messages in thread
From: Andrew Burgess @ 2026-11-20 15:12 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The decode_M_packet function in gdbserver/remote-utils.cc decodes
incoming 'M' packets.  Each of these packets includes a declared length
that says how much data the packet is carrying.  This declared length
was used, unchecked, in two places: to allocate a buffer to hold the
packet's data, when the caller passes a null pointer for the buffer
argument, TO_P, and as the number of bytes to write into the inferior in
handle_limited_packets_while_waiting and process_serial_event.

In handle_limited_packets_while_waiting we pass a null TO_P to
decode_M_packet. The handle_limited_packets_while_waiting function is
the loop that handles packets while gdbserver waits for the reply to a
qSymbol or qRelocInsn query.  A malicious, or buggy, debug client could
reply to a qSymbol query with an M packet that declares a huge length,
for example 'M<addr>,ffffffff:0a0b0c0d', while only actually sending
four bytes of data.  This would cause gdbserver to try to allocate a ~4
GB buffer, at which point gdbserver would either die with an out of
memory error, or slow the machine down through memory pressure.

If the declared length in the packet was longer than the provided data,
but not enough to crash gdbserver then in decode_M_packet the return
value from hex2bin, which says how many bytes were actually decoded, was
ignored.  The remaining bytes within the allocated buffer would be
uninitialised (containing whatever old content happened to be there),
and this would then be written into the inferior.

In this commit, decode_M_packet now rejects any packet for which the
declared length is not exactly half the number of bytes remaining in the
packet after the header, or for which the remaining number of bytes is
odd.  This is a stricter check than the equivalent for the 'X' packet,
which only requires that the declared length be no greater than the
remaining bytes; the difference is that the data in an M packet is
always encoded as exactly two hex characters per byte, with no escaping,
so the payload length of a well formed packet clearly indicates the
actual data length.

Performing this check before the buffer allocation means the size of the
allocation is now bounded by the size of the incoming packet, and, as
the decoded length is now known to match the declared length, the
uninitialized memory problem is closed too.  A payload that contains
non-hex characters still causes hex2bin to throw an error, which causes
gdbserver to return an error and reset the connection.  This solution is
not ideal, and should probably be adjusted, but I don't plan to work on
that in this series.

To go with the new checks, decode_M_packet now returns a bool to say if
the packet was decoded successfully or not, and both callers have been
updated so that the inferior memory is only written when the packet was
accepted.  The function's comment has moved into remote-utils.h to sit
beside the declaration.

The gdb.server/mx-packet-overflow.exp test is extended: the
run_X_packet_tests proc has been renamed to run_MX_packet_tests and now
also sends M packets.  As with the previous commit, the tests are run
twice, once against the main packet loop, and once inside a qSymbol
exchange, in order to reach handle_limited_packets_while_waiting, where
the vulnerable code path lives.

The tests send valid M packets, then read the memory back to check that
the correct bytes were written, as well as sending packets that declare
too much or too little data, packets with an odd number of payload
characters, and packets with a huge declared length, all of which should
be rejected.
---
 .../gdb.server/mx-packet-overflow.exp         | 69 ++++++++++++++-----
 gdbserver/remote-utils.cc                     | 25 +++++--
 gdbserver/remote-utils.h                      | 10 ++-
 gdbserver/server.cc                           |  4 +-
 4 files changed, 85 insertions(+), 23 deletions(-)

diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
index e41495b8f86..8080cdbb377 100644
--- a/gdb/testsuite/gdb.server/mx-packet-overflow.exp
+++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
@@ -16,8 +16,8 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 # Test that the 'm' and 'x' packets protect against buffer overflow,
-# and that the 'X' packet rejects packets where the declared length
-# doesn't match the amount of data actually sent.
+# and that the 'M' and 'X' packets reject packets where the declared
+# length doesn't match the amount of data actually sent.
 
 load_lib gdbserver-support.exp
 
@@ -177,13 +177,13 @@ proc run_mx_packet_tests {} {
     }
 }
 
-# Send 'X' packets to gdbserver with various different declared
-# lengths and payloads, check that gdbserver handles the packets as we
-# expect; rejecting those where the declared length doesn't match the
-# amount of data actually sent.
-proc run_X_packet_tests {} {
-    # The 'X' packet tests write into the inferior.  Use BUFFER2 as the
-    # write target.
+# Send 'M' and 'X' packets to gdbserver with various different
+# declared lengths and payloads, check that gdbserver handles the
+# packets as we expect; rejecting those where the declared length
+# doesn't match the amount of data actually sent.
+proc run_MX_packet_tests {} {
+    # The 'M' and 'X' packet tests write into the inferior.  Use
+    # BUFFER2 as the write target.
     set x_addr [get_hexadecimal_valueof buffer2 0x0 "get buffer2 address"]
     set x_addr [string range $x_addr 2 end]
 
@@ -221,18 +221,55 @@ proc run_X_packet_tests {} {
     # declared data, and run out of memory.
     gdb_test "maint packet X${x_addr},ffffffff:a" "\r\nreceived: \"E01\"" \
 	"test 'X' packet, huge declared length"
+
+    # Send a couple of valid 'M' packets, and, for each one, read the
+    # memory back to check that the correct bytes were written.
+    gdb_test "maint packet M${x_addr},4:0a0b0c0d" "\r\nreceived: \"OK\"" \
+	"test 'M' packet, 4 declared, 4 sent"
+    gdb_test "maint packet m${x_addr},4" "\r\nreceived: \"0a0b0c0d\"" \
+	"check 'M' packet, 4 declared, wrote correct bytes"
+
+    gdb_test "maint packet M${x_addr},2:0e0f" "\r\nreceived: \"OK\"" \
+	"test 'M' packet, 2 declared, 2 sent"
+    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"0e0f\"" \
+	"check 'M' packet, 2 declared, wrote correct bytes"
+
+    # Claim to be sending more data than is actually sent.
+    gdb_test "maint packet M${x_addr},8:0a0b0c0d" "\r\nreceived: \"E01\"" \
+	"test 'M' packet, 8 declared, 4 sent"
+
+    # Send fewer bytes than are declared.
+    gdb_test "maint packet M${x_addr},2:0a" "\r\nreceived: \"E01\"" \
+	"test 'M' packet, 2 declared, 1 sent"
+
+    # Send more bytes than are declared.
+    gdb_test "maint packet M${x_addr},2:0a0b0c0d" \
+	"\r\nreceived: \"E01\"" "test 'M' packet, 2 declared, 4 sent"
+
+    # Send partial bytes: half a byte too many, and half a byte too
+    # few.
+    gdb_test "maint packet M${x_addr},2:0a0b0" "\r\nreceived: \"E01\"" \
+	"test 'M' packet, 2 declared, 2.5 sent"
+    gdb_test "maint packet M${x_addr},2:0a0" "\r\nreceived: \"E01\"" \
+	"test 'M' packet, 2 declared, 1.5 sent"
+
+    # Claim a huge payload is being sent.  Without some sanity checks
+    # gdbserver would try to allocate a buffer to hold all the
+    # declared data, and run out of memory.
+    gdb_test "maint packet M${x_addr},ffffffff:0a0b0c0d" \
+	"\r\nreceived: \"E01\"" "test 'M' packet, huge declared length"
 }
 
-# Run the m/x packet tests, then the 'X' packet tests.
+# Run the m/x packet tests, then the 'M' and 'X' packet tests.
 run_mx_packet_tests
-run_X_packet_tests
+run_MX_packet_tests
 
 # Test within a qSymbol loop.  Send a 'qSymbol::' packet to gdbserver.
 # It should either reply with 'qSymbol:<name>' or 'OK'.  If we get OK
 # then gdbserver doesn't want to know any symbols from GDB, so we
 # cannot get access to its inner packet processing loop.  If we get
-# back a symbol request though, then we can send some m/x/X packets to
-# test the inner packet processing loop.
+# back a symbol request though, then we can send some m/x/M/X packets
+# to test the inner packet processing loop.
 set first_symbol_requested ""
 gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
     -re -wrap "\r\nreceived: \"OK\"" {
@@ -245,12 +282,12 @@ gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
     }
 }
 
-# We got a symbol request from gdbserver; run the m/x and 'X' packet
-# tests, then complete the qSymbol loop.
+# We got a symbol request from gdbserver; run the m/x, 'M' and 'X'
+# packet tests, then complete the qSymbol loop.
 if { $first_symbol_requested ne "" } {
     with_test_prefix "in qSymbol loop" {
 	run_mx_packet_tests
-	run_X_packet_tests
+	run_MX_packet_tests
     }
 
     set symbol_name $first_symbol_requested
diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
index 24f7c9ccdb6..faf2ed7e3f6 100644
--- a/gdbserver/remote-utils.cc
+++ b/gdbserver/remote-utils.cc
@@ -1301,16 +1301,33 @@ decode_m_packet (const char *from, CORE_ADDR *mem_addr_ptr,
   decode_m_packet_params (from, mem_addr_ptr, len_ptr, '\0');
 }
 
-void
+/* See remote-utils.h.  */
+
+bool
 decode_M_packet (const char *from, CORE_ADDR *mem_addr_ptr,
 		 unsigned int *len_ptr, unsigned char **to_p)
 {
   from = decode_m_packet_params (from, mem_addr_ptr, len_ptr, ':');
 
+  /* Each byte of data is encoded as 2 characters in the remaining packet
+     length.  If there are an odd number of characters remaining, or if the
+     declared length isn't half the remaining packet length, then this is
+     not a valid M packet.  */
+  size_t remaining_packet_len = strlen (from);
+  if (remaining_packet_len % 2 != 0 || *len_ptr != remaining_packet_len / 2)
+    return false;
+
   if (*to_p == NULL)
     *to_p = (unsigned char *) xmalloc (*len_ptr);
 
-  hex2bin (from, *to_p, *len_ptr);
+  int converted = hex2bin (from, *to_p, *len_ptr);
+
+  /* We already sanity checked *LEN_PTR above so we should always convert
+     the expected number of bytes, or hex2bin will throw an exception if it
+     encounters a non-hex character.  */
+  gdb_assert (converted == *len_ptr);
+
+  return true;
 }
 
 void
@@ -1558,8 +1575,8 @@ handle_limited_packets_while_waiting ()
 	  {
 	    unsigned char *mem_buf = nullptr;
 	    SCOPE_EXIT { free (mem_buf); };
-	    decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
-	    if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
+	    if (decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf)
+		&& target_write_memory (mem_addr, mem_buf, mem_len) == 0)
 	      write_ok (cs.own_buf);
 	    else
 	      write_enn (cs.own_buf);
diff --git a/gdbserver/remote-utils.h b/gdbserver/remote-utils.h
index b710a8917f1..9b9e9437829 100644
--- a/gdbserver/remote-utils.h
+++ b/gdbserver/remote-utils.h
@@ -55,8 +55,16 @@ const char *decode_m_packet_params (const char *from, CORE_ADDR *mem_addr_ptr,
 				    const char end_marker);
 void decode_m_packet (const char *from, CORE_ADDR * mem_addr_ptr,
 		      unsigned int *len_ptr);
-void decode_M_packet (const char *from, CORE_ADDR * mem_addr_ptr,
+
+/* Decode an 'M' packet from the buffer FROM.  Place the address into
+   *MEM_ADDR_PTR and the length into *LEN_PTR.  If *TO_P is NULL then
+   allocate a suitably sized buffer and *TO_P is updated.  Decode the
+   data payload from the packet FROM into *TO_P.  Return true if
+   everything succeeded, the M packet data will be in *TO_P.
+   Otherwise return false and *TO_P will not have been touched.  */
+bool decode_M_packet (const char *from, CORE_ADDR * mem_addr_ptr,
 		      unsigned int *len_ptr, unsigned char **to_p);
+
 void decode_x_packet (const char *from, CORE_ADDR *mem_addr_ptr,
 		      unsigned int *len_ptr);
 int decode_X_packet (char *from, int packet_len, CORE_ADDR * mem_addr_ptr,
diff --git a/gdbserver/server.cc b/gdbserver/server.cc
index 7ad40e8e2b2..b62d80b08d4 100644
--- a/gdbserver/server.cc
+++ b/gdbserver/server.cc
@@ -4963,8 +4963,8 @@ process_serial_event (void)
       break;
     case 'M':
       require_running_or_break (cs.own_buf);
-      decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
-      if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
+      if (decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf)
+	  && gdb_write_memory (mem_addr, mem_buf, len) == 0)
 	write_ok (cs.own_buf);
       else
 	write_enn (cs.own_buf);
-- 
2.56.0


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets
  2026-11-20 15:12 ` [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets Andrew Burgess
@ 2026-11-20 15:37   ` Eli Zaretskii
  2026-11-23  5:26   ` Kevin Buettner
  1 sibling, 0 replies; 14+ messages in thread
From: Eli Zaretskii @ 2026-11-20 15:37 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Fri, 20 Nov 2026 15:12:46 +0000
> 
> In the process_serial_event function (gdbserver/server.cc), the 'm'
> and 'x' packets, which both read inferior memory, take a length from
> the incoming packet and read that much data into a fixed-size buffer.
> This read can overflow the buffer.
> 
> Cap the length to avoid this overflow.  For 'm', the length is capped
> at half the buffer size, as the result of the read is passed through
> bin2hex, which encodes each byte as two hex characters, doubling the
> space required for the result.
> 
> For 'x' the raw binary data is returned, so the full buffer size is
> available.  The binary data reply places a 'b' at the front; however,
> the outbound result buffer is actually sized to 'PBUFSIZ + 1'.  The
> '+1' in this case allows for the 'b', as a binary data packet does not
> need a trailing '\0' character.
> 
> I've added a new test gdb.server/mx-packet-overflow.exp which tests a
> number of different read request sizes with the 'm' and 'x' packets.
> ---
>  gdb/doc/gdb.texinfo                           |  16 ++
>  gdb/testsuite/gdb.server/mx-packet-overflow.c |  63 ++++++
>  .../gdb.server/mx-packet-overflow.exp         | 179 ++++++++++++++++++
>  gdbserver/server.cc                           |  15 ++
>  4 files changed, 273 insertions(+)
>  create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.c
>  create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.exp

Thanks, the gdb.texinfo part is okay.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets
  2026-11-20 15:12 ` [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets Andrew Burgess
  2026-11-20 15:37   ` Eli Zaretskii
@ 2026-11-23  5:26   ` Kevin Buettner
  1 sibling, 0 replies; 14+ messages in thread
From: Kevin Buettner @ 2026-11-23  5:26 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches



On 11/20/26 8:12 AM, Andrew Burgess wrote:
> In the process_serial_event function (gdbserver/server.cc), the 'm'
> and 'x' packets, which both read inferior memory, take a length from
> the incoming packet and read that much data into a fixed-size buffer.
> This read can overflow the buffer.
> 
> Cap the length to avoid this overflow.  For 'm', the length is capped
> at half the buffer size, as the result of the read is passed through
> bin2hex, which encodes each byte as two hex characters, doubling the
> space required for the result.
> 
> For 'x' the raw binary data is returned, so the full buffer size is
> available.  The binary data reply places a 'b' at the front; however,
> the outbound result buffer is actually sized to 'PBUFSIZ + 1'.  The
> '+1' in this case allows for the 'b', as a binary data packet does not
> need a trailing '\0' character.
> 
> I've added a new test gdb.server/mx-packet-overflow.exp which tests a
> number of different read request sizes with the 'm' and 'x' packets.

I ran the entire series through my AI review workflow.  For this first
commit, it found a nit in the documentation:

  3. [minor, 1/5 doc] gdb.texinfo limits text is inaccurate.
     SUBSTANTIALLY CONFIRMED. The added paragraphs
     (gdb.texinfo:43929-43935 and :44322-44328) say "maximum supported
     packet size, which is currently 131104 bytes". gdbserver advertises
     PacketSize=%x with PBUFSIZ-1 = 131103 (server.cc:2764), so the
     quoted number does not match what the stub reports; the text also
     states a gdbserver-specific limit in the generic protocol section
     without saying whose limit it is, and attributes future change to
     GDB releases. The numeric mismatch is objective; the wording
     judgements (b)/(c) are editorial.

You can fix that if you want.  I'm not that concerned about an
off-by-one inaccuracy.

(I'm still working through the rest.)

Approved-By: Kevin Buettner <kevinb@redhat.com>


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling
  2026-11-20 15:12 ` [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling Andrew Burgess
@ 2026-11-25  5:55   ` Kevin Buettner
  2026-11-26 14:58     ` Andrew Burgess
  0 siblings, 1 reply; 14+ messages in thread
From: Kevin Buettner @ 2026-11-25  5:55 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches



On 11/20/26 8:12 AM, Andrew Burgess wrote:
> Both the look_up_one_symbol and relocate_instruction functions contain a
> loop which handles a limited number of packets received from GDB.  This
> commit merges these loops in order to reduce code duplication.  A
> follow-up commit fixes a buffer overflow bug in this code.  The bug was
> present at both locations, merging the code means only one site needs
> fixing.  The new merged code is added in a new function
> handle_limited_packets_while_waiting.
> 
> There is a potentially user-visible change in this commit though.
> Previously look_up_one_symbol handled m, x, and v packets only, while
> relocate_instruction handled m, M, x, and X packets.  By merging the
> code both functions now handle the superset of these packets, m, M, x,
> X, and v.  Both functions contained a comment saying something along the
> lines of "we should really handle all packets here, but for now these
> will do", I assume the current lists are based on what GDB happens to
> send.  Supporting more packets in each case should not have any negative
> consequences.  If it turns out that there are problems caused by
> accepting this wider set of packets then we can add a packet filter
> argument to handle_limited_packets_while_waiting, but I'd prefer to only
> do this once we know there's a need for it.
> 
> As part of the commit, the result of sending the reply to a 'v' packet
> is now error checked; previously, the look_up_one_symbol loop ignored a
> failure to send this reply.
> 
> Additionally, while thinking about the 'v' packet handling, I wondered
> what would happen if we received a vCont or vKill while we were within
> look_up_one_symbol or relocate_instruction, and I suspect the outcome
> would not be good.  If the inferior disappeared then these functions
> might end up trying to operate on freed process state.  The 'v' packet
> handling was added in commit:
> 
>   commit 28170b88cc8b40fdea2b065dafe6e1872a47ee4e
>   Date:   Sat Mar 12 14:03:26 2016 +0100
> 
>     gdbserver: Handle 'v' packet while processing qSymbol.
> 
> The commit message talks about needing vFile support.  So, while making
> this merge I have made the 'v' packet handling stricter.  We now drop
> out of the handle_limited_packets_while_waiting loop for vCont, vAttach,
> vRun, or vKill.  All other 'v' packets (including vFile) are handled as
> before.
> 
> To the best of my knowledge, existing GDB does not send any packets
> other than m, M, x, X, or v during these two exchanges.  If it did, the
> old code would have rejected the packet as a malformed response, and the
> resulting symbol lookup or instruction relocation failure would most
> likely have shown up as a failing test somewhere.  There should
> therefore be no visible changes after this commit.

I ran the entire series through an AI patch review.  After reading
through a very dense version of what has now been rewritten to be more
comprehensible, it appeared to me that you were aware of these concerns.
Nonetheless, you may wish to read what Claude thought of this patch:

  I have one point, and I'd class it as a nit: four 'v' packets now get
  no reply when they arrive during a qSymbol or qRelocInsn exchange.

  As I read handle_limited_packets_while_waiting, anything other than
  m, M, x, X, or a 'v' packet ends the loop and is handed back to the
  caller, which expects it to be the qSymbol or qRelocInsn answer.
  With this patch, vCont;, vAttach;, vRun;, and vKill; also end the
  loop instead of being carried out.  I agree with the reason you give:
  carrying out any of them in the middle of the exchange could resume,
  kill, or replace the inferior, and leave the caller working on stale
  or freed state.  Removing that risk fits well in this series.

  The side effect I noticed is that neither caller recognises these
  packets when they come back.  Both print "Malformed response ..."
  and give up, and nothing ever replies to the packet itself.  In the
  qSymbol case the main loop then sends "OK", so a client that sent
  vCont would get "OK" instead of a stop reply, and the two sides end
  up out of step.

  When I compared this with master, I found:

    - qSymbol path: this is new with the patch.  On master these
      packets were carried out and answered (unsafely, as you point
      out).

    - qRelocInsn path: this was already the case.  On master that loop
      ended on every 'v' packet and dropped it in the same way.

    - More generally, any unexpected packet (a 'g', say) was already
      handled like this in both loops.  The patch just puts these four
      packets into that existing group.

  I don't think this needs to hold up the series.  Your commit message
  covers it: these packets now end the loop, existing GDB sends nothing
  but m, M, x, X, or v during these exchanges, and you'd rather add
  filtering "once we know there's a need for it".  GDB can't send vCont
  in the middle of the exchange anyway, because it is busy servicing
  the exchange.  What's left is a protocol mix-up with a client that
  has already broken the protocol, not a memory-safety bug, so leaving
  it seems a reasonable choice to me.

  If you do want to tidy it up, one option would be to reply with an
  error rather than ending the loop:

            if (startswith (cs.own_buf, "vCont;")
                || startswith (cs.own_buf, "vAttach;")
                || startswith (cs.own_buf, "vRun;")
                || startswith (cs.own_buf, "vKill;"))
              write_enn (cs.own_buf);
            else
              handle_v_requests (cs.own_buf, len, &new_len);

  The putpkt at the bottom of the loop would send the E01 straight back
  as the reply to the refused packet, and the loop would go on waiting
  for the real qSymbol or qRelocInsn answer.  The client gets a clear
  refusal, and clients already have to cope with E01 from these
  packets.  The comment above the check would then say "refuse with an
  error" rather than "don't service".  I'd be equally happy to see this
  as a follow-up.

  Otherwise I like this patch.  Merging the two copied loops into one
  function means the later fixes only need one site, the reply to 'v'
  packets is now checked for send errors, and the vFile support added
  in 2016 is kept.

I'm fine with your approach of waiting until there's a demonstrated need
for a fix.  Obviously, if you want to post a follow-up that's okay too.

Approved-By: Kevin Buettner <kevinb@redhat.com>


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 3/5] gdbserver: fix buffer overflow in more m/x packet handling
  2026-11-20 15:12 ` [PATCH 3/5] gdbserver: fix buffer overflow in more m/x " Andrew Burgess
@ 2026-11-25  7:24   ` Kevin Buettner
  0 siblings, 0 replies; 14+ messages in thread
From: Kevin Buettner @ 2026-11-25  7:24 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches



On 11/20/26 8:12 AM, Andrew Burgess wrote:
> Building on the work from two patches back, this commit addresses more
> buffer overflow issues with 'm' and 'x' packet handling.  The function
> handle_limited_packets_while_waiting (in gdbserver/remote-utils.cc)
> contains a loop which handles a small sub-set of packets, including 'm'
> and 'x'.
> 
> Both the 'm' and 'x' packets include a length field which declares how
> much data should be read from the inferior.  This length is used,
> unchecked, to allocate a buffer in gdbserver.  A malicious, or buggy
> debug client could ask for a very large read which would cause gdbserver
> to go out of memory trying to allocate the buffer.
> 
> If the buffer allocation succeeds then the result is copied into the
> client_state's own_buf buffer, which is 'PBUFSIZ + 1' bytes in size.
> For the 'm' packet the amount written into own_buf is determined by the
> size the client requested, which means we could overflow own_buf with
> content read from the inferior's memory.
> 
> This commit fixes these issues.  For the 'm' packet we only support
> lengths up to PBUFSIZ / 2.  Each byte read from the inferior is encoded
> as two hex characters, so trying to read any more from the inferior will
> overflow own_buf.  This limit is imposed before we try to allocate the
> temporary buffer, so we know the requested buffer size will be
> reasonable.
> 
> For the 'x' packet we only allow reads of up to PBUFSIZ bytes.  This
> limit means that the allocated buffer size will be reasonable.  The 'x'
> packet code already protected writes into own_buf so overflow was never
> a problem in this case.
> 
> I've used gdb::unique_xmalloc_ptr to handle the buffer allocations for
> 'm' and 'x' packets.  This means that for the 'X' and 'M' packets, which
> still manage their buffers with xmalloc and free, the MEM_BUF variable
> is pushed down into the specific case block for each packet type.  I
> also used SCOPE_EXIT to ensure the buffers are always freed for these
> two packets.
> 
> There's an extension to the gdb.server/mx-packet-overflow.exp test which
> manually sends a qSymbol packet to gdbserver to enter
> handle_limited_packets_while_waiting, then sends various m and x packets
> to test their handling.
> 
> It is worth noting that the 'M' and 'X' packet handling performed by
> decode_M_packet and decode_X_packet also have issues with trusting
> client supplied lengths which could lead to excessive memory allocation
> and buffer overflow.  These will be addressed in a follow on commit.

Claude's comments on this one:

  Patch 3/5 looks good to me.  I have one optional suggestion, for the
  test.

  The new qSymbol part of mx-packet-overflow.exp calls
  run_mx_packet_tests (and, after patches 4 and 5,
  run_MX_packet_tests) while gdbserver is waiting for the qSymbol
  reply.  Both procs start by calling get_hexadecimal_valueof to find
  the addresses of buffer and buffer2 and the value of buffer_length.
  That means GDB evaluates expressions, and sends its own packets, in
  the middle of the exchange.

  This works today, because GDB reads those variables with 'm' or 'x'
  packets, which handle_limited_packets_while_waiting services.  But
  the test then depends on GDB never sending anything else while
  evaluating an expression.  If that ever changed, gdbserver would
  leave the loop, treat GDB's packet as a malformed qSymbol reply, and
  every later test would fail without pointing at the real cause.

  A cheap way to avoid that is to look the values up once, before
  sending "maint packet qSymbol::", and pass them in, something like:

      set addr [get_hexadecimal_valueof buffer 0x0 \
                    "get buffer address"]
      set buffer_len [get_hexadecimal_valueof buffer_length 0x0 \
                          "get buffer length"]
      ...
      run_mx_packet_tests $addr $buffer_len

  Then the only packets sent during the exchange are the ones the test
  sends on purpose.  It would also avoid running the same "get ...
  address" tests twice under two prefixes.  This is only a robustness
  point, though, so I'm happy for it to go in as is.

For my part, I checked how get_hexadecimal_valueof was being used.  I
discovered that you're correctly stripping the leading `0x` when it
matters.

Approved-By: Kevin Buettner <kevinb@redhat.com>


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 4/5] gdbserver: reject X packets with an invalid declared length
  2026-11-20 15:12 ` [PATCH 4/5] gdbserver: reject X packets with an invalid declared length Andrew Burgess
@ 2026-11-25  7:48   ` Kevin Buettner
  2026-11-25  7:48   ` Kevin Buettner
  1 sibling, 0 replies; 14+ messages in thread
From: Kevin Buettner @ 2026-11-25  7:48 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches


Several nits in this one; see inline, below.

On 11/20/26 8:12 AM, Andrew Burgess wrote:
> The decode_X_packet function in gdbserver/remote-utils.cc decodes
> incoming 'X' packets.  Each of these packets includes a declared length
> that says how much data the packet is carrying.  When the caller passes
> a null pointer for the buffer argument TO_P, decode_X_packet uses this
> declared length, unchecked, to allocate a buffer to hold the packet's
> data.
> 
> One of decode_X_packet's callers, the 'X' case within
> handle_limited_packets_while_waiting, passes a null TO_P; this is the
> loop that handles packets while gdbserver waits for the reply to a
> qSymbol or qRelocInsn query.  A malicious, or buggy, debug client could
> reply to a qSymbol query with an X packet that declares a huge length,
> for example 'X<addr>,ffffffff:a', while only actually sending a single
> byte of data.  This would cause gdbserver to try to allocate a ~4 GB
> buffer, at which point gdbserver would either die with an out of memory
> error, or slow the machine down through memory pressure.
> 
> The main loop's 'X' handling is not affected; it always passes the
> static, pre-allocated, mem_buf buffer, so no allocation takes place on
> this path.
> 
> In this commit, decode_X_packet now rejects any packet for which the
> declared length is greater than the number of bytes remaining in the
> packet after the header.  The remaining data within the packet might
> include escape characters, so we might not need the full buffer size.
> But we will never need a buffer larger than the number of bytes
> remaining in the packet buffer.  A packet that declares more data than
> it has room for can never be complete, so rejecting ths packet is the

s/ths/this/

> right thing to do.  Performing this check before the buffer allocation
> means the size of the allocation is now bounded by the size of the
> incoming packet.
> 
> Packets that carry more data than they declare are still rejected, as
> they always were, by the count check on the return value of
> remote_unescape_input; however, for these packets, remote_unescape_input
> calls error, which throws.  This leaves the pre-existing behaviour for
> this mismatch, where gdbserver drops the connection, rather than
> replying with an error.  We might want to improve this in the future,
> but that is not something I plan to do in this series.
> 
> The 'M' packet equivalent, decode_M_packet, still has two problems: the
> declared length is used, unchecked, to allocate a buffer, and the return
> value from hex2bin, which says how many bytes were actually decoded, is
> ignored, so a packet that declares more data than it carries will have
> uninitialized bytes from the allocated buffer written into the inferior.
> Fixing these problems is left for a follow-on commit.
> 
> The gdb.server/mx-packet-overflow.exp test is extended with a new
> run_X_packet_tests proc, which is run twice: once against the main
> packet loop, and once inside a qSymbol exchange, in order to reach
> handle_limited_packets_while_waiting, where the buggy code path lives.
> The tests send valid X packets, then read the memory back to check that
> the correct bytes were written, as well as sending packets with invalid
> declared lengths, and packets where the escaped data expands to fewer
> bytes than declared, all of which should be rejected.
> ---
>  gdb/testsuite/gdb.server/mx-packet-overflow.c |  8 +++
>  .../gdb.server/mx-packet-overflow.exp         | 60 +++++++++++++++++--
>  gdbserver/remote-utils.cc                     | 11 +++-
>  3 files changed, 73 insertions(+), 6 deletions(-)
> 
> diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.c b/gdb/testsuite/gdb.server/mx-packet-overflow.c
> index dc3a92d8031..0603d0c75e7 100644
> --- a/gdb/testsuite/gdb.server/mx-packet-overflow.c
> +++ b/gdb/testsuite/gdb.server/mx-packet-overflow.c
> @@ -20,6 +20,7 @@
>  #include <limits.h>
>  
>  unsigned char *buffer = NULL;
> +unsigned char *buffer2 = NULL;
>  size_t buffer_length = 1024 * 1024 * 100;
>  volatile int global_var = 0;
>  
> @@ -46,6 +47,9 @@ main ()
>    buffer = malloc ( buffer_length );
>    assert (buffer != NULL);
>  
> +  buffer2 = malloc ( buffer_length );

Could the size of buffer2 be reduced?  (Claude tells me that only 4
bytes are written to it, but recommends a buffer size of perhaps 16
bytes.  I checked and it looks that way to me as well.)

> +  assert (buffer2 != NULL);
> +
>    unsigned char val = 0;
>    for (size_t i = 0; i < buffer_length; ++i)
>      {
> @@ -55,6 +59,10 @@ main ()
>  	  val = (val + 1) % UCHAR_MAX;
>  	}
>        while (is_escapable_byte (val));
> +
> +      /* BUFFER2 is written to by GDB.  Just make sure it starts in a
> +	 known state.  */
> +      buffer2[i] = 0;
>      }
>  
>    global_var = 42;	/* Break here.  */
> diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> index 3e5f97872d0..e41495b8f86 100644
> --- a/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> +++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> @@ -15,7 +15,9 @@
>  # You should have received a copy of the GNU General Public License
>  # along with this program.  If not, see <http://www.gnu.org/licenses/>.
>  
> -# Test that the 'm' and 'x' packets protect against buffer overflow.
> +# Test that the 'm' and 'x' packets protect against buffer overflow,
> +# and that the 'X' packet rejects packets where the declared length
> +# doesn't match the amount of data actually sent.
>  
>  load_lib gdbserver-support.exp
>  
> @@ -175,14 +177,61 @@ proc run_mx_packet_tests {} {
>      }
>  }
>  
> -# Run the m/x packet tests.
> +# Send 'X' packets to gdbserver with various different declared
> +# lengths and payloads, check that gdbserver handles the packets as we
> +# expect; rejecting those where the declared length doesn't match the
> +# amount of data actually sent.
> +proc run_X_packet_tests {} {
> +    # The 'X' packet tests write into the inferior.  Use BUFFER2 as the
> +    # write target.
> +    set x_addr [get_hexadecimal_valueof buffer2 0x0 "get buffer2 address"]
> +    set x_addr [string range $x_addr 2 end]
> +
> +    # Send a couple of valid 'X' packets, and, for each one, read the
> +    # memory back to check that the correct bytes were written.
> +    gdb_test "maint packet X${x_addr},4:abcd" "\r\nreceived: \"OK\"" \
> +	"test 'X' packet, 4 declared, 4 sent"
> +    gdb_test "maint packet m${x_addr},4" "\r\nreceived: \"61626364\"" \
> +	"check 'X' packet, 4 declared, wrote correct bytes"
> +
> +    gdb_test "maint packet X${x_addr},2:ef" "\r\nreceived: \"OK\"" \
> +	"test 'X' packet, 2 declared, 2 sent"
> +    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"6566\"" \
> +	"check 'X' packet, 2 declared, wrote correct bytes"
> +
> +    # A packet where the data contains escape sequences; the escaped
> +    # sequence resolves to two bytes of data, which matches the declared
> +    # length, so this should be accepted.
> +    gdb_test "maint packet X${x_addr},2:\}G\}H" "\r\nreceived: \"OK\"" \
> +	"test 'X' packet, 2 declared, data expands to 2 bytes"
> +    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"6768\"" \
> +	"check 'X' packet, 2 declared, escaped, wrote correct bytes"
> +
> +    # Claim to be sending more data than is actually sent.
> +    gdb_test "maint packet X${x_addr},8:ab" "\r\nreceived: \"E01\"" \
> +	"test 'X' packet, 8 declared, 2 sent"
> +
> +    # A packet where the declared length is more than the amount of
> +    # data sent once the escape sequences have been expanded.
> +    gdb_test "maint packet X${x_addr},2:\}A" "\r\nreceived: \"E01\"" \
> +	"test 'X' packet, 2 declared, data expands to 1 byte"
> +
> +    # Claim a huge payload is being sent.  Without some sanity checks
> +    # gdbserver would try to allocate a buffer to hold all the
> +    # declared data, and run out of memory.
> +    gdb_test "maint packet X${x_addr},ffffffff:a" "\r\nreceived: \"E01\"" \
> +	"test 'X' packet, huge declared length"
> +}
> +
> +# Run the m/x packet tests, then the 'X' packet tests.
>  run_mx_packet_tests
> +run_X_packet_tests
>  
>  # Test within a qSymbol loop.  Send a 'qSymbol::' packet to gdbserver.
>  # It should either reply with 'qSymbol:<name>' or 'OK'.  If we get OK
>  # then gdbserver doesn't want to know any symbols from GDB, so we
>  # cannot get access to its inner packet processing loop.  If we get
> -# back a symbol request though, then we can send some m/x packets to
> +# back a symbol request though, then we can send some m/x/X packets to
>  # test the inner packet processing loop.
>  set first_symbol_requested ""
>  gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
> @@ -196,11 +245,12 @@ gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
>      }
>  }
>  
> -# We got a symbol request from gdbserver; run the m/x packet tests
> -# then, complete the qSymbol loop.
> +# We got a symbol request from gdbserver; run the m/x and 'X' packet
> +# tests, then complete the qSymbol loop.
>  if { $first_symbol_requested ne "" } {
>      with_test_prefix "in qSymbol loop" {
>  	run_mx_packet_tests
> +	run_X_packet_tests
>      }
>  
>      set symbol_name $first_symbol_requested
> diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
> index 0d600e8844d..24f7c9ccdb6 100644
> --- a/gdbserver/remote-utils.cc
> +++ b/gdbserver/remote-utils.cc
> @@ -1340,10 +1340,19 @@ decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
>        *len_ptr |= fromhex (ch) & 0x0f;
>      }
>  
> +  /* Adjust PACKET_LEN to account for the bytes already read.  */
> +  packet_len -= i;
> +
> +  /*If the declared length is greater than the number of bytes remaining in

Add a space between the asterisk and the 'I' (in 'If').  Adjust
following lines to match.

> +    the packet, then the packet is malformed and cannot possibly carry
> +    enough data; reject it.  */
> +  if (*len_ptr > packet_len)
> +    return -1;
> +
>    if (*to_p == NULL)
>      *to_p = (unsigned char *) xmalloc (*len_ptr);
>  
> -  if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
> +  if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len,
>  			     *to_p, *len_ptr) != *len_ptr)
>      return -1;
>  

Consider changing the return type of decode_X_packet to bool like you
did for decode_M_packet in part 5.  decode_X_packet could do with a
comment as well.

With those nits fixed:

Approved-By: Kevin Buettner <kevinb@redhat.com>


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 4/5] gdbserver: reject X packets with an invalid declared length
  2026-11-20 15:12 ` [PATCH 4/5] gdbserver: reject X packets with an invalid declared length Andrew Burgess
  2026-11-25  7:48   ` Kevin Buettner
@ 2026-11-25  7:48   ` Kevin Buettner
  1 sibling, 0 replies; 14+ messages in thread
From: Kevin Buettner @ 2026-11-25  7:48 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches


Several nits in this one; see inline, below.

On 11/20/26 8:12 AM, Andrew Burgess wrote:
> The decode_X_packet function in gdbserver/remote-utils.cc decodes
> incoming 'X' packets.  Each of these packets includes a declared length
> that says how much data the packet is carrying.  When the caller passes
> a null pointer for the buffer argument TO_P, decode_X_packet uses this
> declared length, unchecked, to allocate a buffer to hold the packet's
> data.
> 
> One of decode_X_packet's callers, the 'X' case within
> handle_limited_packets_while_waiting, passes a null TO_P; this is the
> loop that handles packets while gdbserver waits for the reply to a
> qSymbol or qRelocInsn query.  A malicious, or buggy, debug client could
> reply to a qSymbol query with an X packet that declares a huge length,
> for example 'X<addr>,ffffffff:a', while only actually sending a single
> byte of data.  This would cause gdbserver to try to allocate a ~4 GB
> buffer, at which point gdbserver would either die with an out of memory
> error, or slow the machine down through memory pressure.
> 
> The main loop's 'X' handling is not affected; it always passes the
> static, pre-allocated, mem_buf buffer, so no allocation takes place on
> this path.
> 
> In this commit, decode_X_packet now rejects any packet for which the
> declared length is greater than the number of bytes remaining in the
> packet after the header.  The remaining data within the packet might
> include escape characters, so we might not need the full buffer size.
> But we will never need a buffer larger than the number of bytes
> remaining in the packet buffer.  A packet that declares more data than
> it has room for can never be complete, so rejecting ths packet is the

s/ths/this/

> right thing to do.  Performing this check before the buffer allocation
> means the size of the allocation is now bounded by the size of the
> incoming packet.
> 
> Packets that carry more data than they declare are still rejected, as
> they always were, by the count check on the return value of
> remote_unescape_input; however, for these packets, remote_unescape_input
> calls error, which throws.  This leaves the pre-existing behaviour for
> this mismatch, where gdbserver drops the connection, rather than
> replying with an error.  We might want to improve this in the future,
> but that is not something I plan to do in this series.
> 
> The 'M' packet equivalent, decode_M_packet, still has two problems: the
> declared length is used, unchecked, to allocate a buffer, and the return
> value from hex2bin, which says how many bytes were actually decoded, is
> ignored, so a packet that declares more data than it carries will have
> uninitialized bytes from the allocated buffer written into the inferior.
> Fixing these problems is left for a follow-on commit.
> 
> The gdb.server/mx-packet-overflow.exp test is extended with a new
> run_X_packet_tests proc, which is run twice: once against the main
> packet loop, and once inside a qSymbol exchange, in order to reach
> handle_limited_packets_while_waiting, where the buggy code path lives.
> The tests send valid X packets, then read the memory back to check that
> the correct bytes were written, as well as sending packets with invalid
> declared lengths, and packets where the escaped data expands to fewer
> bytes than declared, all of which should be rejected.
> ---
>  gdb/testsuite/gdb.server/mx-packet-overflow.c |  8 +++
>  .../gdb.server/mx-packet-overflow.exp         | 60 +++++++++++++++++--
>  gdbserver/remote-utils.cc                     | 11 +++-
>  3 files changed, 73 insertions(+), 6 deletions(-)
> 
> diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.c b/gdb/testsuite/gdb.server/mx-packet-overflow.c
> index dc3a92d8031..0603d0c75e7 100644
> --- a/gdb/testsuite/gdb.server/mx-packet-overflow.c
> +++ b/gdb/testsuite/gdb.server/mx-packet-overflow.c
> @@ -20,6 +20,7 @@
>  #include <limits.h>
>  
>  unsigned char *buffer = NULL;
> +unsigned char *buffer2 = NULL;
>  size_t buffer_length = 1024 * 1024 * 100;
>  volatile int global_var = 0;
>  
> @@ -46,6 +47,9 @@ main ()
>    buffer = malloc ( buffer_length );
>    assert (buffer != NULL);
>  
> +  buffer2 = malloc ( buffer_length );

Could the size of buffer2 be reduced?  (Claude tells me that only 4
bytes are written to it, but recommends a buffer size of perhaps 16
bytes.  I checked and it looks that way to me as well.)

> +  assert (buffer2 != NULL);
> +
>    unsigned char val = 0;
>    for (size_t i = 0; i < buffer_length; ++i)
>      {
> @@ -55,6 +59,10 @@ main ()
>  	  val = (val + 1) % UCHAR_MAX;
>  	}
>        while (is_escapable_byte (val));
> +
> +      /* BUFFER2 is written to by GDB.  Just make sure it starts in a
> +	 known state.  */
> +      buffer2[i] = 0;
>      }
>  
>    global_var = 42;	/* Break here.  */
> diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> index 3e5f97872d0..e41495b8f86 100644
> --- a/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> +++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> @@ -15,7 +15,9 @@
>  # You should have received a copy of the GNU General Public License
>  # along with this program.  If not, see <http://www.gnu.org/licenses/>.
>  
> -# Test that the 'm' and 'x' packets protect against buffer overflow.
> +# Test that the 'm' and 'x' packets protect against buffer overflow,
> +# and that the 'X' packet rejects packets where the declared length
> +# doesn't match the amount of data actually sent.
>  
>  load_lib gdbserver-support.exp
>  
> @@ -175,14 +177,61 @@ proc run_mx_packet_tests {} {
>      }
>  }
>  
> -# Run the m/x packet tests.
> +# Send 'X' packets to gdbserver with various different declared
> +# lengths and payloads, check that gdbserver handles the packets as we
> +# expect; rejecting those where the declared length doesn't match the
> +# amount of data actually sent.
> +proc run_X_packet_tests {} {
> +    # The 'X' packet tests write into the inferior.  Use BUFFER2 as the
> +    # write target.
> +    set x_addr [get_hexadecimal_valueof buffer2 0x0 "get buffer2 address"]
> +    set x_addr [string range $x_addr 2 end]
> +
> +    # Send a couple of valid 'X' packets, and, for each one, read the
> +    # memory back to check that the correct bytes were written.
> +    gdb_test "maint packet X${x_addr},4:abcd" "\r\nreceived: \"OK\"" \
> +	"test 'X' packet, 4 declared, 4 sent"
> +    gdb_test "maint packet m${x_addr},4" "\r\nreceived: \"61626364\"" \
> +	"check 'X' packet, 4 declared, wrote correct bytes"
> +
> +    gdb_test "maint packet X${x_addr},2:ef" "\r\nreceived: \"OK\"" \
> +	"test 'X' packet, 2 declared, 2 sent"
> +    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"6566\"" \
> +	"check 'X' packet, 2 declared, wrote correct bytes"
> +
> +    # A packet where the data contains escape sequences; the escaped
> +    # sequence resolves to two bytes of data, which matches the declared
> +    # length, so this should be accepted.
> +    gdb_test "maint packet X${x_addr},2:\}G\}H" "\r\nreceived: \"OK\"" \
> +	"test 'X' packet, 2 declared, data expands to 2 bytes"
> +    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"6768\"" \
> +	"check 'X' packet, 2 declared, escaped, wrote correct bytes"
> +
> +    # Claim to be sending more data than is actually sent.
> +    gdb_test "maint packet X${x_addr},8:ab" "\r\nreceived: \"E01\"" \
> +	"test 'X' packet, 8 declared, 2 sent"
> +
> +    # A packet where the declared length is more than the amount of
> +    # data sent once the escape sequences have been expanded.
> +    gdb_test "maint packet X${x_addr},2:\}A" "\r\nreceived: \"E01\"" \
> +	"test 'X' packet, 2 declared, data expands to 1 byte"
> +
> +    # Claim a huge payload is being sent.  Without some sanity checks
> +    # gdbserver would try to allocate a buffer to hold all the
> +    # declared data, and run out of memory.
> +    gdb_test "maint packet X${x_addr},ffffffff:a" "\r\nreceived: \"E01\"" \
> +	"test 'X' packet, huge declared length"
> +}
> +
> +# Run the m/x packet tests, then the 'X' packet tests.
>  run_mx_packet_tests
> +run_X_packet_tests
>  
>  # Test within a qSymbol loop.  Send a 'qSymbol::' packet to gdbserver.
>  # It should either reply with 'qSymbol:<name>' or 'OK'.  If we get OK
>  # then gdbserver doesn't want to know any symbols from GDB, so we
>  # cannot get access to its inner packet processing loop.  If we get
> -# back a symbol request though, then we can send some m/x packets to
> +# back a symbol request though, then we can send some m/x/X packets to
>  # test the inner packet processing loop.
>  set first_symbol_requested ""
>  gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
> @@ -196,11 +245,12 @@ gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
>      }
>  }
>  
> -# We got a symbol request from gdbserver; run the m/x packet tests
> -# then, complete the qSymbol loop.
> +# We got a symbol request from gdbserver; run the m/x and 'X' packet
> +# tests, then complete the qSymbol loop.
>  if { $first_symbol_requested ne "" } {
>      with_test_prefix "in qSymbol loop" {
>  	run_mx_packet_tests
> +	run_X_packet_tests
>      }
>  
>      set symbol_name $first_symbol_requested
> diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
> index 0d600e8844d..24f7c9ccdb6 100644
> --- a/gdbserver/remote-utils.cc
> +++ b/gdbserver/remote-utils.cc
> @@ -1340,10 +1340,19 @@ decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
>        *len_ptr |= fromhex (ch) & 0x0f;
>      }
>  
> +  /* Adjust PACKET_LEN to account for the bytes already read.  */
> +  packet_len -= i;
> +
> +  /*If the declared length is greater than the number of bytes remaining in

Add a space between the asterisk and the 'I' (in 'If').  Adjust
following lines to match.

> +    the packet, then the packet is malformed and cannot possibly carry
> +    enough data; reject it.  */
> +  if (*len_ptr > packet_len)
> +    return -1;
> +
>    if (*to_p == NULL)
>      *to_p = (unsigned char *) xmalloc (*len_ptr);
>  
> -  if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
> +  if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len,
>  			     *to_p, *len_ptr) != *len_ptr)
>      return -1;
>  

Consider changing the return type of decode_X_packet to bool like you
did for decode_M_packet in part 5.  decode_X_packet could do with a
comment as well.

With those nits fixed:

Approved-By: Kevin Buettner <kevinb@redhat.com>


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 5/5] gdbserver: reject M packets with an invalid declared length
  2026-11-20 15:12 ` [PATCH 5/5] gdbserver: reject M " Andrew Burgess
@ 2026-11-25  8:03   ` Kevin Buettner
  0 siblings, 0 replies; 14+ messages in thread
From: Kevin Buettner @ 2026-11-25  8:03 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

Just one nit involving a comment in this one.

On 11/20/26 8:12 AM, Andrew Burgess wrote:
> The decode_M_packet function in gdbserver/remote-utils.cc decodes
> incoming 'M' packets.  Each of these packets includes a declared length
> that says how much data the packet is carrying.  This declared length
> was used, unchecked, in two places: to allocate a buffer to hold the
> packet's data, when the caller passes a null pointer for the buffer
> argument, TO_P, and as the number of bytes to write into the inferior in
> handle_limited_packets_while_waiting and process_serial_event.
> 
> In handle_limited_packets_while_waiting we pass a null TO_P to
> decode_M_packet. The handle_limited_packets_while_waiting function is
> the loop that handles packets while gdbserver waits for the reply to a
> qSymbol or qRelocInsn query.  A malicious, or buggy, debug client could
> reply to a qSymbol query with an M packet that declares a huge length,
> for example 'M<addr>,ffffffff:0a0b0c0d', while only actually sending
> four bytes of data.  This would cause gdbserver to try to allocate a ~4
> GB buffer, at which point gdbserver would either die with an out of
> memory error, or slow the machine down through memory pressure.
> 
> If the declared length in the packet was longer than the provided data,
> but not enough to crash gdbserver then in decode_M_packet the return
> value from hex2bin, which says how many bytes were actually decoded, was
> ignored.  The remaining bytes within the allocated buffer would be
> uninitialised (containing whatever old content happened to be there),
> and this would then be written into the inferior.
> 
> In this commit, decode_M_packet now rejects any packet for which the
> declared length is not exactly half the number of bytes remaining in the
> packet after the header, or for which the remaining number of bytes is
> odd.  This is a stricter check than the equivalent for the 'X' packet,
> which only requires that the declared length be no greater than the
> remaining bytes; the difference is that the data in an M packet is
> always encoded as exactly two hex characters per byte, with no escaping,
> so the payload length of a well formed packet clearly indicates the
> actual data length.
> 
> Performing this check before the buffer allocation means the size of the
> allocation is now bounded by the size of the incoming packet, and, as
> the decoded length is now known to match the declared length, the
> uninitialized memory problem is closed too.  A payload that contains
> non-hex characters still causes hex2bin to throw an error, which causes
> gdbserver to return an error and reset the connection.  This solution is
> not ideal, and should probably be adjusted, but I don't plan to work on
> that in this series.
> 
> To go with the new checks, decode_M_packet now returns a bool to say if
> the packet was decoded successfully or not, and both callers have been
> updated so that the inferior memory is only written when the packet was
> accepted.  The function's comment has moved into remote-utils.h to sit
> beside the declaration.
> 
> The gdb.server/mx-packet-overflow.exp test is extended: the
> run_X_packet_tests proc has been renamed to run_MX_packet_tests and now
> also sends M packets.  As with the previous commit, the tests are run
> twice, once against the main packet loop, and once inside a qSymbol
> exchange, in order to reach handle_limited_packets_while_waiting, where
> the vulnerable code path lives.
> 
> The tests send valid M packets, then read the memory back to check that
> the correct bytes were written, as well as sending packets that declare
> too much or too little data, packets with an odd number of payload
> characters, and packets with a huge declared length, all of which should
> be rejected.
> ---
>  .../gdb.server/mx-packet-overflow.exp         | 69 ++++++++++++++-----
>  gdbserver/remote-utils.cc                     | 25 +++++--
>  gdbserver/remote-utils.h                      | 10 ++-
>  gdbserver/server.cc                           |  4 +-
>  4 files changed, 85 insertions(+), 23 deletions(-)
> 
> diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> index e41495b8f86..8080cdbb377 100644
> --- a/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> +++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp
> @@ -16,8 +16,8 @@
>  # along with this program.  If not, see <http://www.gnu.org/licenses/>.
>  
>  # Test that the 'm' and 'x' packets protect against buffer overflow,
> -# and that the 'X' packet rejects packets where the declared length
> -# doesn't match the amount of data actually sent.
> +# and that the 'M' and 'X' packets reject packets where the declared
> +# length doesn't match the amount of data actually sent.
>  
>  load_lib gdbserver-support.exp
>  
> @@ -177,13 +177,13 @@ proc run_mx_packet_tests {} {
>      }
>  }
>  
> -# Send 'X' packets to gdbserver with various different declared
> -# lengths and payloads, check that gdbserver handles the packets as we
> -# expect; rejecting those where the declared length doesn't match the
> -# amount of data actually sent.
> -proc run_X_packet_tests {} {
> -    # The 'X' packet tests write into the inferior.  Use BUFFER2 as the
> -    # write target.
> +# Send 'M' and 'X' packets to gdbserver with various different
> +# declared lengths and payloads, check that gdbserver handles the
> +# packets as we expect; rejecting those where the declared length
> +# doesn't match the amount of data actually sent.
> +proc run_MX_packet_tests {} {
> +    # The 'M' and 'X' packet tests write into the inferior.  Use
> +    # BUFFER2 as the write target.
>      set x_addr [get_hexadecimal_valueof buffer2 0x0 "get buffer2 address"]
>      set x_addr [string range $x_addr 2 end]
>  
> @@ -221,18 +221,55 @@ proc run_X_packet_tests {} {
>      # declared data, and run out of memory.
>      gdb_test "maint packet X${x_addr},ffffffff:a" "\r\nreceived: \"E01\"" \
>  	"test 'X' packet, huge declared length"
> +
> +    # Send a couple of valid 'M' packets, and, for each one, read the
> +    # memory back to check that the correct bytes were written.
> +    gdb_test "maint packet M${x_addr},4:0a0b0c0d" "\r\nreceived: \"OK\"" \
> +	"test 'M' packet, 4 declared, 4 sent"
> +    gdb_test "maint packet m${x_addr},4" "\r\nreceived: \"0a0b0c0d\"" \
> +	"check 'M' packet, 4 declared, wrote correct bytes"
> +
> +    gdb_test "maint packet M${x_addr},2:0e0f" "\r\nreceived: \"OK\"" \
> +	"test 'M' packet, 2 declared, 2 sent"
> +    gdb_test "maint packet m${x_addr},2" "\r\nreceived: \"0e0f\"" \
> +	"check 'M' packet, 2 declared, wrote correct bytes"
> +
> +    # Claim to be sending more data than is actually sent.
> +    gdb_test "maint packet M${x_addr},8:0a0b0c0d" "\r\nreceived: \"E01\"" \
> +	"test 'M' packet, 8 declared, 4 sent"
> +
> +    # Send fewer bytes than are declared.
> +    gdb_test "maint packet M${x_addr},2:0a" "\r\nreceived: \"E01\"" \
> +	"test 'M' packet, 2 declared, 1 sent"
> +
> +    # Send more bytes than are declared.
> +    gdb_test "maint packet M${x_addr},2:0a0b0c0d" \
> +	"\r\nreceived: \"E01\"" "test 'M' packet, 2 declared, 4 sent"
> +
> +    # Send partial bytes: half a byte too many, and half a byte too
> +    # few.
> +    gdb_test "maint packet M${x_addr},2:0a0b0" "\r\nreceived: \"E01\"" \
> +	"test 'M' packet, 2 declared, 2.5 sent"
> +    gdb_test "maint packet M${x_addr},2:0a0" "\r\nreceived: \"E01\"" \
> +	"test 'M' packet, 2 declared, 1.5 sent"
> +
> +    # Claim a huge payload is being sent.  Without some sanity checks
> +    # gdbserver would try to allocate a buffer to hold all the
> +    # declared data, and run out of memory.
> +    gdb_test "maint packet M${x_addr},ffffffff:0a0b0c0d" \
> +	"\r\nreceived: \"E01\"" "test 'M' packet, huge declared length"
>  }
>  
> -# Run the m/x packet tests, then the 'X' packet tests.
> +# Run the m/x packet tests, then the 'M' and 'X' packet tests.
>  run_mx_packet_tests
> -run_X_packet_tests
> +run_MX_packet_tests
>  
>  # Test within a qSymbol loop.  Send a 'qSymbol::' packet to gdbserver.
>  # It should either reply with 'qSymbol:<name>' or 'OK'.  If we get OK
>  # then gdbserver doesn't want to know any symbols from GDB, so we
>  # cannot get access to its inner packet processing loop.  If we get
> -# back a symbol request though, then we can send some m/x/X packets to
> -# test the inner packet processing loop.
> +# back a symbol request though, then we can send some m/x/M/X packets
> +# to test the inner packet processing loop.
>  set first_symbol_requested ""
>  gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
>      -re -wrap "\r\nreceived: \"OK\"" {
> @@ -245,12 +282,12 @@ gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
>      }
>  }
>  
> -# We got a symbol request from gdbserver; run the m/x and 'X' packet
> -# tests, then complete the qSymbol loop.
> +# We got a symbol request from gdbserver; run the m/x, 'M' and 'X'
> +# packet tests, then complete the qSymbol loop.
>  if { $first_symbol_requested ne "" } {
>      with_test_prefix "in qSymbol loop" {
>  	run_mx_packet_tests
> -	run_X_packet_tests
> +	run_MX_packet_tests
>      }
>  
>      set symbol_name $first_symbol_requested
> diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
> index 24f7c9ccdb6..faf2ed7e3f6 100644
> --- a/gdbserver/remote-utils.cc
> +++ b/gdbserver/remote-utils.cc
> @@ -1301,16 +1301,33 @@ decode_m_packet (const char *from, CORE_ADDR *mem_addr_ptr,
>    decode_m_packet_params (from, mem_addr_ptr, len_ptr, '\0');
>  }
>  
> -void
> +/* See remote-utils.h.  */
> +
> +bool
>  decode_M_packet (const char *from, CORE_ADDR *mem_addr_ptr,
>  		 unsigned int *len_ptr, unsigned char **to_p)
>  {
>    from = decode_m_packet_params (from, mem_addr_ptr, len_ptr, ':');
>  
> +  /* Each byte of data is encoded as 2 characters in the remaining packet
> +     length.  If there are an odd number of characters remaining, or if the
> +     declared length isn't half the remaining packet length, then this is
> +     not a valid M packet.  */
> +  size_t remaining_packet_len = strlen (from);
> +  if (remaining_packet_len % 2 != 0 || *len_ptr != remaining_packet_len / 2)
> +    return false;
> +
>    if (*to_p == NULL)
>      *to_p = (unsigned char *) xmalloc (*len_ptr);
>  
> -  hex2bin (from, *to_p, *len_ptr);
> +  int converted = hex2bin (from, *to_p, *len_ptr);
> +
> +  /* We already sanity checked *LEN_PTR above so we should always convert
> +     the expected number of bytes, or hex2bin will throw an exception if it
> +     encounters a non-hex character.  */
> +  gdb_assert (converted == *len_ptr);
> +
> +  return true;
>  }
>  
>  void
> @@ -1558,8 +1575,8 @@ handle_limited_packets_while_waiting ()
>  	  {
>  	    unsigned char *mem_buf = nullptr;
>  	    SCOPE_EXIT { free (mem_buf); };
> -	    decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
> -	    if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
> +	    if (decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf)
> +		&& target_write_memory (mem_addr, mem_buf, mem_len) == 0)
>  	      write_ok (cs.own_buf);
>  	    else
>  	      write_enn (cs.own_buf);
> diff --git a/gdbserver/remote-utils.h b/gdbserver/remote-utils.h
> index b710a8917f1..9b9e9437829 100644
> --- a/gdbserver/remote-utils.h
> +++ b/gdbserver/remote-utils.h
> @@ -55,8 +55,16 @@ const char *decode_m_packet_params (const char *from, CORE_ADDR *mem_addr_ptr,
>  				    const char end_marker);
>  void decode_m_packet (const char *from, CORE_ADDR * mem_addr_ptr,
>  		      unsigned int *len_ptr);
> -void decode_M_packet (const char *from, CORE_ADDR * mem_addr_ptr,
> +
> +/* Decode an 'M' packet from the buffer FROM.  Place the address into
> +   *MEM_ADDR_PTR and the length into *LEN_PTR.  If *TO_P is NULL then
> +   allocate a suitably sized buffer and *TO_P is updated.  Decode the
> +   data payload from the packet FROM into *TO_P.  Return true if
> +   everything succeeded, the M packet data will be in *TO_P.
> +   Otherwise return false and *TO_P will not have been touched.  */

Claude says:

  remote-utils.h:59-64 says that on failure "TO_P will not have been
  touched." But a non-hex digit makes hex2bin throw after the buffer has
  been allocated and assigned to *to_p (remote-utils.cc:1321). Both
  callers are safe: the qSymbol loop frees it with SCOPE_EXIT, and the
  main loop passes its own buffer. So only the promise is wrong. Fix:
  allocate into a local unique_xmalloc_ptr and hand it over only on
  success, or reword the comment. "Return true if everything succeeded,
  the M packet data will be in TO_P" also needs rephrasing.

> +bool decode_M_packet (const char *from, CORE_ADDR * mem_addr_ptr,
>  		      unsigned int *len_ptr, unsigned char **to_p);
> +
>  void decode_x_packet (const char *from, CORE_ADDR *mem_addr_ptr,
>  		      unsigned int *len_ptr);
>  int decode_X_packet (char *from, int packet_len, CORE_ADDR * mem_addr_ptr,
> diff --git a/gdbserver/server.cc b/gdbserver/server.cc
> index 7ad40e8e2b2..b62d80b08d4 100644
> --- a/gdbserver/server.cc
> +++ b/gdbserver/server.cc
> @@ -4963,8 +4963,8 @@ process_serial_event (void)
>        break;
>      case 'M':
>        require_running_or_break (cs.own_buf);
> -      decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
> -      if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
> +      if (decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf)
> +	  && gdb_write_memory (mem_addr, mem_buf, len) == 0)
>  	write_ok (cs.own_buf);
>        else
>  	write_enn (cs.own_buf);

Approved-By: Kevin Buettner <kevinb@redhat.com>


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling
  2026-11-25  5:55   ` Kevin Buettner
@ 2026-11-26 14:58     ` Andrew Burgess
  0 siblings, 0 replies; 14+ messages in thread
From: Andrew Burgess @ 2026-11-26 14:58 UTC (permalink / raw)
  To: Kevin Buettner, gdb-patches

Kevin Buettner <kevinb@redhat.com> writes:

> On 11/20/26 8:12 AM, Andrew Burgess wrote:
>> Both the look_up_one_symbol and relocate_instruction functions contain a
>> loop which handles a limited number of packets received from GDB.  This
>> commit merges these loops in order to reduce code duplication.  A
>> follow-up commit fixes a buffer overflow bug in this code.  The bug was
>> present at both locations, merging the code means only one site needs
>> fixing.  The new merged code is added in a new function
>> handle_limited_packets_while_waiting.
>> 
>> There is a potentially user-visible change in this commit though.
>> Previously look_up_one_symbol handled m, x, and v packets only, while
>> relocate_instruction handled m, M, x, and X packets.  By merging the
>> code both functions now handle the superset of these packets, m, M, x,
>> X, and v.  Both functions contained a comment saying something along the
>> lines of "we should really handle all packets here, but for now these
>> will do", I assume the current lists are based on what GDB happens to
>> send.  Supporting more packets in each case should not have any negative
>> consequences.  If it turns out that there are problems caused by
>> accepting this wider set of packets then we can add a packet filter
>> argument to handle_limited_packets_while_waiting, but I'd prefer to only
>> do this once we know there's a need for it.
>> 
>> As part of the commit, the result of sending the reply to a 'v' packet
>> is now error checked; previously, the look_up_one_symbol loop ignored a
>> failure to send this reply.
>> 
>> Additionally, while thinking about the 'v' packet handling, I wondered
>> what would happen if we received a vCont or vKill while we were within
>> look_up_one_symbol or relocate_instruction, and I suspect the outcome
>> would not be good.  If the inferior disappeared then these functions
>> might end up trying to operate on freed process state.  The 'v' packet
>> handling was added in commit:
>> 
>>   commit 28170b88cc8b40fdea2b065dafe6e1872a47ee4e
>>   Date:   Sat Mar 12 14:03:26 2016 +0100
>> 
>>     gdbserver: Handle 'v' packet while processing qSymbol.
>> 
>> The commit message talks about needing vFile support.  So, while making
>> this merge I have made the 'v' packet handling stricter.  We now drop
>> out of the handle_limited_packets_while_waiting loop for vCont, vAttach,
>> vRun, or vKill.  All other 'v' packets (including vFile) are handled as
>> before.
>> 
>> To the best of my knowledge, existing GDB does not send any packets
>> other than m, M, x, X, or v during these two exchanges.  If it did, the
>> old code would have rejected the packet as a malformed response, and the
>> resulting symbol lookup or instruction relocation failure would most
>> likely have shown up as a failing test somewhere.  There should
>> therefore be no visible changes after this commit.
>
> I ran the entire series through an AI patch review.  After reading
> through a very dense version of what has now been rewritten to be more
> comprehensible, it appeared to me that you were aware of these concerns.
> Nonetheless, you may wish to read what Claude thought of this patch:
>
>   I have one point, and I'd class it as a nit: four 'v' packets now get
>   no reply when they arrive during a qSymbol or qRelocInsn exchange.
>
>   As I read handle_limited_packets_while_waiting, anything other than
>   m, M, x, X, or a 'v' packet ends the loop and is handed back to the
>   caller, which expects it to be the qSymbol or qRelocInsn answer.
>   With this patch, vCont;, vAttach;, vRun;, and vKill; also end the
>   loop instead of being carried out.  I agree with the reason you give:
>   carrying out any of them in the middle of the exchange could resume,
>   kill, or replace the inferior, and leave the caller working on stale
>   or freed state.  Removing that risk fits well in this series.
>
>   The side effect I noticed is that neither caller recognises these
>   packets when they come back.  Both print "Malformed response ..."
>   and give up, and nothing ever replies to the packet itself.  In the
>   qSymbol case the main loop then sends "OK", so a client that sent
>   vCont would get "OK" instead of a stop reply, and the two sides end
>   up out of step.
>
>   When I compared this with master, I found:
>
>     - qSymbol path: this is new with the patch.  On master these
>       packets were carried out and answered (unsafely, as you point
>       out).
>
>     - qRelocInsn path: this was already the case.  On master that loop
>       ended on every 'v' packet and dropped it in the same way.
>
>     - More generally, any unexpected packet (a 'g', say) was already
>       handled like this in both loops.  The patch just puts these four
>       packets into that existing group.
>
>   I don't think this needs to hold up the series.  Your commit message
>   covers it: these packets now end the loop, existing GDB sends nothing
>   but m, M, x, X, or v during these exchanges, and you'd rather add
>   filtering "once we know there's a need for it".  GDB can't send vCont
>   in the middle of the exchange anyway, because it is busy servicing
>   the exchange.  What's left is a protocol mix-up with a client that
>   has already broken the protocol, not a memory-safety bug, so leaving
>   it seems a reasonable choice to me.
>
>   If you do want to tidy it up, one option would be to reply with an
>   error rather than ending the loop:
>
>             if (startswith (cs.own_buf, "vCont;")
>                 || startswith (cs.own_buf, "vAttach;")
>                 || startswith (cs.own_buf, "vRun;")
>                 || startswith (cs.own_buf, "vKill;"))
>               write_enn (cs.own_buf);
>             else
>               handle_v_requests (cs.own_buf, len, &new_len);
>
>   The putpkt at the bottom of the loop would send the E01 straight back
>   as the reply to the refused packet, and the loop would go on waiting
>   for the real qSymbol or qRelocInsn answer.  The client gets a clear
>   refusal, and clients already have to cope with E01 from these
>   packets.  The comment above the check would then say "refuse with an
>   error" rather than "don't service".  I'd be equally happy to see this
>   as a follow-up.

I thought about this over night and I agree with you that what I have
here is not ideal.  But nor do I think your proposal is the right way to
go.

My concern with you proposal is that we end up "stuck" in the secondary
packet loop.  I mean, if we want to return E01 to a vKill, then surely
we should return E01 for 'g', or any other packet.  So then we end with
a loop which will only exit by sending a valid qSymbol or qRelocInsn
packet.  A debug client that somehow gets out of sync would then never
break from the loop.

If we take qSymbol handling as an example, what I think we should do is
this: in server.cc, in handle_query, where we handle qSymbol, we
eventually reach these lines:

      if (current_thread != NULL)
	the_target->look_up_symbols ();

      strcpy (own_buf, "OK");
      return;

We should wrap these like this:

      try
        {
          if (current_thread != NULL)
            the_target->look_up_symbols ();
    
          strcpy (own_buf, "OK");
	}
      catch (const gdb_exception_error &exception)
	{
	  sprintf (cs.own_buf, "E.%s", exception.what ());
	}
      return;

Then, in handle_limited_packets_while_waiting, when we see a packet that
we're not expecting, instead of printing a warning, we should raise an
error.  This error would be caught above and we'd return an error packet
to GDB.

I don't want to get sidetracked fixing the above right now, so I don't
plan to address this issue in this commit.

I have however, made some changes to this commit:

  - I moved the checks for the error packet, and for the expected final
    packet, inside handle_limited_packets_while_waiting.

  - I've added a test that exercises the current behaviour.

I don't think either of these really change the core of this patch
though, so I have applied your approved-by tag.  Still, I'll wait a
while before pushing in case you wish to re-review this new version.

Thanks,
Andrew

---

commit 69d373278050dfe4f797aa5840d0cb6a484a05f8
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Tue Nov 17 13:57:07 2026 +0000

    gdbserver: merge look_up_one_symbol and relocate_instruction packet handling
    
    Both the look_up_one_symbol and relocate_instruction functions contain a
    loop which handles a limited number of packets received from GDB.  This
    commit merges these loops in order to reduce code duplication.  A
    follow-up commit fixes a buffer overflow bug in this code.  The bug was
    present at both locations, merging the code means only one site needs
    fixing.  The new merged code is added in a new function
    handle_limited_packets_while_waiting.
    
    There is a potentially user-visible change in this commit though.
    Previously look_up_one_symbol handled m, x, and v packets only, while
    relocate_instruction handled m, M, x, and X packets.  By merging the
    code both functions now handle the superset of these packets, m, M, x,
    X, and v.  Both functions contained a comment saying something along the
    lines of "we should really handle all packets here, but for now these
    will do", I assume the current lists are based on what GDB happens to
    send.  Supporting more packets in each case should not have any negative
    consequences.  If it turns out that there are problems caused by
    accepting this wider set of packets then we can add a packet filter
    argument to handle_limited_packets_while_waiting, but I'd prefer to only
    do this once we know there's a need for it.
    
    As part of the commit, the result of sending the reply to a 'v' packet
    is now error checked; previously, the look_up_one_symbol loop ignored a
    failure to send this reply.
    
    Additionally, while thinking about the 'v' packet handling, I wondered
    what would happen if we received a vCont or vKill while we were within
    look_up_one_symbol or relocate_instruction, and I suspect the outcome
    would not be good.  If the inferior disappeared then these functions
    might end up trying to operate on freed process state.  The 'v' packet
    handling was added in commit:
    
      commit 28170b88cc8b40fdea2b065dafe6e1872a47ee4e
      Date:   Sat Mar 12 14:03:26 2016 +0100
    
        gdbserver: Handle 'v' packet while processing qSymbol.
    
    The commit message talks about needing vFile support.  So, while making
    this merge I have made the 'v' packet handling stricter.  We now drop
    out of the handle_limited_packets_while_waiting loop for vCont, vAttach,
    vRun, or vKill.  All other 'v' packets (including vFile) are handled as
    before.
    
    To the best of my knowledge, existing GDB does not send any packets
    other than m, M, x, X, or v during these two exchanges.  If it did, the
    old code would have rejected the packet as a malformed response, and the
    resulting symbol lookup or instruction relocation failure would most
    likely have shown up as a failing test somewhere.  There should
    therefore be no visible changes after this commit.
    
    During review [1] it was asked why, for things like vKill, vCont, etc,
    we return from handle_limited_packets_while_waiting rather than sending
    back an error packet and remaining in the loop.  I think that replying
    with an error is the correct way to go, but I think we also need to
    return from handle_limited_packets_while_waiting.  If we don't return
    then there is a risk that a debug client will get stuck within the
    handle_limited_packets_while_waiting loop.  However, as the code is
    currently written, returning from handle_limited_packets_while_waiting
    means that gdbserver will send some other reply packet, either a
    subsequent qSymbol request, or the final OK.  If we send an error then
    we will end up sending two packets in response to a single packet from
    the debug client, and this will definitely cause the communication to
    get out of sync.
    
    I think the correct solution is to have
    handle_limited_packets_while_waiting throw an exception which is caught
    further up the stack.  For qSymbol this would be in handle_query where
    the initial qSymbol packet is being dealt with.  At this point gdbserver
    would catch the exception and return an error packet.  A similar fix
    would be needed for qRelocInsn.  I don't plan to make this change in
    this series which is focused on bugs in m, M, x, and X packet handling.
    
    [1] https://inbox.sourceware.org/gdb-patches/93333453-b4d8-40e2-a20f-adabf34d9690@redhat.com
    
    Approved-By: Kevin Buettner <kevinb@redhat.com>

diff --git a/gdb/testsuite/gdb.server/qSymbol-bad-reply.c b/gdb/testsuite/gdb.server/qSymbol-bad-reply.c
new file mode 100644
index 00000000000..dc3a92d8031
--- /dev/null
+++ b/gdb/testsuite/gdb.server/qSymbol-bad-reply.c
@@ -0,0 +1,63 @@
+/* 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 <stdlib.h>
+#include <assert.h>
+#include <limits.h>
+
+unsigned char *buffer = NULL;
+size_t buffer_length = 1024 * 1024 * 100;
+volatile int global_var = 0;
+
+/* Is C a byte that must be escaped in a reply from gdbserver to
+   GDB?  Return 1 if it is, otherwise, return 0.  */
+static int
+is_escapable_byte (unsigned char c)
+{
+  switch (c)
+    {
+    case 0x23:
+    case 0x24:
+    case 0x7d:
+    case 0x2a:
+      return 1;
+    default:
+      return 0;
+    }
+}
+
+int
+main ()
+{
+  buffer = malloc ( buffer_length );
+  assert (buffer != NULL);
+
+  unsigned char val = 0;
+  for (size_t i = 0; i < buffer_length; ++i)
+    {
+      buffer[i] = val;
+      do
+	{
+	  val = (val + 1) % UCHAR_MAX;
+	}
+      while (is_escapable_byte (val));
+    }
+
+  global_var = 42;	/* Break here.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.server/qSymbol-bad-reply.exp b/gdb/testsuite/gdb.server/qSymbol-bad-reply.exp
new file mode 100644
index 00000000000..7c3dce4d9be
--- /dev/null
+++ b/gdb/testsuite/gdb.server/qSymbol-bad-reply.exp
@@ -0,0 +1,142 @@
+# 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/>.
+
+# The qSymbol and qRelocInsn handling includes a mini packet loop which only
+# handles a small subset of packets while gdbserver and GDB are finalising the
+# qSymbol or qRelocInsn conversation.  The gdbserver code that handles this
+# packet subset is shared between qSymbol and qRelocInsn, but qSymbol is far
+# easier to trigger, so we use that here for testing,
+#
+# This test was added when the packet handling for qSymbol and qRelocInsn was
+# merged together into a single function, and this captures the current
+# behaviour at that time.  However, this behaviour is probably not the ideal
+# behaviour, and hopefully will be improved in the future.  When that happens
+# this test will need to be updated and/or rewritten.  That's OK.
+#
+# To understand what's wrong with the current code, consider the case where the
+# debug client first sends 'qSymbol::'.  gdbserver then replies with a qSymbol
+# packet asking for a particular symbol.  If the debug client at this point
+# sends back a 'g' packet, which is not one the qSymbol loop can handle, then
+# currently gdbserver breaks from the secondary packet handling loop and
+# returns.  gdbserver will then send the next qSymbol request.  This is bad
+# because qSymbol is not a documented reply to a 'g' packet.
+#
+# However, fixing this will require some bigger changes to how qSymbol and
+# qRelocInsn are handled, especially the error cases, within gdbserver.
+#
+# This test uses 'maint packet ...' to trigger a qSymbol packet exchange with
+# gdbserver.  Then sends unexpected packets to gdbserver and check how the
+# server handles them.
+
+load_lib gdbserver-support.exp
+
+require allow_gdbserver_tests
+
+standard_testfile
+
+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] && ![is_remote target] } {
+	set GDBFLAGS "$GDBFLAGS -ex \"set sysroot\""
+    }
+    if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+	return
+    }
+}
+
+# Make sure we're disconnected, in case we're testing with an
+# extended-remote board, therefore already connected.
+gdb_test "disconnect" ".*"
+
+# Start gdbserver and connect.
+set res [gdbserver_spawn ""]
+lassign $res gdbserver_protocol gdbserver_gdbport
+set res [gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport]
+if {![gdb_assert {$res == 0} "connect"]} {
+    return
+}
+
+# Get into position for the test.
+gdb_breakpoint [gdb_get_line_number "/* Break here.  */"]
+gdb_continue_to_breakpoint "test position"
+
+# Run BODY within a qSymbol packet processing loop.  Send 'qSymbol::' to
+# gdbserver .  It should either reply with 'qSymbol:<name>' or 'OK'.
+#
+# If we get OK then gdbserver doesn't want to know any symbols from GDB, so we
+# cannot get access to its inner packet processing loop.  Issue an UNSUPPORTED
+# and return without running BODY.
+#
+# If we get back a symbol request then we can execute BODY which will send some
+# unexpected packets to gdbserver.
+proc within_qSymbol_loop { body } {
+    set first_symbol_requested ""
+    gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" {
+	-re -wrap "\r\nreceived: \"OK\"" {
+	    unsupported "$gdb_test_name (no symbols requested)"
+	}
+
+	-re -wrap "\r\nreceived: \"qSymbol:(\[^\"\]+)\"" {
+	    set first_symbol_requested $expect_out(1,string)
+	    pass $gdb_test_name
+	}
+    }
+
+    # We got a symbol request from gdbserver then run BODY.  Each BODY will run
+    # until gdbserver exits the qSymbol packet processing loop.
+    if { $first_symbol_requested ne "" } {
+	with_test_prefix "in qSymbol loop" {
+	    transparent_uplevel $body
+	}
+    }
+}
+
+# After gdbserver sends a qSymbol request, send back an unexpected packet.  See
+# the comments at the top of this file for the limitations of this test.
+#
+# Place a limit of 100 symbol requests.  This is more than gdbserver currently
+# asks for on GNU/Linux, but should stop thi test getting stuck in a loop if
+# something unexpected goes wrong.
+foreach_with_prefix packet { E01 g vKill; } {
+    within_qSymbol_loop {
+	set limit 100
+	gdb_test_multiple "maint packet $packet" "reply with error" {
+	    -i $server_spawn_id
+	    -re "gdbserver: unexpected \[^\r\n\]+\r\n" {
+		exp_continue
+	    }
+
+	    -i $gdb_spawn_id
+	    -re -wrap "received: \"qSymbol:\[^\r\n\]+\"" {
+		incr limit -1
+		if { $limit == 0 } {
+		    fail $gdb_test_name
+		} else {
+		    send_gdb "maint packet $packet\n"
+		    exp_continue
+		}
+	    }
+
+	    -i $gdb_spawn_id
+	    -re -wrap "received: \"OK\"" {
+		pass $gdb_test_name
+	    }
+	}
+    }
+}
diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc
index 8192e4577f2..abb1789eb76 100644
--- a/gdbserver/remote-utils.cc
+++ b/gdbserver/remote-utils.cc
@@ -1417,6 +1417,199 @@ clear_symbol_cache (struct sym_cache **symcache_p)
   *symcache_p = NULL;
 }
 
+/* In some cases a packet from the debug client triggers a prolonged packet
+   exchange between gdbserver and the client.  For example, gdbserver can
+   send a qRelocInsn request in response to some packets.  When the debug
+   client receives the qRelocInsn request it will perform a series of memory
+   accesses using x, X, m, or M packets before finally sending its own
+   qRelocInsn reply.
+
+   Similarly, the debug client can send 'qSymbol::'; gdbserver will then
+   request symbol values, which the debug client provides with another
+   qSymbol packet.  Before sending the final qSymbol packet, the debug
+   client might access memory or send 'v' packets (for vFile transfers).
+
+   This function takes care of handling the limited set of packets that
+   might arrive while waiting for the final response packet.
+
+   EXPECTED_PACKET_PREFIX is the first part of the final response packet
+   that we are waiting for.  This code fetches packets from the debug
+   client and then:
+
+   + If it is one of the packets this function handles, the packet is
+     handled, and then loops around to fetch and handle another packet.
+
+   + If the packet is empty, is an error (starts with 'E'), or is not one
+     this function can handle and doesn't start with EXPECTED_PACKET_PREFIX,
+     then this function returns false, and the unexpected, unhandled packet
+     is left in the client_state's OWN_BUF.
+
+   + If the packet is not one this function can handle and does start with
+     EXPECTED_PACKET_PREFIX, then this is the final packet we were waiting
+     for.  This function returns true and the unhandled final packet is left
+     in the client_state's OWN_BUF.
+
+   If this function returns with either true or false, then no response will
+   have been sent to the debug client.  Returning from this function will
+   result in a reply being sent, so if we send a reply before returning then
+   this would result in multiple reply packets.  The debug client is not
+   expecting this and will get out of sync.
+
+   We ought to handle pretty much any packet at this point while we wait for
+   the final response, but that requires re-entering the main loop.  For
+   now, this is an adequate approximation.  */
+
+static bool
+handle_limited_packets_while_waiting (const char *expected_packet_prefix)
+{
+  client_state &cs = get_client_state ();
+
+  bool leave_packet_handling_loop = false;
+  while (!leave_packet_handling_loop)
+    {
+      int len = getpkt (cs.own_buf);
+      if (len < 0)
+	return false;
+
+      CORE_ADDR mem_addr;
+      unsigned char *mem_buf = nullptr;
+      unsigned int mem_len;
+      int new_len = -1;
+
+      switch (cs.own_buf[0])
+	{
+	case 'm':
+	  {
+	    decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
+	    mem_buf = (unsigned char *) xmalloc (mem_len);
+	    if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
+	      bin2hex (mem_buf, cs.own_buf, mem_len);
+	    else
+	      write_enn (cs.own_buf);
+	  }
+	  break;
+	case 'x':
+	  {
+	    decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len);
+	    mem_buf = (unsigned char *) xmalloc (mem_len);
+	    if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
+	      {
+		gdb_byte *buffer = (gdb_byte *) cs.own_buf;
+		*buffer++ = 'b';
+
+		int out_len_units;
+		new_len = remote_escape_output (mem_buf, mem_len, 1,
+						buffer,
+						&out_len_units,
+						PBUFSIZ);
+		new_len++; /* For the 'b' marker.  */
+
+		if (out_len_units != mem_len)
+		  {
+		    write_enn (cs.own_buf);
+		    new_len = -1;
+		  }
+		else
+		  suppress_next_putpkt_log ();
+	      }
+	    else
+	      write_enn (cs.own_buf);
+	  }
+	  break;
+	case 'X':
+	  {
+	    if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr,
+				 &mem_len, &mem_buf) < 0
+		|| target_write_memory (mem_addr, mem_buf, mem_len) != 0)
+	      write_enn (cs.own_buf);
+	    else
+	      write_ok (cs.own_buf);
+	  }
+	  break;
+	case 'M':
+	  {
+	    decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
+	    if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
+	      write_ok (cs.own_buf);
+	    else
+	      write_enn (cs.own_buf);
+	  }
+	  break;
+	case 'v':
+	  /* Don't service packets that change which process we are
+	     debugging, or its execution state, while we are in the middle
+	     of another operation.  Handling these here could leave the
+	     caller operating on freed, or stale, state.  Any other 'v'
+	     packets, e.g. vFile, are fine to handle.  */
+	  if (startswith (cs.own_buf, "vCont;")
+	      || startswith (cs.own_buf, "vAttach;")
+	      || startswith (cs.own_buf, "vRun;")
+	      || startswith (cs.own_buf, "vKill;"))
+	    leave_packet_handling_loop = true;
+	  else
+	    handle_v_requests (cs.own_buf, len, &new_len);
+	  break;
+	default:
+	  leave_packet_handling_loop = true;
+	  break;
+	}
+      free (mem_buf);
+
+      if (!leave_packet_handling_loop)
+	{
+	  int res = ((new_len == -1)
+		     ? putpkt (cs.own_buf)
+		     : putpkt_binary (cs.own_buf, new_len));
+	  if (res < 0)
+	    return false;
+	}
+    }
+
+  if (cs.own_buf[0] == '\0')
+    {
+      warning (_("an unexpected empty packet occurred while waiting for '%s'"),
+	       expected_packet_prefix);
+      return false;
+    }
+  else if (cs.own_buf[0] == 'E')
+    {
+      /* Don't describe an error as unexpected.  For both qSymbol and
+	 qRelocInsn, if the debug client needs to read inferior memory to
+	 service the request then the read could fail and the debug client
+	 might return an error.  There's still not much we can do beyond
+	 returning false here; we cannot continue handling the qSymbol or
+	 qRelocInsn, but the warning message should not indicate that this
+	 is necessarily a bug.  */
+      warning (_("an error occurred while waiting for '%s': %s"),
+	       expected_packet_prefix, cs.own_buf);
+      return false;
+    }
+  else if (!startswith (cs.own_buf, expected_packet_prefix))
+    {
+      /* We got an unexpected packet from the debug client.  Do not send an
+	 error packet back at this point.  If we send back an error at this
+	 point then we also need to fetch another packet from the debug
+	 client, which means we need another go around this packet handling
+	 loop again.  There is risk that a debug client could get stuck in
+	 this loop.
+
+	 By instead just returning false we let our caller know that
+	 something went wrong, they can choose to handle this how they want.
+	 But at least gdbserver is making progress towards returning to the
+	 main packet handling loop.
+
+	 In the future it might be better if we threw an exception at this
+	 point, but that will require a suitable catch in our call stack.
+	 If the exception is allowed to propagate all the way back to
+	 captured_main then this will reset the connection.  */
+      warning (_("unexpected packet while waiting for '%s', ignoring: %s"),
+	       expected_packet_prefix, cs.own_buf);
+      return false;
+    }
+
+  return true;
+}
+
 /* Get the address of NAME, and return it in ADDRP if found.  if
    MAY_ASK_GDB is false, assume symbol cache misses are failures.
    Returns 1 if the symbol is found, 0 if it is not, -1 on error.  */
@@ -1426,7 +1619,6 @@ look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
 {
   client_state &cs = get_client_state ();
   char *p, *q;
-  int len;
   struct sym_cache *sym;
   struct process_info *proc;
 
@@ -1452,88 +1644,10 @@ look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
   if (putpkt (cs.own_buf) < 0)
     return -1;
 
-  len = getpkt (cs.own_buf);
-  if (len < 0)
+  if (!handle_limited_packets_while_waiting ("qSymbol:"))
     return -1;
 
-  /* We ought to handle pretty much any packet at this point while we
-     wait for the qSymbol "response".  That requires re-entering the
-     main loop.  For now, this is an adequate approximation; allow
-     GDB to read from memory and handle 'v' packets (for vFile transfers)
-     while it figures out the address of the symbol.  */
-  while (1)
-    {
-      CORE_ADDR mem_addr;
-      unsigned char *mem_buf;
-      unsigned int mem_len;
-      int new_len = -1;
-
-      if (cs.own_buf[0] == 'm')
-	{
-	  decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    bin2hex (mem_buf, cs.own_buf, mem_len);
-	  else
-	    write_enn (cs.own_buf);
-	  free (mem_buf);
-	  if (putpkt (cs.own_buf) < 0)
-	    return -1;
-	}
-      else if (cs.own_buf[0] == 'x')
-	{
-	  decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    {
-	      gdb_byte *buffer = (gdb_byte *) cs.own_buf;
-	      *buffer++ = 'b';
-
-	      int out_len_units;
-	      new_len = remote_escape_output (mem_buf, mem_len, 1,
-					      buffer,
-					      &out_len_units,
-					      PBUFSIZ);
-	      new_len++; /* For the 'b' marker.  */
-
-	      if (out_len_units != mem_len)
-		{
-		  write_enn (cs.own_buf);
-		  new_len = -1;
-		}
-	      else
-		suppress_next_putpkt_log ();
-	    }
-	  else
-	    write_enn (cs.own_buf);
-
-	  free (mem_buf);
-	  int res = ((new_len == -1)
-		     ? putpkt (cs.own_buf)
-		     : putpkt_binary (cs.own_buf, new_len));
-	  if (res < 0)
-	    return -1;
-	}
-      else if (cs.own_buf[0] == 'v')
-	{
-	  handle_v_requests (cs.own_buf, len, &new_len);
-	  if (new_len != -1)
-	    putpkt_binary (cs.own_buf, new_len);
-	  else
-	    putpkt (cs.own_buf);
-	}
-      else
-	break;
-      len = getpkt (cs.own_buf);
-      if (len < 0)
-	return -1;
-    }
-
-  if (!startswith (cs.own_buf, "qSymbol:"))
-    {
-      warning (_("Malformed response to qSymbol, ignoring: %s"), cs.own_buf);
-      return -1;
-    }
+  gdb_assert (startswith (cs.own_buf, "qSymbol:"));
 
   p = cs.own_buf + strlen ("qSymbol:");
   q = p;
@@ -1572,7 +1686,6 @@ int
 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
 {
   client_state &cs = get_client_state ();
-  int len;
   ULONGEST written = 0;
 
   /* Send the request.  */
@@ -1581,100 +1694,10 @@ relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
   if (putpkt (cs.own_buf) < 0)
     return -1;
 
-  len = getpkt (cs.own_buf);
-  if (len < 0)
+  if (!handle_limited_packets_while_waiting ("qRelocInsn:"))
     return -1;
 
-  /* We ought to handle pretty much any packet at this point while we
-     wait for the qRelocInsn "response".  That requires re-entering
-     the main loop.  For now, this is an adequate approximation; allow
-     GDB to access memory.  */
-  while (cs.own_buf[0] == 'm' || cs.own_buf[0] == 'M'
-	 || cs.own_buf[0] == 'X' || cs.own_buf[0] == 'x')
-    {
-      CORE_ADDR mem_addr;
-      unsigned char *mem_buf = NULL;
-      unsigned int mem_len;
-      int new_len = -1;
-
-      if (cs.own_buf[0] == 'm')
-	{
-	  decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    bin2hex (mem_buf, cs.own_buf, mem_len);
-	  else
-	    write_enn (cs.own_buf);
-	}
-      else if (cs.own_buf[0] == 'x')
-	{
-	  decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len);
-	  mem_buf = (unsigned char *) xmalloc (mem_len);
-	  if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
-	    {
-	      gdb_byte *buffer = (gdb_byte *) cs.own_buf;
-	      *buffer++ = 'b';
-
-	      int out_len_units;
-	      new_len = remote_escape_output (mem_buf, mem_len, 1,
-					      buffer,
-					      &out_len_units,
-					      PBUFSIZ);
-	      new_len++; /* For the 'b' marker.  */
-
-	      if (out_len_units != mem_len)
-		{
-		  write_enn (cs.own_buf);
-		  new_len = -1;
-		}
-	      else
-		suppress_next_putpkt_log ();
-	    }
-	  else
-	    write_enn (cs.own_buf);
-	}
-      else if (cs.own_buf[0] == 'X')
-	{
-	  if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr,
-			       &mem_len, &mem_buf) < 0
-	      || target_write_memory (mem_addr, mem_buf, mem_len) != 0)
-	    write_enn (cs.own_buf);
-	  else
-	    write_ok (cs.own_buf);
-	}
-      else
-	{
-	  decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
-	  if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
-	    write_ok (cs.own_buf);
-	  else
-	    write_enn (cs.own_buf);
-	}
-      free (mem_buf);
-
-      int res = ((new_len == -1)
-		 ? putpkt (cs.own_buf)
-		 : putpkt_binary (cs.own_buf, new_len));
-      if (res < 0)
-	return -1;
-      len = getpkt (cs.own_buf);
-      if (len < 0)
-	return -1;
-    }
-
-  if (cs.own_buf[0] == 'E')
-    {
-      warning (_("An error occurred while relocating an instruction: %s"),
-	       cs.own_buf);
-      return -1;
-    }
-
-  if (!startswith (cs.own_buf, "qRelocInsn:"))
-    {
-      warning (_("Malformed response to qRelocInsn, ignoring: %s"),
-	       cs.own_buf);
-      return -1;
-    }
+  gdb_assert (startswith (cs.own_buf, "qRelocInsn:"));
 
   unpack_varlen_hex (cs.own_buf + strlen ("qRelocInsn:"), &written);
 


^ permalink raw reply	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2026-11-26 14:59 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-20 15:12 [PATCH 0/5] gdbserver: fix memory bugs in x, X, m, and M packet handling Andrew Burgess
2026-11-20 15:12 ` [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets Andrew Burgess
2026-11-20 15:37   ` Eli Zaretskii
2026-11-23  5:26   ` Kevin Buettner
2026-11-20 15:12 ` [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling Andrew Burgess
2026-11-25  5:55   ` Kevin Buettner
2026-11-26 14:58     ` Andrew Burgess
2026-11-20 15:12 ` [PATCH 3/5] gdbserver: fix buffer overflow in more m/x " Andrew Burgess
2026-11-25  7:24   ` Kevin Buettner
2026-11-20 15:12 ` [PATCH 4/5] gdbserver: reject X packets with an invalid declared length Andrew Burgess
2026-11-25  7:48   ` Kevin Buettner
2026-11-25  7:48   ` Kevin Buettner
2026-11-20 15:12 ` [PATCH 5/5] gdbserver: reject M " Andrew Burgess
2026-11-25  8:03   ` Kevin Buettner

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox