gdbserver: reject malformed agent expressions in gdb_parse_agent_expr

gdb_parse_agent_expr, defined in gdbserver/ax.cc, is called from four
different sites within gdbserver, two from mem-break.cc and two from
tracepoint.cc.

Within tracepoint.cc, gdb_parse_agent_expr is called to handle the 'X'
portion of a QTDP packet.  The 'X' portion describes agent expressions
used by tracepoints for both conditions and actions.

Within mem-break.cc, it's called to handle breakpoint conditions or
commands as part of a 'Z' packet.  These conditions or commands are
specified in a bytecode format identical to that used for agent
expressions for tracepoints.

The current implementation of gdb_parse_agent_expr contains no checks
about validity of the length specified in the portion of a packet that
represents an agent expression.  This takes the form "X<len>,<hex>".
(This is not an 'X' packet but, rather, a portion of the 'QTDP' packet
for tracepoints or 'Z0' packet for breakpoints.)  gdb_parse_agent_expr
allocates LEN bytes and asks hex2bin to convert that number of bytes,
but hex2bin stops at the end of the packet, leaving the end of the
buffer uninitialized.  For a tracepoint condition, that buffer is
later sent back to GDB in reply to qTfP/qTsP, which are used to
request tracepoint data.  Thus, using an overly large length can
provide access to uninitialized gdbserver heap memory, a potential
security concern.

The parse pointer is also advanced by 2 * LEN bytes regardless of how
much data was present, so callers continue parsing from a pointer that
can be far beyond the end of the packet; a large LEN crashes gdbserver.

Fix this by having gdb_parse_agent_expr return nullptr (representing
an error condition) when the specified length exceeds the amount of
hex data actually present.  This code also wasn't checking for the
mandated comma character in the packet syntax.  I added a check and
error return for that too.

The remainder of this patch to gdbserver consists of propagating the
error back to various points in the code where write_enn may be
called.  This causes the error to be sent as the reply to GDB.

For Z0 packet support, I removed two warning messages.  One concerned
a malformed condition and the other was about a malformed action
(command).  A malformed condition was discarded, making the breakpoint
unconditional; similarly, a malformed action was simply dropped.  The
warning message (which might not even be seen by the user) stated
these facts.  gdbserver now returns an error response for these cases.

The test case uses GDB's little-used "maintenance packet" command to
send bad packets to gdbserver.  This has been done not only for the
tracepoint related packets, but for the Z0 (set breakpoint) packet as
well.  Z0 used to silently drop malformed packets and set a breakpoint
without the (presumably intended, but malformed) condition or action.
It no longer does this.  Malformed conditions and actions within a
Z0 packet now cause an error to be returned.

While working on this patch, I spotted numerous other problems in
nearby code (e.g. memory leaks and lack of packet syntax checking).
I left these alone.  gdbserver desperately needs attention to fix
myriad problems.

This fixes the bug associated with CVE-2026-121996.

Regression tested on x86_64 Fedora 44.  The new test case was tested
on RISC-V Fedora 42, for which neither Z0 packets nor tracepoint
packets are implemented.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=34969

