Mirror of the gdb-patches mailing list
 help / color / mirror / Atom feed
* [PATCH 0/2] gdbserver: fix potential buffer overflow in qTStatus
@ 2026-11-23 22:46 Andrew Burgess
  2026-11-23 22:46 ` [PATCH 1/2] gdbserver: move local variable declarations inline in cmd_qtstatus Andrew Burgess
  2026-11-23 22:46 ` [PATCH 2/2] gdbserver: fix buffer overflow " Andrew Burgess
  0 siblings, 2 replies; 3+ messages in thread
From: Andrew Burgess @ 2026-11-23 22:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Patch #2 fixes a potential buffer overflow in gdbserver's handling of the
qTStatus packet.

Patch #1 is an initial refactor, just bringing the cmd_qtstatus function more
inline with GDB's current coding standards.

Thanks,
Andrew

---

Andrew Burgess (2):
  gdbserver: move local variable declarations inline in cmd_qtstatus
  gdbserver: fix buffer overflow in cmd_qtstatus

 .../gdb.server/overfull-qtstatus-packet.exp   | 177 ++++++++++++++++++
 gdbserver/tracepoint.cc                       |  83 ++++----
 2 files changed, 220 insertions(+), 40 deletions(-)
 create mode 100644 gdb/testsuite/gdb.server/overfull-qtstatus-packet.exp


base-commit: 66be8cee927b2caeefdb9aa8bff753793a976865
-- 
2.56.1


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

* [PATCH 1/2] gdbserver: move local variable declarations inline in cmd_qtstatus
  2026-11-23 22:46 [PATCH 0/2] gdbserver: fix potential buffer overflow in qTStatus Andrew Burgess
@ 2026-11-23 22:46 ` Andrew Burgess
  2026-11-23 22:46 ` [PATCH 2/2] gdbserver: fix buffer overflow " Andrew Burgess
  1 sibling, 0 replies; 3+ messages in thread
From: Andrew Burgess @ 2026-11-23 22:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Refactor cmd_qtstatus (gdbserver/tracepoint.cc) moving the local
variable declarations inline.  This is just a refactor, there should be
no user visible changes after this commit.
---
 gdbserver/tracepoint.cc | 29 ++++++++++-------------------
 1 file changed, 10 insertions(+), 19 deletions(-)

diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 6f657257ee8..bfe1ecc7db6 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -3375,27 +3375,22 @@ cmd_qtframe (char *own_buf)
 static void
 cmd_qtstatus (char *packet)
 {
-  char *stop_reason_rsp = NULL;
-  char *buf1, *buf2, *buf3;
-  const char *str;
-  int slen;
-
   /* Translate the plain text of the notes back into hex for
      transmission.  */
 
-  str = (tracing_user_name ? tracing_user_name : "");
-  slen = strlen (str);
-  buf1 = (char *) alloca (slen * 2 + 1);
+  const char *str = (tracing_user_name ? tracing_user_name : "");
+  int slen = strlen (str);
+  char *buf1 = (char *) alloca (slen * 2 + 1);
   bin2hex ((gdb_byte *) str, buf1, slen);
 
   str = (tracing_notes ? tracing_notes : "");
   slen = strlen (str);
-  buf2 = (char *) alloca (slen * 2 + 1);
+  char *buf2 = (char *) alloca (slen * 2 + 1);
   bin2hex ((gdb_byte *) str, buf2, slen);
 
   str = (tracing_stop_note ? tracing_stop_note : "");
   slen = strlen (str);
-  buf3 = (char *) alloca (slen * 2 + 1);
+  char *buf3 = (char *) alloca (slen * 2 + 1);
   bin2hex ((gdb_byte *) str, buf3, slen);
 
   trace_debug ("Returning trace status as %d, stop reason %s",
@@ -3408,22 +3403,18 @@ cmd_qtstatus (char *packet)
       upload_fast_traceframes ();
 
       target_unpause_all (true);
-   }
+    }
 
