gdb_server: Fix buffer size calculation for snprintf null terminator

The buffer size check was using len + 4 but snprintf requires additional
space for the null terminator. The snprintf call formats '#%02x' which
needs 4 bytes total (1 for '#', 2 for checksum, 1 for null terminator).

The original check of len + 4 was insufficient and could cause snprintf
to truncate the checksum and replace the last character with '\0',
leading to malformed GDB packets.

Fix by changing the buffer size check from len + 4 to len + 5 (1 for '$',
1 for '#', 2 for checksum, 1 for null terminator) to provide adequate space
for snprintf's null terminator.

Change-Id: Ibf8b3c3f5e4d5ac5be795b8e688e055453798afe
Signed-off-by: Ryan QIAN <jianghao.qian@hpmicro.com>
Reviewed-on: https://review.openocd.org/c/openocd/+/9117
Tested-by: jenkins
Reviewed-by: Tomas Vanek <vanekt@fbl.cz>
This commit is contained in:
Ryan QIAN
2025-09-10 12:23:26 +08:00
committed by Tomas Vanek
parent 874be7dc03
commit e10fb1e2a4

View File

@@ -474,7 +474,7 @@ static int gdb_put_packet_inner(struct connection *connection,
char local_buffer[1024];
local_buffer[0] = '$';
if ((size_t)len + 4 <= sizeof(local_buffer)) {
if ((size_t)len + 5 <= sizeof(local_buffer)) {
/* performance gain on smaller packets by only a single call to gdb_write() */
memcpy(local_buffer + 1, buffer, len++);
len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);