Approved-By: Andrew Burgess <aburgess@redhat.com>
diff --git a/gdb/testsuite/gdb.server/agent-expr-length.exp b/gdb/testsuite/gdb.server/agent-expr-length.exp
new file mode 100644
index 0000000..d9e1db7
--- /dev/null
+++ b/gdb/testsuite/gdb.server/agent-expr-length.exp
@@ -0,0 +1,215 @@
+# 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/>.
+
+# Send a variety of malformed Z0 and QTDP packets to gdbserver.  These
+# malformed packets could, at one time, crash gdbserver or provide access
+# to its memory.
+
+load_lib gdbserver-support.exp
+
+require allow_gdbserver_tests
+
+standard_testfile normal.c
+
+if {[build_executable "failed to prepare" $testfile $srcfile]} {
+    return
+}
+
+# Send a packet to gdbserver using "maintenance packet".  Returns the
+# response from gdbserver.
+proc maint_packet { packet testname } {
+    set answer ""
+    gdb_test_multiple "maintenance packet $packet" $testname {
+	-re -wrap {received: "([^"]*)"} {
+	    set answer $expect_out(1,string)
+	}
+    }
+    return $answer
+}
+
+# Do the routine things needed to set up gdbserver.
+proc prepare_server { } {
+    clean_restart $::testfile
+    gdb_test "disconnect" ".*"
+    gdbserver_run ""
+}
+
+# Send out Z0 / z0 (breakpoint) packets for this test.  Use "main" for the
+# address at which to place the breakpoint.
+proc test_Z0 {exp testname} {
+    with_test_prefix $testname {
+	prepare_server
+	set addr [format %x [get_hexadecimal_valueof "&main" 0]]
+
+	set result [maint_packet "Z0,$addr,1;$exp" "maint packet Z0"]
+	gdb_assert {[regexp {^E\d\d} $result]} "Z0 packet returns error"
+
+	# Check that a failed insert didn't leave a breakpoint.
+	set result [maint_packet "z0,$addr,1" "maint packet z0"]
+	gdb_assert {[regexp {^E\d\d} $result]} \
+	    "z0 packet confirms breakpoint was not inserted"
+    }
+}
+
+# Send/receive tracepoint related packets for this test.
+proc test_QTDP {cond action testname} {
+    with_test_prefix $testname {
+	prepare_server
+	set addr [format %x [get_hexadecimal_valueof "&main" 0]]
+
+	set result [maint_packet "QTinit" "maint packet QTinit"]
+	gdb_assert {$result eq "OK"} "QTinit packet returns OK"
+
+	set pcond ""
+	set pcont ""
+	if { $cond ne "" } {
+	    set pcond ":$cond"
+	}
+	if { $action ne "" } {
+	    set pcont "-"
+	}
+
+	set result \
+	    [maint_packet "QTDP:1:$addr:E:0:0$pcond$pcont" "maint packet QTDP"]
+	if {$pcond eq ""} {
+	    gdb_assert {$result eq "OK"} "QTDP packet returns OK"
+	} else {
+	    gdb_assert {[regexp {^E\d\d} $result]} "QTDP packet returns error"
+	}
+
+	if { $action ne "" } {
+	    set result [maint_packet "QTDP:-1:$addr:$action" \
+		"maint packet QTDP continuation"]
+	    gdb_assert {[regexp {^E\d\d} $result]} \
+		"QTDP continuation packet returns error"
+	}
+
+	set result [maint_packet "qTfP" "maint packet qTfP"]
+	gdb_assert {$result eq "l"} "tracepoint list is empty"
+    }
+}
+
+# Check whether gdbserver supports the Z0 packet; return 1 if so, otherwise
+# return 0 and show that tests involving Z0 packets are unsupported.
+proc check_Z0_breakpoint_support {} {
+    with_test_prefix "check Z0 support" {
+	prepare_server
+	set addr [format %x [get_hexadecimal_valueof "&main" 0]]
+
+	# The hex agent expression below pushes 1 onto the evaluation stack
+	# and then returns it.
+	set result [maint_packet "Z0,$addr,1;X03,220127" "maint packet Z0"]
+	if {$result eq ""} {
+	    unsupported "Z0 packets"
+	    return 0
+	}
+	gdb_assert {$result eq "OK"} "Z0 packet returns OK"
+
+	# Attempt to delete the breakpoint created above.  Probably
+	# overkill, but we'll note it as unsupported if it doesn't work.
+	set result [maint_packet "z0,$addr,1" "maint packet z0"]
+	if {$result eq ""} {
+	    unsupported "z0 packets"
+	    return 0
+	}
+	gdb_assert {$result eq "OK"} "z0 packet returns OK"
+
+	return 1
+    }
+}
+
+# Tracepoint support predicate; this one just checks whether QTinit works.
+# Return 0 and show an "unsupported" message if not supported; otherwise
+# return 1 when supported.
+proc check_tracepoint_support {} {
+    with_test_prefix "check tracepoint support" {
+	prepare_server
+	set addr [format %x [get_hexadecimal_valueof "&main" 0]]
+
+	set result [maint_packet "QTinit" "maint packet QTinit"]
+	if {$result eq ""} {
+	    unsupported "tracepoints"
+	    return 0
+	}
+
+	gdb_assert {$result eq "OK"} "QTinit packet returns OK"
+
+	# Check that a valid expression passes; the agent expression pushes
+	# 1 and returns it.
+	set result [maint_packet "QTDP:1:$addr:E:0:0:X03,220127" \
+	    "good maint packet QTDP"]
+	gdb_assert {$result eq "OK"} "good maint packet QTDP returns OK"
+
+	# Fetch the tracepoint list; it should contain the tracepoint
+	# defined above.
+	set result [maint_packet "qTfP" "maint packet qTfP"]
+	gdb_assert {[regexp {^T1:} $result]} "tracepoint list is not empty"
+	return 1
+    }
+}
+
+# Conditions for both Z0 and QTDP packets.  Note that "cc" and "ee" aren't
+# real opcodes.  This does not matter because each of these expressions is
+# malformed in some way.
+set large_cond "X20,cc"
+set huge_cond "X800000,cc"
+set no_comma_cond "X04"
+
+# Z0 commands:
+set large_exp "cmds:0,X20,ee"
+set huge_exp "cmds:0,X800000,ee"
+set no_comma_exp "cmds:0,X04"
+
+# QTDP actions:
+set large_action "X20,ee"
+set huge_action "X800000,ee"
+set no_comma_action "X04"
+
+if {[check_Z0_breakpoint_support]} {
+    with_test_prefix "breakpoint tests" {
+	test_Z0 $large_cond "over-long condition"
+	test_Z0 $huge_cond "massively over-long condition"
+	test_Z0 $no_comma_cond "missing comma before condition"
+	test_Z0 $large_exp "over-long expression"
+	test_Z0 $huge_exp "massively over-long expression"
+	test_Z0 $no_comma_exp "missing comma before expression"
+    }
+}
+
+if {[check_tracepoint_support]} {
+    with_test_prefix "tracepoint tests" {
+	test_QTDP $large_cond "" "over-long condition"
+	test_QTDP $huge_cond "" "massively over-long condition"
+	test_QTDP $no_comma_cond "" "missing comma before condition"
+
+	test_QTDP "" $large_action "over-long action"
+	test_QTDP "" $huge_action "massively over-long action"
+	test_QTDP "" $no_comma_action "missing comma before action"
+
+	test_QTDP $large_cond $large_action \
+	    "over-long condition and over-long action"
+	test_QTDP $large_cond $huge_action \
+	    "over-long condition and massively over-long action"
+	test_QTDP $large_cond $no_comma_action \
+	    "over-long condition and missing comma before action"
+
+	test_QTDP $huge_cond $large_action \
+	    "massively over-long condition and over-long action"
+	test_QTDP $huge_cond $huge_action \
+	    "massively over-long condition and massively over-long action"
+	test_QTDP $huge_cond $no_comma_action \
+	    "massively over-long condition and missing comma before action"
+    }
+}
diff --git a/gdbserver/ax.cc b/gdbserver/ax.cc
index 4993bed..f73a407 100644
--- a/gdbserver/ax.cc
+++ b/gdbserver/ax.cc
@@ -91,8 +91,7 @@
 
 #ifndef IN_PROCESS_AGENT
 
-/* The packet form of an agent expression consists of an 'X', number
-   of bytes in expression, a comma, and then the bytes.  */
+/* See ax.h.  */
 
 struct agent_expr *
 gdb_parse_agent_expr (const char **actparm)
@@ -103,7 +102,15 @@
 
   ++act;  /* skip the X */
   act = unpack_varlen_hex (act, &xlen);
-  ++act;  /* skip a comma */
+
+  if (*act != ',')
+    return nullptr;
+  ++act;  /* skip the comma */
+
+  /* Return error if provided length exceeds size of actual hex string.  */
+  if (xlen > ((ULONGEST) strspn (act, "0123456789abcdefABCDEF") / 2))
+    return nullptr;
+
   aexpr = XNEW (struct agent_expr);
   aexpr->length = xlen;
   aexpr->bytes = (unsigned char *) xmalloc (xlen);
diff --git a/gdbserver/ax.h b/gdbserver/ax.h
index 03882f4..7ad077f 100644
--- a/gdbserver/ax.h
+++ b/gdbserver/ax.h
@@ -48,7 +48,9 @@ struct agent_expr
 #ifndef IN_PROCESS_AGENT
 
 /* The packet form of an agent expression consists of an 'X', number
-   of bytes in expression, a comma, and then the bytes.  */
+   of bytes in expression, a comma, and then the bytes.  Parse one at
+   *ACTPARM, advancing *ACTPARM past it.  Return nullptr, leaving
+   *ACTPARM unchanged, if the expression is malformed.  */
 struct agent_expr *gdb_parse_agent_expr (const char **actparm);
 
 /* Release an agent expression.  */
diff --git a/gdbserver/mem-break.cc b/gdbserver/mem-break.cc
index 4e944ff..071f833 100644
--- a/gdbserver/mem-break.cc
+++ b/gdbserver/mem-break.cc
@@ -1205,10 +1205,7 @@
   cond = gdb_parse_agent_expr (&actparm);
 
   if (cond == NULL)
-    {
-      warning (_("Condition evaluation failed. Assuming unconditional."));
-      return 0;
-    }
+    return 0;
 
   add_condition_to_breakpoint (bp, cond);
 
@@ -1304,10 +1301,7 @@
   cmd = gdb_parse_agent_expr (&actparm);
 
   if (cmd == NULL)