-  stop_reason_rsp = (char *) tracing_stop_reason;
+  char *stop_reason_rsp = (char *) tracing_stop_reason;
 
   /* The user visible error string in terror needs to be hex encoded.
      We leave it as plain string in `tracing_stop_reason' to ease
      debugging.  */
   if (startswith (stop_reason_rsp, "terror:"))
     {
-      const char *result_name;
-      int hexstr_len;
-      char *p;
-
-      result_name = stop_reason_rsp + strlen ("terror:");
-      hexstr_len = strlen (result_name) * 2;
-      p = stop_reason_rsp
+      const char *result_name = stop_reason_rsp + strlen ("terror:");
+      size_t hexstr_len = strlen (result_name) * 2;
+      char *p = stop_reason_rsp
 	= (char *) alloca (strlen ("terror:") + hexstr_len + 1);
       strcpy (p, "terror:");
       p += strlen (p);
-- 
2.56.1


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

* [PATCH 2/2] gdbserver: fix buffer overflow in cmd_qtstatus
  2026-11-23 22:46 [PATCH 0/2] gdbserver: fix potential buffer overflow in qTStatus Andrew Burgess
  2026-11-23 22:46 ` [PATCH 1/2] gdbserver: move local variable declarations inline in cmd_qtstatus Andrew Burgess
@ 2026-11-23 22:46 ` Andrew Burgess
  1 sibling, 0 replies; 3+ messages in thread
From: Andrew Burgess @ 2026-11-23 22:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In cmd_qtstatus (gdbserver/tracepoint.cc), the response packet was built
using sprintf into a buffer of PBUFSIZ + 1 (131105) bytes.  See
gdbserver/server.h for both the definition of PBUFSIZ and for the
client_state constructor, where the buffer is allocated.  The response
packet contains several different fields, but two that are of interest
for this commit are tracing_user_name and tracing_notes, which are
placed into the response packet as hex-encoded string.  Due to the use
of sprintf, if the combined response packet exceeds PBUFSIZ + 1 bytes
then sprintf overflows the packet buffer resulting in undefined
behaviour.

The tracing_user_name and tracing_notes fields which are mentioned above
can be set to arbitrary length string by the user using QTNotes packets.
Actually the length of the hex-encoded data for each field is limited to
just under PBUFSIZ bytes.  A QTNotes packet contains the packet name,
the field being set ("user" or "notes") then the hex-encoded payload.
An incoming packet is limited to PBUFSIZ + 1 bytes.

What this means is that if both the tracing_user_name and tracing_notes
fields are set to large strings, then the combined qTStatus response
packet can overflow the output buffer, triggering undefined behaviour.

Fix this by changing cmd_qtstatus to take a gdb::span<char> rather than
a bare char *, so the buffer size is carried along with it.  Replace
sprintf with snprintf using packet.size () as the bound.  If the
formatted output would exceed the buffer (the snprintf return value is
negative or >= packet.size ()), call write_enn to return an error
response to GDB rather than sending a truncated or corrupt packet that
GDB would likely misparse.

Currently I am creating the gdb::span<char> in handle_tracepoint_query,
this might not seem much better than just hard-coding PBUFSIZ into
cmd_qtstatus.  However, I think it is.  Long term, I think most (maybe
all of the functions that take a packet buffer pointer should be updated
to take gdb::span<char>.  But if I try to add the gdb::span throughout
the whole call stack in this commit then the commit will get very large.

The change as presented here fixes the existing bug, and is just a tiny
part of an eventual piece of work to start using gdb::span more in
gdbserver.

A new test, gdb/testsuite/gdb.server/overfull-qtstatus-packet.exp,
checks that small payloads produce valid qTStatus replies, that a
payload large enough to overflow the buffer causes an E01 response,
and that reducing the payload size again restores normal behaviour.
---
 .../gdb.server/overfull-qtstatus-packet.exp   | 177 ++++++++++++++++++
 gdbserver/tracepoint.cc                       |  52 +++--
 2 files changed, 209 insertions(+), 20 deletions(-)
 create mode 100644 gdb/testsuite/gdb.server/overfull-qtstatus-packet.exp

diff --git a/gdb/testsuite/gdb.server/overfull-qtstatus-packet.exp b/gdb/testsuite/gdb.server/overfull-qtstatus-packet.exp
new file mode 100644
index 00000000000..0dc436f8392
--- /dev/null
+++ b/gdb/testsuite/gdb.server/overfull-qtstatus-packet.exp
@@ -0,0 +1,177 @@
+# 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 what happens when we cause the qTStatus packet to grow so large
+# it can no longer fit in the gdbserver allocated buffer.  We expect
+# that gdbserver should start sending back errors.
+
+load_lib gdbserver-support.exp
+
+require allow_gdbserver_tests
+
+# Due to environment setting.
+require {!is_remote host}
+
+standard_testfile normal.c
+
+if {[build_executable "failed to build" $testfile $srcfile]} {
+    return
+}
+
+# Start GDB and gdbserver ready for the test.  Return false if
+# anything goes wrong, otherwise, return true.
+proc start_gdbserver_for_test {} {
+    save_vars { env(ASAN_OPTIONS) env(TSAN_OPTIONS) } {
+	# The large QTNotes packets sent in this test trigger
+	# ASAN/TSAN errors which are disabled by these settings.
+	append_environment ASAN_OPTIONS allocator_may_return_null 1
+	append_environment TSAN_OPTIONS allocator_may_return_null 1
+
+	clean_restart $::testfile
+
+	# 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 false
+	}
+
+	return true
+    }
+}
+
+# Disassemble the main function and return a list containing the addresses
+# of each instruction.  The returned addresses have the leading 0x and any
+# leading 0s stripped off.
+proc disassemble_main_for_addresses {} {
+    # Disassemble main and find an address at which we could place a
+    # tracepoint.
+    set addresses {}
+    gdb_test_multiple "disassemble main" "" -lbl {
+	-re "\r\n\\s+0x0*(\[0-9a-f\]+)\\s+\[^\r\n\]+(?=\r\n)" {
+	    set addr $expect_out(1,string)
+	    lappend addresses $addr
+	    exp_continue
+	}
+
+	-re "^\r\n$::gdb_prompt $" {
+	    gdb_assert {[llength $addresses] > 0} \
+		"found instruction addresses"
+	}
+    }
+
+    return $addresses
+}
+
+# Test for overfull qTStatus packet.
+proc_with_prefix test_qtstatus {} {
+    if {![start_gdbserver_for_test]} {
+	return
+    }
+
+    # Disassemble main and find an address at which we could place a
+    # tracepoint.
+    set addresses [disassemble_main_for_addresses]
+
+    # We need at least 1 address in main for this test.
+    if {[llength $addresses] < 1} {
+	unsupported "not enough instruction addresses in main"
+	gdbserver_exit false
+	return
+    }
+
+    # Record the address we'll use in this test.
+    set addr [lindex $addresses 0]
+
+    # Create a tracepoint at ADDR.  Do this manually as the rest of this
+    # test also does manual packet manipulation.
+    gdb_test_multiple "maint packet QTDP:1:$addr:D:1:1" "create tracepoint" {
+	-re -wrap "\r\nreceived: \"OK\"" {
+	    pass $gdb_test_name
+	}
+
+	-re -wrap "" {
+	    unsupported $gdb_test_name
+	    gdbserver_exit false
+	    return
+	}
+    }
+
+    # Set 'user' and 'notes' text using separate QTNotes packets.  The
+    # payload in each case is a hex-encoded data block of
+    # PAYLOAD_SIZE.  As the payload is hex-encoded PAYLOAD_SIZE must
+    # be even for the payload to be valid.
+    #
+    # Once set, use qTStatus to read the fields back.  The reply will
+    # include both 'user' and 'notes' text.
+    #
+    # However, the maximum buffer size within gdbserver is ~131104
+    # bytes, so when the payload size is 66000 bytes, the two fields
+    # combined (plus the other qTStatus fields) will exceed the
+    # maximum packet size.  In this case qTStatus should return an
+    # error.
+    #
+    # We finish with a small size to show that the error state isn't
+    # "locked in", reduce the user/notes fields sizes and the qTStatus
+    # will start working again.
+    foreach_with_prefix payload_size { 0 2 100 1000 10000 50000 66000 4 } {
+	set user_payload [string repeat a $payload_size]
+	set notes_payload [string repeat b $payload_size]
+
+	gdb_test "maint packet QTNotes:user:$user_payload;" "\r\nreceived: \"OK\"" \
+	    "set 'user' text via QTNotes"
+	gdb_test "maint packet QTNotes:notes:$notes_payload;" "\r\nreceived: \"OK\"" \
+	    "set 'notes' text via QTNotes"
+
+	if { $payload_size > 65000 } {
+	    # Send qTStatus.  In this case the payload is such that the
+	    # reply exceeds the maximum packet size, we should get back an
+	    # error.
+	    gdb_test "maint packet qTStatus" "\r\nreceived: \"E01\"" \
+		"over sized qTStatus reply becomes an error"
+	} else {
+	    # Send qTStatus.  In this case the payload is small enough that
+	    # we should get back a valid reply.
+	    gdb_test_multiple "maint packet qTStatus" \
+		"got expected qTStatus reply" {
+		-re -wrap "\r\nreceived: \"T0;.*username:(a*);notes:(b*):\"" {
+		    set user_string $expect_out(1,string)
+		    set notes_string $expect_out(2,string)
+
+		    gdb_assert { $user_string eq $user_payload \
+				     && $notes_string eq $notes_payload } \
+			$gdb_test_name
+		}
+	    }
+	}
+    }
+
+    gdbserver_exit false
+}
+
+# This test receives some large packets from the remote, which are then
+# displayed by GDB and processed by expect.  Doing this character at a time
+# make this test quite slow.  Increase the timeout to compensate.
+with_read1_timeout_factor 25 {
+    test_qtstatus
+}
diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index bfe1ecc7db6..2f5b52ea3eb 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -3372,8 +3372,10 @@ cmd_qtframe (char *own_buf)
     sprintf (own_buf, "F-1");
 }
 
