server: gdb_server: check for out of memory and fix a memory leak

During GDB service start, check that memory is properly allocated
and if add_service() fails release the allocated memory.

While there, modify the code following the coding style.

Change-Id: Iebd1481a82f7391c110c5f6ad9878ba4abf052b3
Signed-off-by: Antonio Borneo <borneo.antonio@gmail.com>
Reviewed-on: https://review.openocd.org/c/openocd/+/9374
Tested-by: jenkins
Reviewed-by: Tomas Vanek <vanekt@fbl.cz>
This commit is contained in:
Antonio Borneo
2026-01-04 17:40:43 +01:00
parent 70d4ac0395
commit b10372f0d2

View File

@@ -3881,12 +3881,11 @@ static const struct service_driver gdb_service_driver = {
static int gdb_target_start(struct target *target, const char *port)
{
struct gdb_service *gdb_service;
int ret;
gdb_service = malloc(sizeof(struct gdb_service));
if (!gdb_service)
return -ENOMEM;
struct gdb_service *gdb_service = malloc(sizeof(struct gdb_service));
if (!gdb_service) {
LOG_ERROR("Out of memory");
return ERROR_FAIL;
}
LOG_TARGET_INFO(target, "starting gdb server on %s", port);
@@ -3895,17 +3894,22 @@ static int gdb_target_start(struct target *target, const char *port)
gdb_service->core[1] = -1;
target->gdb_service = gdb_service;
ret = add_service(&gdb_service_driver, port, target->gdb_max_connections, gdb_service);
/* initialize all targets gdb service with the same pointer */
{
struct target_list *head;
foreach_smp_target(head, target->smp_targets) {
struct target *curr = head->target;
if (curr != target)
curr->gdb_service = gdb_service;
}
int retval = add_service(&gdb_service_driver, port,
target->gdb_max_connections, gdb_service);
if (retval != ERROR_OK) {
free(gdb_service);
return retval;
}
return ret;
/* initialize all targets gdb service with the same pointer */
struct target_list *head;
foreach_smp_target(head, target->smp_targets) {
struct target *curr = head->target;
if (curr != target)
curr->gdb_service = gdb_service;
}
return ERROR_OK;
}
static int gdb_target_add_one(struct target *target)