-    {
-      warning (_("Command evaluation failed. Disabling."));
-      return 0;
-    }
+    return 0;
 
   add_commands_to_breakpoint (bp, cmd, persist);
 
diff --git a/gdbserver/server.cc b/gdbserver/server.cc
index df57542..9bb15d1 100644
--- a/gdbserver/server.cc
+++ b/gdbserver/server.cc
@@ -4753,17 +4753,20 @@
 
 /* Process options coming from Z packets for a breakpoint.  PACKET is
    the packet buffer.  *PACKET is updated to point to the first char
-   after the last processed option.  */
+   after the last processed option.  Return true on success and false
+   if caller should report an error.  */
 
-static void
+static bool
 process_point_options (struct gdb_breakpoint *bp, const char **packet)
 {
   const char *dataptr = *packet;
   int persist;
 
-  /* Check if data has the correct format.  */
+  /* Return success if the next character is not semicolon; the semicolon
+     introduces optional conditional and/or bytecode expressions to
+     evaluate/execute.  */
   if (*dataptr != ';')
-    return;
+    return true;
 
   dataptr++;
 
@@ -4777,7 +4780,7 @@
 	  /* Conditional expression.  */
 	  threads_debug_printf ("Found breakpoint condition.");
 	  if (!add_breakpoint_condition (bp, &dataptr))
-	    dataptr = strchrnul (dataptr, ';');
+	    return false;
 	}
       else if (startswith (dataptr, "cmds:"))
 	{
@@ -4785,8 +4788,9 @@
 	  threads_debug_printf ("Found breakpoint commands %s.", dataptr);
 	  persist = (*dataptr == '1');
 	  dataptr += 2;
-	  if (add_breakpoint_commands (bp, &dataptr, persist))
-	    dataptr = strchrnul (dataptr, ';');
+	  if (!add_breakpoint_commands (bp, &dataptr, persist))
+	    return false;
+	  dataptr = strchrnul (dataptr, ';');
 	}
       else
 	{
@@ -4797,6 +4801,7 @@
 	}
     }
   *packet = dataptr;
+  return true;
 }
 
 /* Event loop callback that handles a serial event.  The first byte in
@@ -5067,7 +5072,13 @@
 		   instead.  */
 		clear_breakpoint_conditions_and_commands (bp);
 		const char *options = dataptr;
-		process_point_options (bp, &options);
+		if (!process_point_options (bp, &options))
+		  {
+		    /* Error: remove breakpoint and write error.  */
+		    delete_gdb_breakpoint (type, addr, kind);
+		    write_enn (cs.own_buf);
+		    break;
+		  }
 	      }
 	  }
 	else
diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 6f65725..e7b09b8 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -1800,9 +1800,12 @@
 
 #endif
 
-/* Append another action to perform when the tracepoint triggers.  */
+/* Append another action to perform when the tracepoint triggers.
+   PACKET holds the action(s) from a QTDP packet.  Return true on
+   success, or false if an action is malformed, in which case the
+   caller should report an error.  */
 
-static void
+static bool
 add_tracepoint_action (struct tracepoint *tpoint, const char *packet)
 {
   const char *act;
@@ -1877,6 +1880,11 @@
 
 	    trace_debug ("Want to evaluate expression");
 	    xaction->expr = gdb_parse_agent_expr (&act);
+	    if (xaction->expr == nullptr)
+	      {
+		free (xaction);
+		return false;
+	      }
 	    break;
 	  }
 	default:
@@ -1916,6 +1924,7 @@
 	    = savestring (act_start, act - act_start);
 	}
     }
+  return true;
 }
 
 #endif
@@ -2404,6 +2413,13 @@
 	  else if (*packet == 'X')
 	    {
 	      tpoint->cond = gdb_parse_agent_expr (&packet);
+	      if (tpoint->cond == nullptr)
+		{
+		  trace_debug ("Malformed agent expression for conditional");
+		  write_enn (own_buf);
+		  remove_tracepoint (tpoint);
+		  return;
+		}
 	    }
 	  else if (*packet == '-')
 	    break;
@@ -2425,7 +2441,15 @@
 		   tpoint->step_count, tpoint->pass_count);
     }
   else if (tpoint)
-    add_tracepoint_action (tpoint, packet);
+    {
+      if (!add_tracepoint_action (tpoint, packet))
+	{
+	  trace_debug ("Malformed tracepoint action");
+	  write_enn (own_buf);
+	  remove_tracepoint (tpoint);
+	  return;
+	}
+    }
   else
     {
       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",