+/* Respond to a qTStatus packet, writing the result into PACKET.  */
+
 static void
-cmd_qtstatus (char *packet)
+cmd_qtstatus (gdb::span<char> packet)
 {
   /* Translate the plain text of the notes back into hex for
      transmission.  */
@@ -3429,24 +3431,31 @@ cmd_qtstatus (char *packet)
       strcat (stop_reason_rsp, buf3);
     }
 
-  sprintf (packet,
-	   "T%d;"
-	   "%s:%x;"
-	   "tframes:%x;tcreated:%x;"
-	   "tfree:%x;tsize:%s;"
-	   "circular:%d;"
-	   "disconn:%d;"
-	   "starttime:%s;stoptime:%s;"
-	   "username:%s;notes:%s:",
-	   tracing ? 1 : 0,
-	   stop_reason_rsp, tracing_stop_tpnum,
-	   traceframe_count, traceframes_created,
-	   free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
-	   circular_trace_buffer,
-	   disconnected_tracing,
-	   phex_nz (tracing_start_time),
-	   phex_nz (tracing_stop_time),
-	   buf1, buf2);
+  int res = snprintf (packet.data (), packet.size (),
+		      "T%d;"
+		      "%s:%x;"
+		      "tframes:%x;tcreated:%x;"
+		      "tfree:%x;tsize:%s;"
+		      "circular:%d;"
+		      "disconn:%d;"
+		      "starttime:%s;stoptime:%s;"
+		      "username:%s;notes:%s:",
+		      tracing ? 1 : 0,
+		      stop_reason_rsp, tracing_stop_tpnum,
+		      traceframe_count, traceframes_created,
+		      free_space (), phex_nz (trace_buffer_hi
+					      - trace_buffer_lo, 0),
+		      circular_trace_buffer,
+		      disconnected_tracing,
+		      phex_nz (tracing_start_time),
+		      phex_nz (tracing_stop_time),
+		      buf1, buf2);
+
+  /* Don't send back a partial packet.  We cannot know which field in the
+     reply was truncated, so a partial reply cannot be safely interpreted by
+     the debug client.  */
+  if (res < 0 || res >= packet.size ())
+    write_enn (packet.data ());
 }
 
 static void
@@ -3943,7 +3952,10 @@ handle_tracepoint_query (char *packet)
 {
   if (streq ("qTStatus", packet))
     {
-      cmd_qtstatus (packet);
+      /* This assumes the size of PACKET, e.g. PACKET is client_state::own_buf.
+	 This was true at the time this comment was added.  A better solution
+	 would be to pass a gdb::span<char> into this function.  */
+      cmd_qtstatus ({packet, PBUFSIZ + 1});
       return 1;
     }
   else if (startswith (packet, "qTP:"))
-- 
2.56.1


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

end of thread, other threads:[~2026-11-23 22:47 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-23 22:46 [PATCH 0/2] gdbserver: fix potential buffer overflow in qTStatus Andrew Burgess
2026-11-23 22:46 ` [PATCH 1/2] gdbserver: move local variable declarations inline in cmd_qtstatus Andrew Burgess
2026-11-23 22:46 ` [PATCH 2/2] gdbserver: fix buffer overflow " Andrew Burgess

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