From: Andrew Burgess <aburgess@redhat.com>
To: Tom Tromey <tom@tromey.com>
Cc: gdb-patches@sourceware.org
Subject: Re: [PATCH 3/3] gdb/remote: improve error checking for 'p' packet reply
Date: Mon, 23 Nov 2026 16:44:27 +0000 [thread overview]
Message-ID: <xhuyffqwr7b10.fsf@aburgess-thinkpadp1gen8.rmtgb.csb> (raw)
In-Reply-To: <875wy5vrsa.fsf@tromey.com>
Tom Tromey <tom@tromey.com> writes:
>>>>>> "Andrew" == Andrew Burgess <aburgess@redhat.com> writes:
>
> Andrew> When building the outgoing packet use xsnprintf; this allows for
> Andrew> bounds checking as the packet is being written. The chances of the
> Andrew> outgoing packet overflowing are pretty slim, but using a bounded write
> Andrew> seems better than not, so let's do that.
>
> I suppose for this to assert we'd have to have a packet that's smaller
> than a register number and the register value. But I guess we
> anticipate that this can't really happen? Or is pathological enough
> that we don't care?
You are correct that for the xsnprintf to fail we'd need an absolutely
tiny packet buffer. I don't think we'd make it as far as sending a p
packet in that case, things like qSupported would have gone wrong before
we got here.
But also, I'm switching to xsnprintf because it's better than just
pushing content blindly into the buffer, so we really should check the
return value, it doesn't cost much.
I initially added something like:
int res = xsnprintf (...);
if (res < 0 && res >= get_remote_packet_size ())
error (_("..."));
But then I started writing a comment, and the comment was along this
lines of: this error will never trigger because ....
And we already have a construct for use when something will never
happen, gdb_assert. So then I changed the code to:
int res = xsnprintf (...);
gdb_assert (res > 0 && res < get_remote_packet_size ());
There's also a comment explaining why I used an assert rather than an if
and error.
>
> Andrew> + /* Otherwise, parse the register value from the hex string. */
> Andrew> + struct gdbarch *gdbarch = regcache->arch ();
> Andrew> + int reg_size = register_size (gdbarch, reg->regnum);
> Andrew> + gdb_byte *regp = (gdb_byte *) alloca (reg_size);
>
> I would prefer it if we didn't add new calls to alloca to the tree.
> I think alloca is bad and that generally we will not notice an extra
> allocation.
I switched this to gdb::byte_vector.
Let me know what you think of the updated patch below.
Thanks,
Andrew
---
commit c59492b533149b5ebe20bb0953f10a6179f8c266
Author: Andrew Burgess <aburgess@redhat.com>
Date: Sun Nov 8 20:37:32 2026 +0000
gdb/remote: improve error checking for 'p' packet reply
Improve the remote_target::fetch_register_using_p function (remote.c)
in a couple of ways.
When building the outgoing packet use xsnprintf; this allows for
bounds checking as the packet is being written. The chances of the
outgoing packet overflowing are pretty slim, but using a bounded write
seems better than not, so let's do that.
Next, when parsing the reply packet the result is written into a
buffer which is the size of the register being fetched. Unfortunately
the loop that reads the packet does not have any bounds checking,
which allows for buffer overflow. Convert the manual loop which calls
fromhex on each character to instead use hex2bin which allows a limit
to be applied to the number of bytes parsed; this prevents buffer
overflow. hex2bin returns the number of bytes parsed, which also
allows me to check for cases where the remote fails to supply all of
the expected bytes.
For testing I made use of the gdbserver option --disable-packet=gG
which I added in the previous commit. I ran the testsuite like this:
make check-gdb RUNTESTFLAGS="--target_board=native-gdbserver \
GDBSERVER='/path/to/patched/gdbserver --disable-packet=gG'"
I've also added a new test that makes use of the gdbreplay mechanism
to adjust the size of the returned register. This allows testing of
the two error cases: register value too short, and register value too
long.
As in the previous commit the trace related tests fail as the trace
functionality depends on the 'g' packet being supported, but otherwise
I saw no regressions after this commit.
diff --git a/gdb/remote.c b/gdb/remote.c
index c1560c28e6b..2d264168f59 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -9242,27 +9242,28 @@ int
remote_target::fetch_register_using_p (struct regcache *regcache,
packet_reg *reg)
{
- struct gdbarch *gdbarch = regcache->arch ();
- struct remote_state *rs = get_remote_state ();
- char *buf, *p;
- gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
- int i;
-
if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
return 0;
if (reg->pnum == -1)
return 0;
- p = rs->buf.data ();
- *p++ = 'p';
- p += hexnumstr (p, reg->pnum);
- *p++ = '\0';
+ /* Send the packet asking for the register. */
+ struct remote_state *rs = get_remote_state ();
+ int res = xsnprintf (rs->buf.data (), get_remote_packet_size (), "p%s",
+ phex_nz (reg->pnum, 0));
+
+ /* For writing a string into a buffer xsnprintf isn't going to return an
+ error. Nor can this overflow, a 'p' followed by an int register number
+ will always fit. */
+ gdb_assert (res > 0 && res < get_remote_packet_size ());
+
putpkt (rs->buf);
+
+ /* Read the reply. */
getpkt (&rs->buf);
- buf = rs->buf.data ();
-
+ /* Check the packet status. */
packet_result result = m_features.packet_ok (rs->buf, PACKET_p);
switch (result.status ())
{
@@ -9277,24 +9278,28 @@ remote_target::fetch_register_using_p (struct regcache *regcache,
}
/* If this register is unfetchable, tell the regcache. */
+ char *buf = rs->buf.data ();
if (buf[0] == 'x')
{
regcache->raw_supply (reg->regnum, NULL);
return 1;
}
- /* Otherwise, parse and supply the value. */
- p = buf;
- i = 0;
- while (p[0] != 0)
- {
- if (p[1] == 0)
- error (_("fetch_register_using_p: early buf termination"));
+ /* Otherwise, parse the register value from the hex string. */
+ struct gdbarch *gdbarch = regcache->arch ();
+ int reg_size = register_size (gdbarch, reg->regnum);
+ gdb::byte_vector regp (reg_size);
+ int bytes_converted = hex2bin (buf, regp.data (), reg_size);
- regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
- p += 2;
- }
- regcache->raw_supply (reg->regnum, regp);
+ /* Check the whole packet was parsed, and that the packet length matches
+ the register size. */
+ if (buf[bytes_converted * 2] != '\0' || bytes_converted != reg_size)
+ error (_("Remote 'p' packet reply for register %s is of unexpected "
+ "length (expected %d bytes): %s"),
+ gdbarch_register_name (gdbarch, reg->regnum), reg_size, buf);
+
+ /* Supply the value to the register cache. */
+ regcache->raw_supply (reg->regnum, regp.data ());
return 1;
}
diff --git a/gdb/testsuite/gdb.replay/p-packet.c b/gdb/testsuite/gdb.replay/p-packet.c
new file mode 100644
index 00000000000..6a0e311ef41
--- /dev/null
+++ b/gdb/testsuite/gdb.replay/p-packet.c
@@ -0,0 +1,22 @@
+/* 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/>. */
+
+int
+main (void)
+{
+ return 0;
+}
diff --git a/gdb/testsuite/gdb.replay/p-packet.exp b/gdb/testsuite/gdb.replay/p-packet.exp
new file mode 100644
index 00000000000..f59fc13faa2
--- /dev/null
+++ b/gdb/testsuite/gdb.replay/p-packet.exp
@@ -0,0 +1,213 @@
+# 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 error handling for the 'p' packet. Start gdbserver with the g/G
+# packets disabled. Start GDB, connect to the server, and then run 'info
+# registers', this will make use of the 'p' packet.
+#
+# Update the recorded logfile to replace the reply to the first 'p' packet,
+# the updated reply will be an invalid size.
+#
+# Replay the log and check that the 'info registers' gives a suitable error
+# message.
+
+load_lib gdbserver-support.exp
+load_lib gdbreplay-support.exp
+
+require allow_gdbserver_tests
+require has_gdbreplay
+
+standard_testfile
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile] } {
+ return
+}
+
+# Check that remote register 0 is a suitable size. The test could be
+# updated to handle other register sizes, but for now handle 4 or 8 byte
+# registers.
+set reg_size 0
+gdb_test_multiple "maint print remote-registers" "" -lbl {
+ -re "\r\n\\S+\\s+$::decimal\\s+$::decimal\\s+$::decimal\\s+($::decimal)\\s+\[^\r\n\]+\\s+0\\s+0\\s*(?=\r\n)" {
+ set reg_size $expect_out(1,string)
+ exp_continue
+ }
+
+ -re "\r\n$gdb_prompt $" {
+ pass $gdb_test_name
+ }
+}
+
+if { $reg_size != 4 && $reg_size != 8 } {
+ unsupported "remote register 0 is an unsupported size"
+ return
+}
+
+# Connect to gdbserver and run to a breakpoint in main, then use the 'info
+# registers' command. Record the remotelogfile into the REMOTELOG log
+# file.
+proc_with_prefix record_initial_logfile { remotelog } {
+ # Make sure we're disconnected, in case we're testing with an
+ # extended-remote board, therefore already connected.
+ gdb_test "disconnect" ".*"
+
+ gdb_test_no_output "set sysroot" \
+ "setting sysroot before starting gdbserver"
+
+ # Start gdbserver like:
+ # gdbserver :PORT ....
+ set res [gdbserver_start "--disable-packet=gG" $::binfile]
+ set gdbserver_protocol [lindex $res 0]
+ set gdbserver_gdbport [lindex $res 1]
+
+ gdb_test_no_output "set remotelogfile $remotelog" \
+ "setup remotelogfile"
+
+ # Connect to gdbserver.
+ if {![gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport] == 0} {
+ unsupported "couldn't start gdbserver"
+ return
+ }
+
+ # If we're connecting as 'remote' then we can't use 'runto'.
+ gdb_breakpoint main
+ gdb_continue_to_breakpoint "continuing to main"
+
+ gdb_test "info registers" ".*"
+}
+
+# Connect to gdbreplay using the REMOTELOG log file. Runs to a breakpoint in
+# main and then uses the 'info registers' command.
+proc_with_prefix replay_without_error { remotelog } {
+ clean_restart $::testfile
+
+ # Make sure we're disconnected, in case we're testing with an
+ # extended-remote board, therefore already connected.
+ gdb_test "disconnect" ".*"
+
+ gdb_test_no_output "set sysroot" "setting sysroot"
+
+ set res [gdbreplay_start $remotelog]
+ set gdbserver_protocol [lindex $res 0]
+ set gdbserver_gdbport [lindex $res 1]
+
+ # Connect to gdbreplay.
+ if {![gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport] == 0} {
+ unsupported "couldn't start gdbreplay"
+ return
+ }
+
+ gdb_breakpoint main
+ gdb_continue_to_breakpoint "continue to main"
+
+ gdb_test "info registers" ".*"
+}
+
+# Connect to gdbreplay using the REMOTELOG log file. Runs to a breakpoint in
+# main and then uses the 'info registers' command. Expect an error from the
+# 'info registers' command, the error will include the VALUE string.
+proc_with_prefix replay_with_error { remotelog value } {
+ clean_restart $::testfile
+
+ # Make sure we're disconnected, in case we're testing with an
+ # extended-remote board, therefore already connected.
+ gdb_test "disconnect" ".*"
+
+ gdb_test_no_output "set sysroot" "setting sysroot"
+
+ set res [gdbreplay_start $remotelog]
+ set gdbserver_protocol [lindex $res 0]
+ set gdbserver_gdbport [lindex $res 1]
+
+ # Connect to gdbreplay.
+ if {![gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport] == 0} {
+ unsupported "couldn't start gdbreplay"
+ return
+ }
+
+ gdb_breakpoint main
+ gdb_continue_to_breakpoint "continue to main"
+
+ gdb_test "info registers" \
+ "Remote 'p' packet reply for register \[^\r\n\]+ is of unexpected length \\(expected $::decimal bytes\\): $value" \
+ "info registers gives an error"
+}
+
+# Create a copy of file SRC into DST. While making the copy look for the
+# 'info registers' command. After the 'info registers' GDB will send a 'p'
+# packet, and the remote will send a reply.
+#
+# Rewrite the reply to the first 'p' packet, replacing the returned register
+# value with NEW_VALUE.
+proc create_modified_remote_logfile { src dst new_value } {
+ set dst_fd [open $dst w]
+ set src_fd [open $src r]
+
+ # State machine: 'init' -> 'info regs' -> 'p pkt' -> 'done'.
+ # 'init' -- before we find the "info registers" command.
+ # 'info regs' -- after seeing the "info registers" command, before
+ # finding the outbound 'p' packet.
+ # 'p pkt' -- after seeing the outbound 'p' packet, looking for the reply
+ # line.
+ # 'done' -- after finding and modifying the reply to the first 'p'
+ # packet.
+ set state "init"
+ while { [gets $src_fd line] != -1 } {
+ if { $state eq "init" } {
+ if { $line eq "c info registers" } {
+ set state "info regs"
+ }
+ } elseif { $state eq "info regs" } {
+ if { [regexp "^w \\\$p\[0-9a-f\]+#" $line] } {
+ set state "p pkt"
+ } else {
+ set state "done"
+ }
+ } elseif { $state eq "p pkt" } {
+ if { [regexp "^r \\\$\[0-9a-f\]+.*#" $line] } {
+ set line "r \$${new_value}"
+ }
+ set state "done"
+ }
+
+ puts $dst_fd $line
+ }
+
+ close $src_fd
+ close $dst_fd
+}
+
+# The replay log is placed in 'replay.log'.
+set remotelog [standard_output_file replay.log]
+
+record_initial_logfile $remotelog
+replay_without_error $remotelog
+
+# Create two modified logfiles. The first replaces a register with a 1 byte
+# value.
+set remotelog_short [standard_output_file replay-short.log]
+set short_value_str 00
+create_modified_remote_logfile $remotelog $remotelog_short $short_value_str
+with_test_prefix "with short register" {
+ replay_with_error $remotelog_short $short_value_str
+}
+
+# The second replaces a register with a 10 byte value.
+set remotelog_long [standard_output_file replay-long.log]
+set long_value_str 00000000000000000000
+create_modified_remote_logfile $remotelog $remotelog_long $long_value_str
+with_test_prefix "with long register" {
+ replay_with_error $remotelog_long $long_value_str
+}
prev parent reply other threads:[~2026-11-23 16:45 UTC|newest]
Thread overview: 8+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-09 15:35 [PATCH 0/3] gdb/remote: improve packet buffer checks for p packet Andrew Burgess
2026-11-09 15:35 ` [PATCH 1/3] gdbsupport: update comment on hex2bin Andrew Burgess
2026-11-09 16:49 ` Tom Tromey
2026-11-09 15:35 ` [PATCH 2/3] gdbserver: add support for p/P packets and flag to disable g/G packets Andrew Burgess
2026-11-09 17:16 ` Tom Tromey
2026-11-09 15:35 ` [PATCH 3/3] gdb/remote: improve error checking for 'p' packet reply Andrew Burgess
2026-11-09 17:27 ` Tom Tromey
2026-11-23 16:44 ` Andrew Burgess [this message]
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=xhuyffqwr7b10.fsf@aburgess-thinkpadp1gen8.rmtgb.csb \
--to=aburgess@redhat.com \
--cc=gdb-patches@sourceware.org \
--cc=tom@tromey.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox